repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
michaelliao/openweixin
wxapi/src/main/java/com/itranswarp/wxapi/message/ReceivedTextMessage.java
383
package com.itranswarp.wxapi.message; public class ReceivedTextMessage extends AbstractReceivedMessage { public final String MsgType = Message.TYPE_TEXT; public final String Content; ReceivedTextMessage(long CreateTime, String FromUserName, String ToUserName, long MsgId, String Content) { super(CreateTime, FromUserName, ToUserName, MsgId); this.Content = Content; } }
apache-2.0
aws/aws-sdk-java
aws-java-sdk-chimesdkmessaging/src/main/java/com/amazonaws/services/chimesdkmessaging/model/transform/ListChannelBansRequestProtocolMarshaller.java
2684
/* * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.chimesdkmessaging.model.transform; import javax.annotation.Generated; import com.amazonaws.SdkClientException; import com.amazonaws.Request; import com.amazonaws.http.HttpMethodName; import com.amazonaws.services.chimesdkmessaging.model.*; import com.amazonaws.transform.Marshaller; import com.amazonaws.protocol.*; import com.amazonaws.protocol.Protocol; import com.amazonaws.annotation.SdkInternalApi; /** * ListChannelBansRequest Marshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") @SdkInternalApi public class ListChannelBansRequestProtocolMarshaller implements Marshaller<Request<ListChannelBansRequest>, ListChannelBansRequest> { private static final OperationInfo SDK_OPERATION_BINDING = OperationInfo.builder().protocol(Protocol.REST_JSON).requestUri("/channels/{channelArn}/bans") .httpMethodName(HttpMethodName.GET).hasExplicitPayloadMember(false).hasPayloadMembers(false).serviceName("AmazonChimeSDKMessaging").build(); private final com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory; public ListChannelBansRequestProtocolMarshaller(com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory) { this.protocolFactory = protocolFactory; } public Request<ListChannelBansRequest> marshall(ListChannelBansRequest listChannelBansRequest) { if (listChannelBansRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { final ProtocolRequestMarshaller<ListChannelBansRequest> protocolMarshaller = protocolFactory.createProtocolMarshaller(SDK_OPERATION_BINDING, listChannelBansRequest); protocolMarshaller.startMarshalling(); ListChannelBansRequestMarshaller.getInstance().marshall(listChannelBansRequest, protocolMarshaller); return protocolMarshaller.finishMarshalling(); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
apache-2.0
joansmith/spring-boot
spring-boot/src/test/java/org/springframework/boot/web/servlet/view/velocity/EmbeddedVelocityViewResolverTests.java
3094
/* * Copyright 2012-2015 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.boot.web.servlet.view.velocity; import org.apache.struts.mock.MockServletContext; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.test.util.ReflectionTestUtils; import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; import org.springframework.web.servlet.view.velocity.VelocityConfigurer; import org.springframework.web.servlet.view.velocity.VelocityView; import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link EmbeddedVelocityViewResolver}. * * @author Phillip Webb */ public class EmbeddedVelocityViewResolverTests { @Test public void standardViewWithoutToolboxConfig() throws Exception { ApplicationContext context = loadContext(WithoutToolboxConfig.class); EmbeddedVelocityViewResolver resolver = context .getBean(EmbeddedVelocityViewResolver.class); Object viewClass = ReflectionTestUtils.getField(resolver, "viewClass"); assertThat(viewClass).isEqualTo(VelocityView.class); } @Test public void embeddedViewWithToolboxConfig() throws Exception { ApplicationContext context = loadContext(WithToolboxConfig.class); EmbeddedVelocityViewResolver resolver = context .getBean(EmbeddedVelocityViewResolver.class); Object viewClass = ReflectionTestUtils.getField(resolver, "viewClass"); assertThat(viewClass).isEqualTo(EmbeddedVelocityToolboxView.class); } private ApplicationContext loadContext(Class<?> config) { AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext(); context.setServletContext(new MockServletContext()); context.register(config); context.refresh(); return context; } @Configuration static class WithoutToolboxConfig { @Bean public EmbeddedVelocityViewResolver resolver() { return new EmbeddedVelocityViewResolver(); } @Bean public VelocityConfigurer velocityConfigurer() { return new VelocityConfigurer(); } } @Configuration static class WithToolboxConfig { @Bean public EmbeddedVelocityViewResolver resolver() { EmbeddedVelocityViewResolver resolver = new EmbeddedVelocityViewResolver(); resolver.setToolboxConfigLocation("/toolbox.xml"); return resolver; } @Bean public VelocityConfigurer velocityConfigurer() { return new VelocityConfigurer(); } } }
apache-2.0
ppiech/RxJava
src/main/java/rx/Observable.java
529933
/** * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See * the License for the specific language governing permissions and limitations under the License. */ package rx; import java.util.*; import java.util.concurrent.*; import rx.annotations.*; import rx.exceptions.*; import rx.functions.*; import rx.internal.operators.*; import rx.internal.producers.SingleProducer; import rx.internal.util.*; import rx.observables.*; import rx.observers.SafeSubscriber; import rx.plugins.*; import rx.schedulers.*; import rx.subscriptions.Subscriptions; /** * The Observable class that implements the Reactive Pattern. * <p> * This class provides methods for subscribing to the Observable as well as delegate methods to the various * Observers. * <p> * The documentation for this class makes use of marble diagrams. The following legend explains these diagrams: * <p> * <img width="640" height="301" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/legend.png" alt=""> * <p> * For more information see the <a href="http://reactivex.io/documentation/observable.html">ReactiveX * documentation</a>. * * @param <T> * the type of the items emitted by the Observable */ public class Observable<T> { final OnSubscribe<T> onSubscribe; /** * Creates an Observable with a Function to execute when it is subscribed to. * <p> * <em>Note:</em> Use {@link #create(OnSubscribe)} to create an Observable, instead of this constructor, * unless you specifically have a need for inheritance. * * @param f * {@link OnSubscribe} to be executed when {@link #subscribe(Subscriber)} is called */ protected Observable(OnSubscribe<T> f) { this.onSubscribe = f; } private static final RxJavaObservableExecutionHook hook = RxJavaPlugins.getInstance().getObservableExecutionHook(); /** * Returns an Observable that will execute the specified function when a {@link Subscriber} subscribes to * it. * <p> * <img width="640" height="200" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/create.png" alt=""> * <p> * Write the function you pass to {@code create} so that it behaves as an Observable: It should invoke the * Subscriber's {@link Subscriber#onNext onNext}, {@link Subscriber#onError onError}, and * {@link Subscriber#onCompleted onCompleted} methods appropriately. * <p> * A well-formed Observable must invoke either the Subscriber's {@code onCompleted} method exactly once or * its {@code onError} method exactly once. * <p> * See <a href="http://go.microsoft.com/fwlink/?LinkID=205219">Rx Design Guidelines (PDF)</a> for detailed * information. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code create} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param <T> * the type of the items that this Observable emits * @param f * a function that accepts an {@code Subscriber<T>}, and invokes its {@code onNext}, * {@code onError}, and {@code onCompleted} methods as appropriate * @return an Observable that, when a {@link Subscriber} subscribes to it, will execute the specified * function * @see <a href="http://reactivex.io/documentation/operators/create.html">ReactiveX operators documentation: Create</a> */ public final static <T> Observable<T> create(OnSubscribe<T> f) { return new Observable<T>(hook.onCreate(f)); } /** * Invoked when Observable.subscribe is called. */ public interface OnSubscribe<T> extends Action1<Subscriber<? super T>> { // cover for generics insanity } /** * Operator function for lifting into an Observable. */ public interface Operator<R, T> extends Func1<Subscriber<? super R>, Subscriber<? super T>> { // cover for generics insanity } /** * Passes all emitted values from this Observable to the provided conversion function to be collected and * returned as a single value. Note that it is legal for a conversion function to return an Observable * (enabling chaining). * * @param conversion a function that converts from this {@code Observable<T>} to an {@code R} * @return an instance of R created by the provided conversion function * @since (if this graduates from Experimental/Beta to supported, replace this parenthetical with the release number) */ @Experimental public <R> R extend(Func1<? super OnSubscribe<T>, ? extends R> conversion) { return conversion.call(new OnSubscribe<T>() { @Override public void call(Subscriber<? super T> subscriber) { subscriber.add(Observable.subscribe(subscriber, Observable.this)); }}); } /** * Lifts a function to the current Observable and returns a new Observable that when subscribed to will pass * the values of the current Observable through the Operator function. * <p> * In other words, this allows chaining Observers together on an Observable for acting on the values within * the Observable. * <p> {@code * observable.map(...).filter(...).take(5).lift(new OperatorA()).lift(new OperatorB(...)).subscribe() * } * <p> * If the operator you are creating is designed to act on the individual items emitted by a source * Observable, use {@code lift}. If your operator is designed to transform the source Observable as a whole * (for instance, by applying a particular set of existing RxJava operators to it) use {@link #compose}. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code lift} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param operator the Operator that implements the Observable-operating function to be applied to the source * Observable * @return an Observable that is the result of applying the lifted Operator to the source Observable * @see <a href="https://github.com/ReactiveX/RxJava/wiki/Implementing-Your-Own-Operators">RxJava wiki: Implementing Your Own Operators</a> */ public final <R> Observable<R> lift(final Operator<? extends R, ? super T> operator) { return new Observable<R>(new OnSubscribe<R>() { @Override public void call(Subscriber<? super R> o) { try { Subscriber<? super T> st = hook.onLift(operator).call(o); try { // new Subscriber created and being subscribed with so 'onStart' it st.onStart(); onSubscribe.call(st); } catch (Throwable e) { // localized capture of errors rather than it skipping all operators // and ending up in the try/catch of the subscribe method which then // prevents onErrorResumeNext and other similar approaches to error handling if (e instanceof OnErrorNotImplementedException) { throw (OnErrorNotImplementedException) e; } st.onError(e); } } catch (Throwable e) { if (e instanceof OnErrorNotImplementedException) { throw (OnErrorNotImplementedException) e; } // if the lift function failed all we can do is pass the error to the final Subscriber // as we don't have the operator available to us o.onError(e); } } }); } /** * Transform an Observable by applying a particular Transformer function to it. * <p> * This method operates on the Observable itself whereas {@link #lift} operates on the Observable's * Subscribers or Observers. * <p> * If the operator you are creating is designed to act on the individual items emitted by a source * Observable, use {@link #lift}. If your operator is designed to transform the source Observable as a whole * (for instance, by applying a particular set of existing RxJava operators to it) use {@code compose}. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code compose} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param transformer implements the function that transforms the source Observable * @return the source Observable, transformed by the transformer function * @see <a href="https://github.com/ReactiveX/RxJava/wiki/Implementing-Your-Own-Operators">RxJava wiki: Implementing Your Own Operators</a> */ @SuppressWarnings("unchecked") public <R> Observable<R> compose(Transformer<? super T, ? extends R> transformer) { return ((Transformer<T, R>) transformer).call(this); } /** * Transformer function used by {@link #compose}. * @warn more complete description needed */ public interface Transformer<T, R> extends Func1<Observable<T>, Observable<R>> { // cover for generics insanity } /** * Returns a Single that emits the single item emitted by the source Observable, if that Observable * emits only a single item. If the source Observable emits more than one item or no items, notify of an * {@code IllegalArgumentException} or {@code NoSuchElementException} respectively. * <p> * <img width="640" height="295" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.toSingle.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code toSingle} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @return a Single that emits the single item emitted by the source Observable * @throws IllegalArgumentException * if the source observable emits more than one item * @throws NoSuchElementException * if the source observable emits no items * @see <a href="http://reactivex.io/documentation/single.html">ReactiveX documentation: Single</a> * @since (if this graduates from Experimental/Beta to supported, replace this parenthetical with the release number) */ @Experimental public Single<T> toSingle() { return new Single<T>(OnSubscribeSingle.create(this)); } /* ********************************************************************************************************* * Operators Below Here * ********************************************************************************************************* */ /** * Mirrors the one Observable in an Iterable of several Observables that first either emits an item or sends * a termination notification. * <p> * <img width="640" height="385" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/amb.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code amb} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param sources * an Iterable of Observable sources competing to react first * @return an Observable that emits the same sequence as whichever of the source Observables first * emitted an item or sent a termination notification * @see <a href="http://reactivex.io/documentation/operators/amb.html">ReactiveX operators documentation: Amb</a> */ public final static <T> Observable<T> amb(Iterable<? extends Observable<? extends T>> sources) { return create(OnSubscribeAmb.amb(sources)); } /** * Given two Observables, mirrors the one that first either emits an item or sends a termination * notification. * <p> * <img width="640" height="385" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/amb.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code amb} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param o1 * an Observable competing to react first * @param o2 * an Observable competing to react first * @return an Observable that emits the same sequence as whichever of the source Observables first * emitted an item or sent a termination notification * @see <a href="http://reactivex.io/documentation/operators/amb.html">ReactiveX operators documentation: Amb</a> */ public final static <T> Observable<T> amb(Observable<? extends T> o1, Observable<? extends T> o2) { return create(OnSubscribeAmb.amb(o1, o2)); } /** * Given three Observables, mirrors the one that first either emits an item or sends a termination * notification. * <p> * <img width="640" height="385" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/amb.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code amb} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param o1 * an Observable competing to react first * @param o2 * an Observable competing to react first * @param o3 * an Observable competing to react first * @return an Observable that emits the same sequence as whichever of the source Observables first * emitted an item or sent a termination notification * @see <a href="http://reactivex.io/documentation/operators/amb.html">ReactiveX operators documentation: Amb</a> */ public final static <T> Observable<T> amb(Observable<? extends T> o1, Observable<? extends T> o2, Observable<? extends T> o3) { return create(OnSubscribeAmb.amb(o1, o2, o3)); } /** * Given four Observables, mirrors the one that first either emits an item or sends a termination * notification. * <p> * <img width="640" height="385" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/amb.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code amb} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param o1 * an Observable competing to react first * @param o2 * an Observable competing to react first * @param o3 * an Observable competing to react first * @param o4 * an Observable competing to react first * @return an Observable that emits the same sequence as whichever of the source Observables first * emitted an item or sent a termination notification * @see <a href="http://reactivex.io/documentation/operators/amb.html">ReactiveX operators documentation: Amb</a> */ public final static <T> Observable<T> amb(Observable<? extends T> o1, Observable<? extends T> o2, Observable<? extends T> o3, Observable<? extends T> o4) { return create(OnSubscribeAmb.amb(o1, o2, o3, o4)); } /** * Given five Observables, mirrors the one that first either emits an item or sends a termination * notification. * <p> * <img width="640" height="385" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/amb.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code amb} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param o1 * an Observable competing to react first * @param o2 * an Observable competing to react first * @param o3 * an Observable competing to react first * @param o4 * an Observable competing to react first * @param o5 * an Observable competing to react first * @return an Observable that emits the same sequence as whichever of the source Observables first * emitted an item or sent a termination notification * @see <a href="http://reactivex.io/documentation/operators/amb.html">ReactiveX operators documentation: Amb</a> */ public final static <T> Observable<T> amb(Observable<? extends T> o1, Observable<? extends T> o2, Observable<? extends T> o3, Observable<? extends T> o4, Observable<? extends T> o5) { return create(OnSubscribeAmb.amb(o1, o2, o3, o4, o5)); } /** * Given six Observables, mirrors the one that first either emits an item or sends a termination * notification. * <p> * <img width="640" height="385" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/amb.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code amb} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param o1 * an Observable competing to react first * @param o2 * an Observable competing to react first * @param o3 * an Observable competing to react first * @param o4 * an Observable competing to react first * @param o5 * an Observable competing to react first * @param o6 * an Observable competing to react first * @return an Observable that emits the same sequence as whichever of the source Observables first * emitted an item or sent a termination notification * @see <a href="http://reactivex.io/documentation/operators/amb.html">ReactiveX operators documentation: Amb</a> */ public final static <T> Observable<T> amb(Observable<? extends T> o1, Observable<? extends T> o2, Observable<? extends T> o3, Observable<? extends T> o4, Observable<? extends T> o5, Observable<? extends T> o6) { return create(OnSubscribeAmb.amb(o1, o2, o3, o4, o5, o6)); } /** * Given seven Observables, mirrors the one that first either emits an item or sends a termination * notification. * <p> * <img width="640" height="385" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/amb.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code amb} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param o1 * an Observable competing to react first * @param o2 * an Observable competing to react first * @param o3 * an Observable competing to react first * @param o4 * an Observable competing to react first * @param o5 * an Observable competing to react first * @param o6 * an Observable competing to react first * @param o7 * an Observable competing to react first * @return an Observable that emits the same sequence as whichever of the source Observables first * emitted an item or sent a termination notification * @see <a href="http://reactivex.io/documentation/operators/amb.html">ReactiveX operators documentation: Amb</a> */ public final static <T> Observable<T> amb(Observable<? extends T> o1, Observable<? extends T> o2, Observable<? extends T> o3, Observable<? extends T> o4, Observable<? extends T> o5, Observable<? extends T> o6, Observable<? extends T> o7) { return create(OnSubscribeAmb.amb(o1, o2, o3, o4, o5, o6, o7)); } /** * Given eight Observables, mirrors the one that first either emits an item or sends a termination * notification. * <p> * <img width="640" height="385" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/amb.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code amb} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param o1 * an Observable competing to react first * @param o2 * an Observable competing to react first * @param o3 * an Observable competing to react first * @param o4 * an Observable competing to react first * @param o5 * an Observable competing to react first * @param o6 * an Observable competing to react first * @param o7 * an Observable competing to react first * @param o8 * an observable competing to react first * @return an Observable that emits the same sequence as whichever of the source Observables first * emitted an item or sent a termination notification * @see <a href="http://reactivex.io/documentation/operators/amb.html">ReactiveX operators documentation: Amb</a> */ public final static <T> Observable<T> amb(Observable<? extends T> o1, Observable<? extends T> o2, Observable<? extends T> o3, Observable<? extends T> o4, Observable<? extends T> o5, Observable<? extends T> o6, Observable<? extends T> o7, Observable<? extends T> o8) { return create(OnSubscribeAmb.amb(o1, o2, o3, o4, o5, o6, o7, o8)); } /** * Given nine Observables, mirrors the one that first either emits an item or sends a termination * notification. * <p> * <img width="640" height="385" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/amb.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code amb} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param o1 * an Observable competing to react first * @param o2 * an Observable competing to react first * @param o3 * an Observable competing to react first * @param o4 * an Observable competing to react first * @param o5 * an Observable competing to react first * @param o6 * an Observable competing to react first * @param o7 * an Observable competing to react first * @param o8 * an Observable competing to react first * @param o9 * an Observable competing to react first * @return an Observable that emits the same sequence as whichever of the source Observables first * emitted an item or sent a termination notification * @see <a href="http://reactivex.io/documentation/operators/amb.html">ReactiveX operators documentation: Amb</a> */ public final static <T> Observable<T> amb(Observable<? extends T> o1, Observable<? extends T> o2, Observable<? extends T> o3, Observable<? extends T> o4, Observable<? extends T> o5, Observable<? extends T> o6, Observable<? extends T> o7, Observable<? extends T> o8, Observable<? extends T> o9) { return create(OnSubscribeAmb.amb(o1, o2, o3, o4, o5, o6, o7, o8, o9)); } /** * Combines two source Observables by emitting an item that aggregates the latest values of each of the * source Observables each time an item is received from either of the source Observables, 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/combineLatest.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code combineLatest} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param o1 * the first source Observable * @param o2 * the second source Observable * @param combineFunction * the aggregation function used to combine the items emitted by the source Observables * @return an Observable that emits items that are the result of combining the items emitted by the source * Observables by means of the given aggregation function * @see <a href="http://reactivex.io/documentation/operators/combinelatest.html">ReactiveX operators documentation: CombineLatest</a> */ @SuppressWarnings("unchecked") public static final <T1, T2, R> Observable<R> combineLatest(Observable<? extends T1> o1, Observable<? extends T2> o2, Func2<? super T1, ? super T2, ? extends R> combineFunction) { return combineLatest(Arrays.asList(o1, o2), Functions.fromFunc(combineFunction)); } /** * Combines three source Observables by emitting an item that aggregates the latest values of each of the * source Observables each time an item is received from any of the source Observables, 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/combineLatest.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code combineLatest} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param o1 * the first source Observable * @param o2 * the second source Observable * @param o3 * the third source Observable * @param combineFunction * the aggregation function used to combine the items emitted by the source Observables * @return an Observable that emits items that are the result of combining the items emitted by the source * Observables by means of the given aggregation function * @see <a href="http://reactivex.io/documentation/operators/combinelatest.html">ReactiveX operators documentation: CombineLatest</a> */ @SuppressWarnings("unchecked") public static final <T1, T2, T3, R> Observable<R> combineLatest(Observable<? extends T1> o1, Observable<? extends T2> o2, Observable<? extends T3> o3, Func3<? super T1, ? super T2, ? super T3, ? extends R> combineFunction) { return combineLatest(Arrays.asList(o1, o2, o3), Functions.fromFunc(combineFunction)); } /** * Combines four source Observables by emitting an item that aggregates the latest values of each of the * source Observables each time an item is received from any of the source Observables, 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/combineLatest.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code combineLatest} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param o1 * the first source Observable * @param o2 * the second source Observable * @param o3 * the third source Observable * @param o4 * the fourth source Observable * @param combineFunction * the aggregation function used to combine the items emitted by the source Observables * @return an Observable that emits items that are the result of combining the items emitted by the source * Observables by means of the given aggregation function * @see <a href="http://reactivex.io/documentation/operators/combinelatest.html">ReactiveX operators documentation: CombineLatest</a> */ @SuppressWarnings("unchecked") public static final <T1, T2, T3, T4, R> Observable<R> combineLatest(Observable<? extends T1> o1, Observable<? extends T2> o2, Observable<? extends T3> o3, Observable<? extends T4> o4, Func4<? super T1, ? super T2, ? super T3, ? super T4, ? extends R> combineFunction) { return combineLatest(Arrays.asList(o1, o2, o3, o4), Functions.fromFunc(combineFunction)); } /** * Combines five source Observables by emitting an item that aggregates the latest values of each of the * source Observables each time an item is received from any of the source Observables, 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/combineLatest.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code combineLatest} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param o1 * the first source Observable * @param o2 * the second source Observable * @param o3 * the third source Observable * @param o4 * the fourth source Observable * @param o5 * the fifth source Observable * @param combineFunction * the aggregation function used to combine the items emitted by the source Observables * @return an Observable that emits items that are the result of combining the items emitted by the source * Observables by means of the given aggregation function * @see <a href="http://reactivex.io/documentation/operators/combinelatest.html">ReactiveX operators documentation: CombineLatest</a> */ @SuppressWarnings("unchecked") public static final <T1, T2, T3, T4, T5, R> Observable<R> combineLatest(Observable<? extends T1> o1, Observable<? extends T2> o2, Observable<? extends T3> o3, Observable<? extends T4> o4, Observable<? extends T5> o5, Func5<? super T1, ? super T2, ? super T3, ? super T4, ? super T5, ? extends R> combineFunction) { return combineLatest(Arrays.asList(o1, o2, o3, o4, o5), Functions.fromFunc(combineFunction)); } /** * Combines six source Observables by emitting an item that aggregates the latest values of each of the * source Observables each time an item is received from any of the source Observables, 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/combineLatest.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code combineLatest} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param o1 * the first source Observable * @param o2 * the second source Observable * @param o3 * the third source Observable * @param o4 * the fourth source Observable * @param o5 * the fifth source Observable * @param o6 * the sixth source Observable * @param combineFunction * the aggregation function used to combine the items emitted by the source Observables * @return an Observable that emits items that are the result of combining the items emitted by the source * Observables by means of the given aggregation function * @see <a href="http://reactivex.io/documentation/operators/combinelatest.html">ReactiveX operators documentation: CombineLatest</a> */ @SuppressWarnings("unchecked") public static final <T1, T2, T3, T4, T5, T6, R> Observable<R> combineLatest(Observable<? extends T1> o1, Observable<? extends T2> o2, Observable<? extends T3> o3, Observable<? extends T4> o4, Observable<? extends T5> o5, Observable<? extends T6> o6, Func6<? super T1, ? super T2, ? super T3, ? super T4, ? super T5, ? super T6, ? extends R> combineFunction) { return combineLatest(Arrays.asList(o1, o2, o3, o4, o5, o6), Functions.fromFunc(combineFunction)); } /** * Combines seven source Observables by emitting an item that aggregates the latest values of each of the * source Observables each time an item is received from any of the source Observables, 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/combineLatest.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code combineLatest} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param o1 * the first source Observable * @param o2 * the second source Observable * @param o3 * the third source Observable * @param o4 * the fourth source Observable * @param o5 * the fifth source Observable * @param o6 * the sixth source Observable * @param o7 * the seventh source Observable * @param combineFunction * the aggregation function used to combine the items emitted by the source Observables * @return an Observable that emits items that are the result of combining the items emitted by the source * Observables by means of the given aggregation function * @see <a href="http://reactivex.io/documentation/operators/combinelatest.html">ReactiveX operators documentation: CombineLatest</a> */ @SuppressWarnings("unchecked") public static final <T1, T2, T3, T4, T5, T6, T7, R> Observable<R> combineLatest(Observable<? extends T1> o1, Observable<? extends T2> o2, Observable<? extends T3> o3, Observable<? extends T4> o4, Observable<? extends T5> o5, Observable<? extends T6> o6, Observable<? extends T7> o7, Func7<? super T1, ? super T2, ? super T3, ? super T4, ? super T5, ? super T6, ? super T7, ? extends R> combineFunction) { return combineLatest(Arrays.asList(o1, o2, o3, o4, o5, o6, o7), Functions.fromFunc(combineFunction)); } /** * Combines eight source Observables by emitting an item that aggregates the latest values of each of the * source Observables each time an item is received from any of the source Observables, 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/combineLatest.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code combineLatest} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param o1 * the first source Observable * @param o2 * the second source Observable * @param o3 * the third source Observable * @param o4 * the fourth source Observable * @param o5 * the fifth source Observable * @param o6 * the sixth source Observable * @param o7 * the seventh source Observable * @param o8 * the eighth source Observable * @param combineFunction * the aggregation function used to combine the items emitted by the source Observables * @return an Observable that emits items that are the result of combining the items emitted by the source * Observables by means of the given aggregation function * @see <a href="http://reactivex.io/documentation/operators/combinelatest.html">ReactiveX operators documentation: CombineLatest</a> */ @SuppressWarnings("unchecked") public static final <T1, T2, T3, T4, T5, T6, T7, T8, R> Observable<R> combineLatest(Observable<? extends T1> o1, Observable<? extends T2> o2, Observable<? extends T3> o3, Observable<? extends T4> o4, Observable<? extends T5> o5, Observable<? extends T6> o6, Observable<? extends T7> o7, Observable<? extends T8> o8, Func8<? super T1, ? super T2, ? super T3, ? super T4, ? super T5, ? super T6, ? super T7, ? super T8, ? extends R> combineFunction) { return combineLatest(Arrays.asList(o1, o2, o3, o4, o5, o6, o7, o8), Functions.fromFunc(combineFunction)); } /** * Combines nine source Observables by emitting an item that aggregates the latest values of each of the * source Observables each time an item is received from any of the source Observables, 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/combineLatest.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code combineLatest} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param o1 * the first source Observable * @param o2 * the second source Observable * @param o3 * the third source Observable * @param o4 * the fourth source Observable * @param o5 * the fifth source Observable * @param o6 * the sixth source Observable * @param o7 * the seventh source Observable * @param o8 * the eighth source Observable * @param o9 * the ninth source Observable * @param combineFunction * the aggregation function used to combine the items emitted by the source Observables * @return an Observable that emits items that are the result of combining the items emitted by the source * Observables by means of the given aggregation function * @see <a href="http://reactivex.io/documentation/operators/combinelatest.html">ReactiveX operators documentation: CombineLatest</a> */ @SuppressWarnings("unchecked") public static final <T1, T2, T3, T4, T5, T6, T7, T8, T9, R> Observable<R> combineLatest(Observable<? extends T1> o1, Observable<? extends T2> o2, Observable<? extends T3> o3, Observable<? extends T4> o4, Observable<? extends T5> o5, Observable<? extends T6> o6, Observable<? extends T7> o7, Observable<? extends T8> o8, Observable<? extends T9> o9, Func9<? super T1, ? super T2, ? super T3, ? super T4, ? super T5, ? super T6, ? super T7, ? super T8, ? super T9, ? extends R> combineFunction) { return combineLatest(Arrays.asList(o1, o2, o3, o4, o5, o6, o7, o8, o9), Functions.fromFunc(combineFunction)); } /** * Combines a list of source Observables by emitting an item that aggregates the latest values of each of * the source Observables each time an item is received from any of the source Observables, where this * aggregation is defined by a specified function. * <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 list of source Observables * @param combineFunction * the aggregation function used to combine the items emitted by the source Observables * @return an Observable that emits items that are the result of combining the items emitted by the source * Observables by means of the given aggregation function * @see <a href="http://reactivex.io/documentation/operators/combinelatest.html">ReactiveX operators documentation: CombineLatest</a> */ public static final <T, R> Observable<R> combineLatest(List<? extends Observable<? extends T>> sources, FuncN<? extends R> combineFunction) { return create(new OnSubscribeCombineLatest<T, R>(sources, combineFunction)); } /** * Returns an Observable that emits the items emitted by each of the Observables emitted by the source * Observable, 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.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code concat} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param observables * an Observable that emits Observables * @return an Observable that emits items all of the items emitted by the Observables emitted by * {@code observables}, one after the other, without interleaving them * @see <a href="http://reactivex.io/documentation/operators/concat.html">ReactiveX operators documentation: Concat</a> */ public final static <T> Observable<T> concat(Observable<? extends Observable<? extends T>> observables) { return observables.lift(OperatorConcat.<T>instance()); } /** * Returns an Observable that emits the items emitted by two Observables, 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.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code concat} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param t1 * an Observable to be concatenated * @param t2 * an Observable to be concatenated * @return an Observable that emits items emitted by the two source Observables, one after the other, * without interleaving them * @see <a href="http://reactivex.io/documentation/operators/concat.html">ReactiveX operators documentation: Concat</a> */ public final static <T> Observable<T> concat(Observable<? extends T> t1, Observable<? extends T> t2) { return concat(just(t1, t2)); } /** * Returns an Observable that emits the items emitted by three Observables, 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.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code concat} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param t1 * an Observable to be concatenated * @param t2 * an Observable to be concatenated * @param t3 * an Observable to be concatenated * @return an Observable that emits items emitted by the three source Observables, one after the other, * without interleaving them * @see <a href="http://reactivex.io/documentation/operators/concat.html">ReactiveX operators documentation: Concat</a> */ public final static <T> Observable<T> concat(Observable<? extends T> t1, Observable<? extends T> t2, Observable<? extends T> t3) { return concat(just(t1, t2, t3)); } /** * Returns an Observable that emits the items emitted by four Observables, 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.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code concat} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param t1 * an Observable to be concatenated * @param t2 * an Observable to be concatenated * @param t3 * an Observable to be concatenated * @param t4 * an Observable to be concatenated * @return an Observable that emits items emitted by the four source Observables, one after the other, * without interleaving them * @see <a href="http://reactivex.io/documentation/operators/concat.html">ReactiveX operators documentation: Concat</a> */ public final static <T> Observable<T> concat(Observable<? extends T> t1, Observable<? extends T> t2, Observable<? extends T> t3, Observable<? extends T> t4) { return concat(just(t1, t2, t3, t4)); } /** * Returns an Observable that emits the items emitted by five Observables, 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.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code concat} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param t1 * an Observable to be concatenated * @param t2 * an Observable to be concatenated * @param t3 * an Observable to be concatenated * @param t4 * an Observable to be concatenated * @param t5 * an Observable to be concatenated * @return an Observable that emits items emitted by the five source Observables, one after the other, * without interleaving them * @see <a href="http://reactivex.io/documentation/operators/concat.html">ReactiveX operators documentation: Concat</a> */ public final static <T> Observable<T> concat(Observable<? extends T> t1, Observable<? extends T> t2, Observable<? extends T> t3, Observable<? extends T> t4, Observable<? extends T> t5) { return concat(just(t1, t2, t3, t4, t5)); } /** * Returns an Observable that emits the items emitted by six Observables, 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.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code concat} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param t1 * an Observable to be concatenated * @param t2 * an Observable to be concatenated * @param t3 * an Observable to be concatenated * @param t4 * an Observable to be concatenated * @param t5 * an Observable to be concatenated * @param t6 * an Observable to be concatenated * @return an Observable that emits items emitted by the six source Observables, one after the other, * without interleaving them * @see <a href="http://reactivex.io/documentation/operators/concat.html">ReactiveX operators documentation: Concat</a> */ public final static <T> Observable<T> concat(Observable<? extends T> t1, Observable<? extends T> t2, Observable<? extends T> t3, Observable<? extends T> t4, Observable<? extends T> t5, Observable<? extends T> t6) { return concat(just(t1, t2, t3, t4, t5, t6)); } /** * Returns an Observable that emits the items emitted by seven Observables, 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.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code concat} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param t1 * an Observable to be concatenated * @param t2 * an Observable to be concatenated * @param t3 * an Observable to be concatenated * @param t4 * an Observable to be concatenated * @param t5 * an Observable to be concatenated * @param t6 * an Observable to be concatenated * @param t7 * an Observable to be concatenated * @return an Observable that emits items emitted by the seven source Observables, one after the other, * without interleaving them * @see <a href="http://reactivex.io/documentation/operators/concat.html">ReactiveX operators documentation: Concat</a> */ public final static <T> Observable<T> concat(Observable<? extends T> t1, Observable<? extends T> t2, Observable<? extends T> t3, Observable<? extends T> t4, Observable<? extends T> t5, Observable<? extends T> t6, Observable<? extends T> t7) { return concat(just(t1, t2, t3, t4, t5, t6, t7)); } /** * Returns an Observable that emits the items emitted by eight Observables, 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.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code concat} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param t1 * an Observable to be concatenated * @param t2 * an Observable to be concatenated * @param t3 * an Observable to be concatenated * @param t4 * an Observable to be concatenated * @param t5 * an Observable to be concatenated * @param t6 * an Observable to be concatenated * @param t7 * an Observable to be concatenated * @param t8 * an Observable to be concatenated * @return an Observable that emits items emitted by the eight source Observables, one after the other, * without interleaving them * @see <a href="http://reactivex.io/documentation/operators/concat.html">ReactiveX operators documentation: Concat</a> */ public final static <T> Observable<T> concat(Observable<? extends T> t1, Observable<? extends T> t2, Observable<? extends T> t3, Observable<? extends T> t4, Observable<? extends T> t5, Observable<? extends T> t6, Observable<? extends T> t7, Observable<? extends T> t8) { return concat(just(t1, t2, t3, t4, t5, t6, t7, t8)); } /** * Returns an Observable that emits the items emitted by nine Observables, 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.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code concat} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param t1 * an Observable to be concatenated * @param t2 * an Observable to be concatenated * @param t3 * an Observable to be concatenated * @param t4 * an Observable to be concatenated * @param t5 * an Observable to be concatenated * @param t6 * an Observable to be concatenated * @param t7 * an Observable to be concatenated * @param t8 * an Observable to be concatenated * @param t9 * an Observable to be concatenated * @return an Observable that emits items emitted by the nine source Observables, one after the other, * without interleaving them * @see <a href="http://reactivex.io/documentation/operators/concat.html">ReactiveX operators documentation: Concat</a> */ public final static <T> Observable<T> concat(Observable<? extends T> t1, Observable<? extends T> t2, Observable<? extends T> t3, Observable<? extends T> t4, Observable<? extends T> t5, Observable<? extends T> t6, Observable<? extends T> t7, Observable<? extends T> t8, Observable<? extends T> t9) { return concat(just(t1, t2, t3, t4, t5, t6, t7, t8, t9)); } /** * Returns an Observable that calls an Observable factory to create an Observable for each new Observer * that subscribes. That is, for each subscriber, the actual Observable 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.png" alt=""> * <p> * The defer Observer allows you to defer or delay emitting items from an Observable until such time as an * Observer subscribes to the Observable. This allows an {@link 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 observableFactory * the Observable factory function to invoke for each {@link Observer} that subscribes to the * resulting Observable * @param <T> * the type of the items emitted by the Observable * @return an Observable whose {@link Observer}s' subscriptions trigger an invocation of the given * Observable factory function * @see <a href="http://reactivex.io/documentation/operators/defer.html">ReactiveX operators documentation: Defer</a> */ public final static <T> Observable<T> defer(Func0<Observable<T>> observableFactory) { return create(new OnSubscribeDefer<T>(observableFactory)); } /** Lazy initialized Holder for an empty observable which just emits onCompleted to any subscriber. */ private static final class EmptyHolder { final static Observable<Object> INSTANCE = create(new OnSubscribe<Object>() { @Override public void call(Subscriber<? super Object> subscriber) { subscriber.onCompleted(); } }); } /** * Returns an Observable that emits no items to the {@link Observer} and immediately invokes its * {@link Observer#onCompleted onCompleted} method. * <p> * <img width="640" height="190" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/empty.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 Observable * @return an Observable that emits no items to the {@link Observer} but immediately invokes the * {@link Observer}'s {@link Observer#onCompleted() onCompleted} method * @see <a href="http://reactivex.io/documentation/operators/empty-never-throw.html">ReactiveX operators documentation: Empty</a> */ @SuppressWarnings("unchecked") public final static <T> Observable<T> empty() { return (Observable<T>) EmptyHolder.INSTANCE; } /** * Returns an Observable that invokes an {@link Observer}'s {@link Observer#onError onError} method when the * Observer subscribes to it. * <p> * <img width="640" height="190" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/error.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code error} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param exception * the particular Throwable to pass to {@link Observer#onError onError} * @param <T> * the type of the items (ostensibly) emitted by the Observable * @return an Observable that invokes the {@link Observer}'s {@link Observer#onError onError} method when * the Observer subscribes to it * @see <a href="http://reactivex.io/documentation/operators/empty-never-throw.html">ReactiveX operators documentation: Throw</a> */ public final static <T> Observable<T> error(Throwable exception) { return new ThrowObservable<T>(exception); } /** * Converts a {@link Future} into an Observable. * <p> * <img width="640" height="315" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/from.Future.png" alt=""> * <p> * You can convert any object that supports the {@link Future} interface into an Observable that emits the * return value of the {@link Future#get} method of that object, by passing the object into the {@code from} * method. * <p> * <em>Important note:</em> This Observable is blocking; you cannot unsubscribe from it. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code from} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param future * the source {@link Future} * @param <T> * the type of object that the {@link Future} returns, and also the type of item to be emitted by * the resulting Observable * @return an Observable that emits the item from the source {@link Future} * @see <a href="http://reactivex.io/documentation/operators/from.html">ReactiveX operators documentation: From</a> */ public final static <T> Observable<T> from(Future<? extends T> future) { return create(OnSubscribeToObservableFuture.toObservableFuture(future)); } /** * Converts a {@link Future} into an Observable, with a timeout on the Future. * <p> * <img width="640" height="315" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/from.Future.png" alt=""> * <p> * You can convert any object that supports the {@link Future} interface into an Observable that emits the * return value of the {@link Future#get} method of that object, by passing the object into the {@code from} * method. * <p> * <em>Important note:</em> This Observable is blocking; you cannot unsubscribe from it. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code from} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param future * the source {@link 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 {@link Future} returns, and also the type of item to be emitted by * the resulting Observable * @return an Observable that emits the item from the source {@link Future} * @see <a href="http://reactivex.io/documentation/operators/from.html">ReactiveX operators documentation: From</a> */ public final static <T> Observable<T> from(Future<? extends T> future, long timeout, TimeUnit unit) { return create(OnSubscribeToObservableFuture.toObservableFuture(future, timeout, unit)); } /** * Converts a {@link Future}, operating on a specified {@link Scheduler}, into an Observable. * <p> * <img width="640" height="315" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/from.Future.s.png" alt=""> * <p> * You can convert any object that supports the {@link Future} interface into an Observable that emits the * return value of the {@link Future#get} method of that object, by passing the object into the {@code from} * method. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>you specify which {@link Scheduler} this operator will use</dd> * </dl> * * @param future * the source {@link Future} * @param scheduler * the {@link Scheduler} to wait for the Future on. Use a Scheduler such as * {@link Schedulers#io()} that can block and wait on the Future * @param <T> * the type of object that the {@link Future} returns, and also the type of item to be emitted by * the resulting Observable * @return an Observable that emits the item from the source {@link Future} * @see <a href="http://reactivex.io/documentation/operators/from.html">ReactiveX operators documentation: From</a> */ public final static <T> Observable<T> from(Future<? extends T> future, Scheduler scheduler) { // TODO in a future revision the Scheduler will become important because we'll start polling instead of blocking on the Future return create(OnSubscribeToObservableFuture.toObservableFuture(future)).subscribeOn(scheduler); } /** * Converts an {@link Iterable} sequence into an Observable that emits the items in the sequence. * <p> * <img width="640" height="315" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/from.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code from} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param iterable * the source {@link Iterable} sequence * @param <T> * the type of items in the {@link Iterable} sequence and the type of items to be emitted by the * resulting Observable * @return an Observable that emits each item in the source {@link Iterable} sequence * @see <a href="http://reactivex.io/documentation/operators/from.html">ReactiveX operators documentation: From</a> */ public final static <T> Observable<T> from(Iterable<? extends T> iterable) { return create(new OnSubscribeFromIterable<T>(iterable)); } /** * Converts an Array into an Observable 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.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code from} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param array * the source Array * @param <T> * the type of items in the Array and the type of items to be emitted by the resulting Observable * @return an Observable that emits each item in the source Array * @see <a href="http://reactivex.io/documentation/operators/from.html">ReactiveX operators documentation: From</a> */ public final static <T> Observable<T> from(T[] array) { return from(Arrays.asList(array)); } /** * Returns an 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="195" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/fromCallable.png" alt=""> * <p> * This allows you to defer the execution of the function you specify untl an observer subscribes to the * 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> * </dl> * * @param func * a function, the execution of which should be deferred; {@code fromCallable} will invoke this * function only when an observer subscribes to the Observable that {@code fromCallable} returns * @param <T> * the type of the item emitted by the Observable * @return an Observable whose {@link Observer}s' subscriptions trigger an invocation of the given function * @see #defer(Func0) * @since (if this graduates from Experimental/Beta to supported, replace this parenthetical with the release number) */ @Experimental public static <T> Observable<T> fromCallable(Callable<? extends T> func) { return create(new OnSubscribeFromCallable<T>(func)); } /** * Returns an 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.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code interval} operates by default on the {@code computation} {@link Scheduler}.</dd> * </dl> * * @param interval * interval size in time units (see below) * @param unit * time units to use for the interval size * @return an Observable that emits a sequential number each time interval * @see <a href="http://reactivex.io/documentation/operators/interval.html">ReactiveX operators documentation: Interval</a> */ public final static Observable<Long> interval(long interval, TimeUnit unit) { return interval(interval, interval, unit, Schedulers.computation()); } /** * Returns an Observable that emits a sequential number every specified interval of time, on a * specified Scheduler. * <p> * <img width="640" height="200" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/interval.s.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>you specify which {@link Scheduler} this operator will use</dd> * </dl> * * @param interval * interval size in time units (see below) * @param unit * time units to use for the interval size * @param scheduler * the Scheduler to use for scheduling the items * @return an Observable that emits a sequential number each time interval * @see <a href="http://reactivex.io/documentation/operators/interval.html">ReactiveX operators documentation: Interval</a> */ public final static Observable<Long> interval(long interval, TimeUnit unit, Scheduler scheduler) { return interval(interval, interval, unit, scheduler); } /** * Returns an 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.png" alt=""> * <dl> * <dt><b>Backpressure Support:</b></dt> * <dd>This operator does not support backpressure as it uses time. If the downstream needs a slower rate * it should slow the timer or use something like {@link #onBackpressureDrop}.</dd> * <dt><b>Scheduler:</b></dt> * <dd>{@code timer} 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 an Observable that emits a 0L after the {@code initialDelay} and ever increasing numbers after * each {@code period} of time thereafter * @see <a href="http://reactivex.io/documentation/operators/interval.html">ReactiveX operators documentation: Interval</a> * @since 1.0.12 */ public final static Observable<Long> interval(long initialDelay, long period, TimeUnit unit) { return interval(initialDelay, period, unit, Schedulers.computation()); } /** * Returns an 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.png" alt=""> * <dl> * <dt><b>Backpressure Support:</b></dt> * <dd>This operator does not support backpressure as it uses time. If the downstream needs a slower rate * it should slow the timer or use something like {@link #onBackpressureDrop}.</dd> * <dt><b>Scheduler:</b></dt> * <dd>you specify which {@link 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 Scheduler on which the waiting happens and items are emitted * @return an Observable that emits a 0L after the {@code initialDelay} and ever increasing numbers after * each {@code period} of time thereafter, while running on the given Scheduler * @see <a href="http://reactivex.io/documentation/operators/interval.html">ReactiveX operators documentation: Interval</a> * @since 1.0.12 */ public final static Observable<Long> interval(long initialDelay, long period, TimeUnit unit, Scheduler scheduler) { return create(new OnSubscribeTimerPeriodically(initialDelay, period, unit, scheduler)); } /** * Returns an Observable that emits a single item and then completes. * <p> * <img width="640" height="310" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/just.png" alt=""> * <p> * To convert any object into an Observable that emits that object, pass that object into the {@code just} * method. * <p> * This is similar to the {@link #from(java.lang.Object[])} method, except that {@code from} will convert * an {@link Iterable} object into an Observable that emits each of the items in the Iterable, one at a * time, while the {@code just} method converts an Iterable into an Observable that emits the entire * Iterable as a single item. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code just} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param value * the item to emit * @param <T> * the type of that item * @return an Observable that emits {@code value} as a single item and then completes * @see <a href="http://reactivex.io/documentation/operators/just.html">ReactiveX operators documentation: Just</a> */ public final static <T> Observable<T> just(final T value) { return ScalarSynchronousObservable.create(value); } /** * Converts two items into an Observable that emits those items. * <p> * <img width="640" height="315" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/just.m.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code just} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param t1 * first item * @param t2 * second item * @param <T> * the type of these items * @return an Observable that emits each item * @see <a href="http://reactivex.io/documentation/operators/just.html">ReactiveX operators documentation: Just</a> */ // suppress unchecked because we are using varargs inside the method @SuppressWarnings("unchecked") public final static <T> Observable<T> just(T t1, T t2) { return from(Arrays.asList(t1, t2)); } /** * Converts three items into an Observable that emits those items. * <p> * <img width="640" height="315" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/just.m.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code just} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param t1 * first item * @param t2 * second item * @param t3 * third item * @param <T> * the type of these items * @return an Observable that emits each item * @see <a href="http://reactivex.io/documentation/operators/just.html">ReactiveX operators documentation: Just</a> */ // suppress unchecked because we are using varargs inside the method @SuppressWarnings("unchecked") public final static <T> Observable<T> just(T t1, T t2, T t3) { return from(Arrays.asList(t1, t2, t3)); } /** * Converts four items into an Observable that emits those items. * <p> * <img width="640" height="315" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/just.m.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code just} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param t1 * first item * @param t2 * second item * @param t3 * third item * @param t4 * fourth item * @param <T> * the type of these items * @return an Observable that emits each item * @see <a href="http://reactivex.io/documentation/operators/just.html">ReactiveX operators documentation: Just</a> */ // suppress unchecked because we are using varargs inside the method @SuppressWarnings("unchecked") public final static <T> Observable<T> just(T t1, T t2, T t3, T t4) { return from(Arrays.asList(t1, t2, t3, t4)); } /** * Converts five items into an Observable that emits those items. * <p> * <img width="640" height="315" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/just.m.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code just} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param t1 * first item * @param t2 * second item * @param t3 * third item * @param t4 * fourth item * @param t5 * fifth item * @param <T> * the type of these items * @return an Observable that emits each item * @see <a href="http://reactivex.io/documentation/operators/just.html">ReactiveX operators documentation: Just</a> */ // suppress unchecked because we are using varargs inside the method @SuppressWarnings("unchecked") public final static <T> Observable<T> just(T t1, T t2, T t3, T t4, T t5) { return from(Arrays.asList(t1, t2, t3, t4, t5)); } /** * Converts six items into an Observable that emits those items. * <p> * <img width="640" height="315" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/just.m.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code just} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param t1 * first item * @param t2 * second item * @param t3 * third item * @param t4 * fourth item * @param t5 * fifth item * @param t6 * sixth item * @param <T> * the type of these items * @return an Observable that emits each item * @see <a href="http://reactivex.io/documentation/operators/just.html">ReactiveX operators documentation: Just</a> */ // suppress unchecked because we are using varargs inside the method @SuppressWarnings("unchecked") public final static <T> Observable<T> just(T t1, T t2, T t3, T t4, T t5, T t6) { return from(Arrays.asList(t1, t2, t3, t4, t5, t6)); } /** * Converts seven items into an Observable that emits those items. * <p> * <img width="640" height="315" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/just.m.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code just} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param t1 * first item * @param t2 * second item * @param t3 * third item * @param t4 * fourth item * @param t5 * fifth item * @param t6 * sixth item * @param t7 * seventh item * @param <T> * the type of these items * @return an Observable that emits each item * @see <a href="http://reactivex.io/documentation/operators/just.html">ReactiveX operators documentation: Just</a> */ // suppress unchecked because we are using varargs inside the method @SuppressWarnings("unchecked") public final static <T> Observable<T> just(T t1, T t2, T t3, T t4, T t5, T t6, T t7) { return from(Arrays.asList(t1, t2, t3, t4, t5, t6, t7)); } /** * Converts eight items into an Observable that emits those items. * <p> * <img width="640" height="315" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/just.m.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code just} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param t1 * first item * @param t2 * second item * @param t3 * third item * @param t4 * fourth item * @param t5 * fifth item * @param t6 * sixth item * @param t7 * seventh item * @param t8 * eighth item * @param <T> * the type of these items * @return an Observable that emits each item * @see <a href="http://reactivex.io/documentation/operators/just.html">ReactiveX operators documentation: Just</a> */ // suppress unchecked because we are using varargs inside the method @SuppressWarnings("unchecked") public final static <T> Observable<T> just(T t1, T t2, T t3, T t4, T t5, T t6, T t7, T t8) { return from(Arrays.asList(t1, t2, t3, t4, t5, t6, t7, t8)); } /** * Converts nine items into an Observable that emits those items. * <p> * <img width="640" height="315" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/just.m.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code just} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param t1 * first item * @param t2 * second item * @param t3 * third item * @param t4 * fourth item * @param t5 * fifth item * @param t6 * sixth item * @param t7 * seventh item * @param t8 * eighth item * @param t9 * ninth item * @param <T> * the type of these items * @return an Observable that emits each item * @see <a href="http://reactivex.io/documentation/operators/just.html">ReactiveX operators documentation: Just</a> */ // suppress unchecked because we are using varargs inside the method @SuppressWarnings("unchecked") public final static <T> Observable<T> just(T t1, T t2, T t3, T t4, T t5, T t6, T t7, T t8, T t9) { return from(Arrays.asList(t1, t2, t3, t4, t5, t6, t7, t8, t9)); } /** * Converts ten items into an Observable that emits those items. * <p> * <img width="640" height="315" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/just.m.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code just} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param t1 * first item * @param t2 * second item * @param t3 * third item * @param t4 * fourth item * @param t5 * fifth item * @param t6 * sixth item * @param t7 * seventh item * @param t8 * eighth item * @param t9 * ninth item * @param t10 * tenth item * @param <T> * the type of these items * @return an Observable that emits each item * @see <a href="http://reactivex.io/documentation/operators/just.html">ReactiveX operators documentation: Just</a> */ // suppress unchecked because we are using varargs inside the method @SuppressWarnings("unchecked") public final static <T> Observable<T> just(T t1, T t2, T t3, T t4, T t5, T t6, T t7, T t8, T t9, T t10) { return from(Arrays.asList(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10)); } /** * Flattens an Iterable of Observables into one Observable, without any transformation. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/merge.png" alt=""> * <p> * You can combine the items emitted by multiple Observables so that they appear as a single Observable, 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> * </dl> * * @param sequences * the Iterable of Observables * @return an Observable that emits items that are the result of flattening the items emitted by the * Observables in the Iterable * @see <a href="http://reactivex.io/documentation/operators/merge.html">ReactiveX operators documentation: Merge</a> */ public final static <T> Observable<T> merge(Iterable<? extends Observable<? extends T>> sequences) { return merge(from(sequences)); } /** * Flattens an Iterable of Observables into one Observable, without any transformation, while limiting the * number of concurrent subscriptions to these Observables. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/merge.png" alt=""> * <p> * You can combine the items emitted by multiple Observables so that they appear as a single Observable, 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> * </dl> * * @param sequences * the Iterable of Observables * @param maxConcurrent * the maximum number of Observables that may be subscribed to concurrently * @return an Observable that emits items that are the result of flattening the items emitted by the * Observables in the Iterable * @throws IllegalArgumentException * if {@code maxConcurrent} is less than or equal to 0 * @see <a href="http://reactivex.io/documentation/operators/merge.html">ReactiveX operators documentation: Merge</a> */ public final static <T> Observable<T> merge(Iterable<? extends Observable<? extends T>> sequences, int maxConcurrent) { return merge(from(sequences), maxConcurrent); } /** * Flattens an Observable that emits Observables into a single Observable that emits the items emitted by * those Observables, without any transformation. * <p> * <img width="640" height="370" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/merge.oo.png" alt=""> * <p> * You can combine the items emitted by multiple Observables so that they appear as a single Observable, 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> * </dl> * * @param source * an Observable that emits Observables * @return an Observable that emits items that are the result of flattening the Observables emitted by the * {@code source} Observable * @see <a href="http://reactivex.io/documentation/operators/merge.html">ReactiveX operators documentation: Merge</a> */ @SuppressWarnings({"unchecked", "rawtypes"}) public final static <T> Observable<T> merge(Observable<? extends Observable<? extends T>> source) { if (source.getClass() == ScalarSynchronousObservable.class) { return ((ScalarSynchronousObservable<T>)source).scalarFlatMap((Func1)UtilityFunctions.identity()); } return source.lift(OperatorMerge.<T>instance(false)); } /** * Flattens an Observable that emits Observables into a single Observable that emits the items emitted by * those Observables, without any transformation, while limiting the maximum number of concurrent * subscriptions to these Observables. * <p> * <img width="640" height="370" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/merge.oo.png" alt=""> * <p> * You can combine the items emitted by multiple Observables so that they appear as a single Observable, 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> * </dl> * * @param source * an Observable that emits Observables * @param maxConcurrent * the maximum number of Observables that may be subscribed to concurrently * @return an Observable that emits items that are the result of flattening the Observables emitted by the * {@code source} Observable * @throws IllegalArgumentException * if {@code maxConcurrent} is less than or equal to 0 * @see <a href="http://reactivex.io/documentation/operators/merge.html">ReactiveX operators documentation: Merge</a> * @since (if this graduates from Experimental/Beta to supported, replace this parenthetical with the release number) */ @Experimental @SuppressWarnings({"unchecked", "rawtypes"}) public final static <T> Observable<T> merge(Observable<? extends Observable<? extends T>> source, int maxConcurrent) { if (source.getClass() == ScalarSynchronousObservable.class) { return ((ScalarSynchronousObservable<T>)source).scalarFlatMap((Func1)UtilityFunctions.identity()); } return source.lift(OperatorMerge.<T>instance(false, maxConcurrent)); } /** * Flattens two Observables into a single Observable, without any transformation. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/merge.png" alt=""> * <p> * You can combine items emitted by multiple Observables so that they appear as a single Observable, 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> * </dl> * * @param t1 * an Observable to be merged * @param t2 * an Observable to be merged * @return an Observable that emits all of the items emitted by the source Observables * @see <a href="http://reactivex.io/documentation/operators/merge.html">ReactiveX operators documentation: Merge</a> */ @SuppressWarnings("unchecked") public final static <T> Observable<T> merge(Observable<? extends T> t1, Observable<? extends T> t2) { return merge(from(Arrays.asList(t1, t2))); } /** * Flattens three Observables into a single Observable, without any transformation. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/merge.png" alt=""> * <p> * You can combine items emitted by multiple Observables so that they appear as a single Observable, 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> * </dl> * * @param t1 * an Observable to be merged * @param t2 * an Observable to be merged * @param t3 * an Observable to be merged * @return an Observable that emits all of the items emitted by the source Observables * @see <a href="http://reactivex.io/documentation/operators/merge.html">ReactiveX operators documentation: Merge</a> */ @SuppressWarnings("unchecked") public final static <T> Observable<T> merge(Observable<? extends T> t1, Observable<? extends T> t2, Observable<? extends T> t3) { return merge(from(Arrays.asList(t1, t2, t3))); } /** * Flattens four Observables into a single Observable, without any transformation. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/merge.png" alt=""> * <p> * You can combine items emitted by multiple Observables so that they appear as a single Observable, 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> * </dl> * * @param t1 * an Observable to be merged * @param t2 * an Observable to be merged * @param t3 * an Observable to be merged * @param t4 * an Observable to be merged * @return an Observable that emits all of the items emitted by the source Observables * @see <a href="http://reactivex.io/documentation/operators/merge.html">ReactiveX operators documentation: Merge</a> */ @SuppressWarnings("unchecked") public final static <T> Observable<T> merge(Observable<? extends T> t1, Observable<? extends T> t2, Observable<? extends T> t3, Observable<? extends T> t4) { return merge(from(Arrays.asList(t1, t2, t3, t4))); } /** * Flattens five Observables into a single Observable, without any transformation. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/merge.png" alt=""> * <p> * You can combine items emitted by multiple Observables so that they appear as a single Observable, 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> * </dl> * * @param t1 * an Observable to be merged * @param t2 * an Observable to be merged * @param t3 * an Observable to be merged * @param t4 * an Observable to be merged * @param t5 * an Observable to be merged * @return an Observable that emits all of the items emitted by the source Observables * @see <a href="http://reactivex.io/documentation/operators/merge.html">ReactiveX operators documentation: Merge</a> */ @SuppressWarnings("unchecked") public final static <T> Observable<T> merge(Observable<? extends T> t1, Observable<? extends T> t2, Observable<? extends T> t3, Observable<? extends T> t4, Observable<? extends T> t5) { return merge(from(Arrays.asList(t1, t2, t3, t4, t5))); } /** * Flattens six Observables into a single Observable, without any transformation. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/merge.png" alt=""> * <p> * You can combine items emitted by multiple Observables so that they appear as a single Observable, 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> * </dl> * * @param t1 * an Observable to be merged * @param t2 * an Observable to be merged * @param t3 * an Observable to be merged * @param t4 * an Observable to be merged * @param t5 * an Observable to be merged * @param t6 * an Observable to be merged * @return an Observable that emits all of the items emitted by the source Observables * @see <a href="http://reactivex.io/documentation/operators/merge.html">ReactiveX operators documentation: Merge</a> */ @SuppressWarnings("unchecked") public final static <T> Observable<T> merge(Observable<? extends T> t1, Observable<? extends T> t2, Observable<? extends T> t3, Observable<? extends T> t4, Observable<? extends T> t5, Observable<? extends T> t6) { return merge(from(Arrays.asList(t1, t2, t3, t4, t5, t6))); } /** * Flattens seven Observables into a single Observable, without any transformation. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/merge.png" alt=""> * <p> * You can combine items emitted by multiple Observables so that they appear as a single Observable, 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> * </dl> * * @param t1 * an Observable to be merged * @param t2 * an Observable to be merged * @param t3 * an Observable to be merged * @param t4 * an Observable to be merged * @param t5 * an Observable to be merged * @param t6 * an Observable to be merged * @param t7 * an Observable to be merged * @return an Observable that emits all of the items emitted by the source Observables * @see <a href="http://reactivex.io/documentation/operators/merge.html">ReactiveX operators documentation: Merge</a> */ @SuppressWarnings("unchecked") public final static <T> Observable<T> merge(Observable<? extends T> t1, Observable<? extends T> t2, Observable<? extends T> t3, Observable<? extends T> t4, Observable<? extends T> t5, Observable<? extends T> t6, Observable<? extends T> t7) { return merge(from(Arrays.asList(t1, t2, t3, t4, t5, t6, t7))); } /** * Flattens eight Observables into a single Observable, without any transformation. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/merge.png" alt=""> * <p> * You can combine items emitted by multiple Observables so that they appear as a single Observable, 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> * </dl> * * @param t1 * an Observable to be merged * @param t2 * an Observable to be merged * @param t3 * an Observable to be merged * @param t4 * an Observable to be merged * @param t5 * an Observable to be merged * @param t6 * an Observable to be merged * @param t7 * an Observable to be merged * @param t8 * an Observable to be merged * @return an Observable that emits all of the items emitted by the source Observables * @see <a href="http://reactivex.io/documentation/operators/merge.html">ReactiveX operators documentation: Merge</a> */ @SuppressWarnings("unchecked") public final static <T> Observable<T> merge(Observable<? extends T> t1, Observable<? extends T> t2, Observable<? extends T> t3, Observable<? extends T> t4, Observable<? extends T> t5, Observable<? extends T> t6, Observable<? extends T> t7, Observable<? extends T> t8) { return merge(from(Arrays.asList(t1, t2, t3, t4, t5, t6, t7, t8))); } /** * Flattens nine Observables into a single Observable, without any transformation. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/merge.png" alt=""> * <p> * You can combine items emitted by multiple Observables so that they appear as a single Observable, 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> * </dl> * * @param t1 * an Observable to be merged * @param t2 * an Observable to be merged * @param t3 * an Observable to be merged * @param t4 * an Observable to be merged * @param t5 * an Observable to be merged * @param t6 * an Observable to be merged * @param t7 * an Observable to be merged * @param t8 * an Observable to be merged * @param t9 * an Observable to be merged * @return an Observable that emits all of the items emitted by the source Observables * @see <a href="http://reactivex.io/documentation/operators/merge.html">ReactiveX operators documentation: Merge</a> */ @SuppressWarnings("unchecked") public final static <T> Observable<T> merge(Observable<? extends T> t1, Observable<? extends T> t2, Observable<? extends T> t3, Observable<? extends T> t4, Observable<? extends T> t5, Observable<? extends T> t6, Observable<? extends T> t7, Observable<? extends T> t8, Observable<? extends T> t9) { return merge(from(Arrays.asList(t1, t2, t3, t4, t5, t6, t7, t8, t9))); } /** * Flattens an Array of Observables into one Observable, without any transformation. * <p> * <img width="640" height="370" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/merge.io.png" alt=""> * <p> * You can combine items emitted by multiple Observables so that they appear as a single Observable, 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> * </dl> * * @param sequences * the Array of Observables * @return an Observable that emits all of the items emitted by the Observables in the Array * @see <a href="http://reactivex.io/documentation/operators/merge.html">ReactiveX operators documentation: Merge</a> */ public final static <T> Observable<T> merge(Observable<? extends T>[] sequences) { return merge(from(sequences)); } /** * Flattens an Array of Observables into one Observable, without any transformation, while limiting the * number of concurrent subscriptions to these Observables. * <p> * <img width="640" height="370" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/merge.io.png" alt=""> * <p> * You can combine items emitted by multiple Observables so that they appear as a single Observable, 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> * </dl> * * @param sequences * the Array of Observables * @param maxConcurrent * the maximum number of Observables that may be subscribed to concurrently * @return an Observable that emits all of the items emitted by the Observables in the Array * @see <a href="http://reactivex.io/documentation/operators/merge.html">ReactiveX operators documentation: Merge</a> * @since (if this graduates from Experimental/Beta to supported, replace this parenthetical with the release number) */ @Experimental public final static <T> Observable<T> merge(Observable<? extends T>[] sequences, int maxConcurrent) { return merge(from(sequences), maxConcurrent); } /** * Flattens an Observable that emits Observables into one Observable, in a way that allows an Observer to * receive all successfully emitted items from all of the source Observables without being interrupted by * an error notification from one of them. * <p> * This behaves like {@link #merge(Observable)} except that if any of the merged Observables notify of an * error via {@link Observer#onError onError}, {@code mergeDelayError} will refrain from propagating that * error notification until all of the merged Observables have finished emitting items. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/mergeDelayError.png" alt=""> * <p> * Even if multiple merged Observables send {@code onError} notifications, {@code mergeDelayError} will only * invoke the {@code onError} method of its Observers once. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code mergeDelayError} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param source * an Observable that emits Observables * @return an Observable that emits all of the items emitted by the Observables emitted by the * {@code source} Observable * @see <a href="http://reactivex.io/documentation/operators/merge.html">ReactiveX operators documentation: Merge</a> */ public final static <T> Observable<T> mergeDelayError(Observable<? extends Observable<? extends T>> source) { return source.lift(OperatorMerge.<T>instance(true)); } /** * Flattens an Observable that emits Observables into one Observable, in a way that allows an Observer to * receive all successfully emitted items from all of the source Observables without being interrupted by * an error notification from one of them, while limiting the * number of concurrent subscriptions to these Observables. * <p> * This behaves like {@link #merge(Observable)} except that if any of the merged Observables notify of an * error via {@link Observer#onError onError}, {@code mergeDelayError} will refrain from propagating that * error notification until all of the merged Observables have finished emitting items. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/mergeDelayError.png" alt=""> * <p> * Even if multiple merged Observables send {@code onError} notifications, {@code mergeDelayError} will only * invoke the {@code onError} method of its Observers once. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code mergeDelayError} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param source * an Observable that emits Observables * @param maxConcurrent * the maximum number of Observables that may be subscribed to concurrently * @return an Observable that emits all of the items emitted by the Observables emitted by the * {@code source} Observable * @see <a href="http://reactivex.io/documentation/operators/merge.html">ReactiveX operators documentation: Merge</a> * @since (if this graduates from Experimental/Beta to supported, replace this parenthetical with the release number) */ @Experimental public final static <T> Observable<T> mergeDelayError(Observable<? extends Observable<? extends T>> source, int maxConcurrent) { return source.lift(OperatorMerge.<T>instance(true, maxConcurrent)); } /** * Flattens two Observables into one Observable, in a way that allows an Observer to receive all * successfully emitted items from each of the source Observables without being interrupted by an error * notification from one of them. * <p> * This behaves like {@link #merge(Observable, Observable)} except that if any of the merged Observables * notify of an error via {@link Observer#onError onError}, {@code mergeDelayError} will refrain from * propagating that error notification until all of the merged Observables have finished emitting items. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/mergeDelayError.png" alt=""> * <p> * Even if both merged Observables send {@code onError} notifications, {@code mergeDelayError} will only * invoke the {@code onError} method of its Observers once. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code mergeDelayError} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param t1 * an Observable to be merged * @param t2 * an Observable to be merged * @return an Observable that emits all of the items that are emitted by the two source Observables * @see <a href="http://reactivex.io/documentation/operators/merge.html">ReactiveX operators documentation: Merge</a> */ public final static <T> Observable<T> mergeDelayError(Observable<? extends T> t1, Observable<? extends T> t2) { return mergeDelayError(just(t1, t2)); } /** * Flattens three Observables into one Observable, in a way that allows an Observer to receive all * successfully emitted items from all of the source Observables without being interrupted by an error * notification from one of them. * <p> * This behaves like {@link #merge(Observable, Observable, Observable)} except that if any of the merged * Observables notify of an error via {@link Observer#onError onError}, {@code mergeDelayError} will refrain * from propagating that error notification until all of the merged Observables have finished emitting * items. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/mergeDelayError.png" alt=""> * <p> * Even if multiple merged Observables send {@code onError} notifications, {@code mergeDelayError} will only * invoke the {@code onError} method of its Observers once. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code mergeDelayError} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param t1 * an Observable to be merged * @param t2 * an Observable to be merged * @param t3 * an Observable to be merged * @return an Observable that emits all of the items that are emitted by the source Observables * @see <a href="http://reactivex.io/documentation/operators/merge.html">ReactiveX operators documentation: Merge</a> */ public final static <T> Observable<T> mergeDelayError(Observable<? extends T> t1, Observable<? extends T> t2, Observable<? extends T> t3) { return mergeDelayError(just(t1, t2, t3)); } /** * Flattens four Observables into one Observable, in a way that allows an Observer to receive all * successfully emitted items from all of the source Observables without being interrupted by an error * notification from one of them. * <p> * This behaves like {@link #merge(Observable, Observable, Observable, Observable)} except that if any of * the merged Observables notify of an error via {@link Observer#onError onError}, {@code mergeDelayError} * will refrain from propagating that error notification until all of the merged Observables have finished * emitting items. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/mergeDelayError.png" alt=""> * <p> * Even if multiple merged Observables send {@code onError} notifications, {@code mergeDelayError} will only * invoke the {@code onError} method of its Observers once. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code mergeDelayError} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param t1 * an Observable to be merged * @param t2 * an Observable to be merged * @param t3 * an Observable to be merged * @param t4 * an Observable to be merged * @return an Observable that emits all of the items that are emitted by the source Observables * @see <a href="http://reactivex.io/documentation/operators/merge.html">ReactiveX operators documentation: Merge</a> */ public final static <T> Observable<T> mergeDelayError(Observable<? extends T> t1, Observable<? extends T> t2, Observable<? extends T> t3, Observable<? extends T> t4) { return mergeDelayError(just(t1, t2, t3, t4)); } /** * Flattens five Observables into one Observable, in a way that allows an Observer to receive all * successfully emitted items from all of the source Observables without being interrupted by an error * notification from one of them. * <p> * This behaves like {@link #merge(Observable, Observable, Observable, Observable, Observable)} except that * if any of the merged Observables notify of an error via {@link Observer#onError onError}, * {@code mergeDelayError} will refrain from propagating that error notification until all of the merged * Observables have finished emitting items. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/mergeDelayError.png" alt=""> * <p> * Even if multiple merged Observables send {@code onError} notifications, {@code mergeDelayError} will only * invoke the {@code onError} method of its Observers once. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code mergeDelayError} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param t1 * an Observable to be merged * @param t2 * an Observable to be merged * @param t3 * an Observable to be merged * @param t4 * an Observable to be merged * @param t5 * an Observable to be merged * @return an Observable that emits all of the items that are emitted by the source Observables * @see <a href="http://reactivex.io/documentation/operators/merge.html">ReactiveX operators documentation: Merge</a> */ public final static <T> Observable<T> mergeDelayError(Observable<? extends T> t1, Observable<? extends T> t2, Observable<? extends T> t3, Observable<? extends T> t4, Observable<? extends T> t5) { return mergeDelayError(just(t1, t2, t3, t4, t5)); } /** * Flattens six Observables into one Observable, in a way that allows an Observer to receive all * successfully emitted items from all of the source Observables without being interrupted by an error * notification from one of them. * <p> * This behaves like {@link #merge(Observable, Observable, Observable, Observable, Observable, Observable)} * except that if any of the merged Observables notify of an error via {@link Observer#onError onError}, * {@code mergeDelayError} will refrain from propagating that error notification until all of the merged * Observables have finished emitting items. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/mergeDelayError.png" alt=""> * <p> * Even if multiple merged Observables send {@code onError} notifications, {@code mergeDelayError} will only * invoke the {@code onError} method of its Observers once. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code mergeDelayError} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param t1 * an Observable to be merged * @param t2 * an Observable to be merged * @param t3 * an Observable to be merged * @param t4 * an Observable to be merged * @param t5 * an Observable to be merged * @param t6 * an Observable to be merged * @return an Observable that emits all of the items that are emitted by the source Observables * @see <a href="http://reactivex.io/documentation/operators/merge.html">ReactiveX operators documentation: Merge</a> */ public final static <T> Observable<T> mergeDelayError(Observable<? extends T> t1, Observable<? extends T> t2, Observable<? extends T> t3, Observable<? extends T> t4, Observable<? extends T> t5, Observable<? extends T> t6) { return mergeDelayError(just(t1, t2, t3, t4, t5, t6)); } /** * Flattens seven Observables into one Observable, in a way that allows an Observer to receive all * successfully emitted items from all of the source Observables without being interrupted by an error * notification from one of them. * <p> * This behaves like * {@link #merge(Observable, Observable, Observable, Observable, Observable, Observable, Observable)} * except that if any of the merged Observables notify of an error via {@link Observer#onError onError}, * {@code mergeDelayError} will refrain from propagating that error notification until all of the merged * Observables have finished emitting items. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/mergeDelayError.png" alt=""> * <p> * Even if multiple merged Observables send {@code onError} notifications, {@code mergeDelayError} will only * invoke the {@code onError} method of its Observers once. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code mergeDelayError} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param t1 * an Observable to be merged * @param t2 * an Observable to be merged * @param t3 * an Observable to be merged * @param t4 * an Observable to be merged * @param t5 * an Observable to be merged * @param t6 * an Observable to be merged * @param t7 * an Observable to be merged * @return an Observable that emits all of the items that are emitted by the source Observables * @see <a href="http://reactivex.io/documentation/operators/merge.html">ReactiveX operators documentation: Merge</a> */ public final static <T> Observable<T> mergeDelayError(Observable<? extends T> t1, Observable<? extends T> t2, Observable<? extends T> t3, Observable<? extends T> t4, Observable<? extends T> t5, Observable<? extends T> t6, Observable<? extends T> t7) { return mergeDelayError(just(t1, t2, t3, t4, t5, t6, t7)); } /** * Flattens eight Observables into one Observable, in a way that allows an Observer to receive all * successfully emitted items from all of the source Observables without being interrupted by an error * notification from one of them. * <p> * This behaves like {@link #merge(Observable, Observable, Observable, Observable, Observable, Observable, Observable, Observable)} * except that if any of the merged Observables notify of an error via {@link Observer#onError onError}, * {@code mergeDelayError} will refrain from propagating that error notification until all of the merged * Observables have finished emitting items. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/mergeDelayError.png" alt=""> * <p> * Even if multiple merged Observables send {@code onError} notifications, {@code mergeDelayError} will only * invoke the {@code onError} method of its Observers once. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code mergeDelayError} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param t1 * an Observable to be merged * @param t2 * an Observable to be merged * @param t3 * an Observable to be merged * @param t4 * an Observable to be merged * @param t5 * an Observable to be merged * @param t6 * an Observable to be merged * @param t7 * an Observable to be merged * @param t8 * an Observable to be merged * @return an Observable that emits all of the items that are emitted by the source Observables * @see <a href="http://reactivex.io/documentation/operators/merge.html">ReactiveX operators documentation: Merge</a> */ // suppress because the types are checked by the method signature before using a vararg public final static <T> Observable<T> mergeDelayError(Observable<? extends T> t1, Observable<? extends T> t2, Observable<? extends T> t3, Observable<? extends T> t4, Observable<? extends T> t5, Observable<? extends T> t6, Observable<? extends T> t7, Observable<? extends T> t8) { return mergeDelayError(just(t1, t2, t3, t4, t5, t6, t7, t8)); } /** * Flattens nine Observables into one Observable, in a way that allows an Observer to receive all * successfully emitted items from all of the source Observables without being interrupted by an error * notification from one of them. * <p> * This behaves like {@link #merge(Observable, Observable, Observable, Observable, Observable, Observable, Observable, Observable, Observable)} * except that if any of the merged Observables notify of an error via {@link Observer#onError onError}, * {@code mergeDelayError} will refrain from propagating that error notification until all of the merged * Observables have finished emitting items. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/mergeDelayError.png" alt=""> * <p> * Even if multiple merged Observables send {@code onError} notifications, {@code mergeDelayError} will only * invoke the {@code onError} method of its Observers once. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code mergeDelayError} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param t1 * an Observable to be merged * @param t2 * an Observable to be merged * @param t3 * an Observable to be merged * @param t4 * an Observable to be merged * @param t5 * an Observable to be merged * @param t6 * an Observable to be merged * @param t7 * an Observable to be merged * @param t8 * an Observable to be merged * @param t9 * an Observable to be merged * @return an Observable that emits all of the items that are emitted by the source Observables * @see <a href="http://reactivex.io/documentation/operators/merge.html">ReactiveX operators documentation: Merge</a> */ public final static <T> Observable<T> mergeDelayError(Observable<? extends T> t1, Observable<? extends T> t2, Observable<? extends T> t3, Observable<? extends T> t4, Observable<? extends T> t5, Observable<? extends T> t6, Observable<? extends T> t7, Observable<? extends T> t8, Observable<? extends T> t9) { return mergeDelayError(just(t1, t2, t3, t4, t5, t6, t7, t8, t9)); } /** * Converts the source {@code Observable<T>} into an {@code Observable<Observable<T>>} that emits the * source Observable as its single emission. * <p> * <img width="640" height="350" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/nest.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code nest} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @return an Observable that emits a single item: the source Observable * @see <a href="http://reactivex.io/documentation/operators/to.html">ReactiveX operators documentation: To</a> */ public final Observable<Observable<T>> nest() { return just(this); } /** * Returns an 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.png" alt=""> * <p> * This 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 Observable * @return an Observable that never emits any items or sends any notifications to an {@link Observer} * @see <a href="http://reactivex.io/documentation/operators/empty-never-throw.html">ReactiveX operators documentation: Never</a> */ public final static <T> Observable<T> never() { return NeverObservable.instance(); } /** * Returns an Observable that emits a sequence of Integers within a specified range. * <p> * <img width="640" height="195" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/range.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 Integer in the sequence * @param count * the number of sequential Integers to generate * @return an Observable that emits a range of sequential Integers * @throws IllegalArgumentException * if {@code count} is less than zero, or if {@code start} + {@code count} &minus; 1 exceeds * {@code Integer.MAX_VALUE} * @see <a href="http://reactivex.io/documentation/operators/range.html">ReactiveX operators documentation: Range</a> */ public final static Observable<Integer> range(int start, int count) { if (count < 0) { throw new IllegalArgumentException("Count can not be negative"); } if (count == 0) { return Observable.empty(); } if (start > Integer.MAX_VALUE - count + 1) { throw new IllegalArgumentException("start + count can not exceed Integer.MAX_VALUE"); } if(count == 1) { return Observable.just(start); } return Observable.create(new OnSubscribeRange(start, start + (count - 1))); } /** * Returns an Observable that emits a sequence of Integers within a specified range, on a specified * Scheduler. * <p> * <img width="640" height="195" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/range.s.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>you specify which {@link Scheduler} this operator will use</dd> * </dl> * * @param start * the value of the first Integer in the sequence * @param count * the number of sequential Integers to generate * @param scheduler * the Scheduler to run the generator loop on * @return an Observable that emits a range of sequential Integers * @see <a href="http://reactivex.io/documentation/operators/range.html">ReactiveX operators documentation: Range</a> */ public final static Observable<Integer> range(int start, int count, Scheduler scheduler) { return range(start, count).subscribeOn(scheduler); } /** * Returns an Observable that emits a Boolean value that indicates whether two Observable sequences are the * same by comparing the items emitted by each Observable pairwise. * <p> * <img width="640" height="385" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/sequenceEqual.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code sequenceEqual} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param first * the first Observable to compare * @param second * the second Observable to compare * @param <T> * the type of items emitted by each Observable * @return an Observable that emits a Boolean value that indicates whether the two sequences are the same * @see <a href="http://reactivex.io/documentation/operators/sequenceequal.html">ReactiveX operators documentation: SequenceEqual</a> */ public final static <T> Observable<Boolean> sequenceEqual(Observable<? extends T> first, Observable<? extends T> second) { return sequenceEqual(first, second, new Func2<T, T, Boolean>() { @Override public final Boolean call(T first, T second) { if (first == null) { return second == null; } return first.equals(second); } }); } /** * Returns an Observable that emits a Boolean value that indicates whether two Observable sequences are the * same by comparing the items emitted by each Observable pairwise based on the results of a specified * equality function. * <p> * <img width="640" height="385" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/sequenceEqual.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code sequenceEqual} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param first * the first Observable to compare * @param second * the second Observable to compare * @param equality * a function used to compare items emitted by each Observable * @param <T> * the type of items emitted by each Observable * @return an Observable that emits a Boolean value that indicates whether the two Observable two sequences * are the same according to the specified function * @see <a href="http://reactivex.io/documentation/operators/sequenceequal.html">ReactiveX operators documentation: SequenceEqual</a> */ public final static <T> Observable<Boolean> sequenceEqual(Observable<? extends T> first, Observable<? extends T> second, Func2<? super T, ? super T, Boolean> equality) { return OperatorSequenceEqual.sequenceEqual(first, second, equality); } /** * Converts an Observable that emits Observables into an Observable that emits the items emitted by the * most recently emitted of those Observables. * <p> * <img width="640" height="370" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/switchDo.png" alt=""> * <p> * {@code switchOnNext} subscribes to an Observable that emits Observables. Each time it observes one of * these emitted Observables, the Observable returned by {@code switchOnNext} begins emitting the items * emitted by that Observable. When a new Observable is emitted, {@code switchOnNext} stops emitting items * from the earlier-emitted Observable and begins emitting items from the new one. * <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 sequenceOfSequences * the source Observable that emits Observables * @return an Observable that emits the items emitted by the Observable most recently emitted by the source * Observable * @see <a href="http://reactivex.io/documentation/operators/switch.html">ReactiveX operators documentation: Switch</a> */ public final static <T> Observable<T> switchOnNext(Observable<? extends Observable<? extends T>> sequenceOfSequences) { return sequenceOfSequences.lift(OperatorSwitch.<T>instance()); } /** * Returns an 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.png" alt=""> * <dl> * <dt><b>Backpressure Support:</b></dt> * <dd>This operator does not support backpressure as it uses time. If the downstream needs a slower rate * it should slow the timer or use something like {@link #onBackpressureDrop}.</dd> * <dt><b>Scheduler:</b></dt> * <dd>{@code timer} 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 an Observable that emits a 0L after the {@code initialDelay} and ever increasing numbers after * each {@code period} of time thereafter * @see <a href="http://reactivex.io/documentation/operators/timer.html">ReactiveX operators documentation: Timer</a> * @deprecated use {@link #interval(long, long, TimeUnit)} instead */ @Deprecated public final static Observable<Long> timer(long initialDelay, long period, TimeUnit unit) { return interval(initialDelay, period, unit, Schedulers.computation()); } /** * Returns an 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.png" alt=""> * <dl> * <dt><b>Backpressure Support:</b></dt> * <dd>This operator does not support backpressure as it uses time. If the downstream needs a slower rate * it should slow the timer or use something like {@link #onBackpressureDrop}.</dd> * <dt><b>Scheduler:</b></dt> * <dd>you specify which {@link 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 Scheduler on which the waiting happens and items are emitted * @return an Observable that emits a 0L after the {@code initialDelay} and ever increasing numbers after * each {@code period} of time thereafter, while running on the given Scheduler * @see <a href="http://reactivex.io/documentation/operators/timer.html">ReactiveX operators documentation: Timer</a> * @deprecated use {@link #interval(long, long, TimeUnit, Scheduler)} instead */ @Deprecated public final static Observable<Long> timer(long initialDelay, long period, TimeUnit unit, Scheduler scheduler) { return interval(initialDelay, period, unit, scheduler); } /** * Returns an Observable that emits one item 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.png" alt=""> * <dl> * <dt><b>Backpressure Support:</b></dt> * <dd>This operator does not support backpressure as it uses time. If the downstream needs a slower rate * it should slow the timer or use something like {@link #onBackpressureDrop}.</dd> * <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 an Observable that emits one item after a specified delay, and then completes * @see <a href="http://reactivex.io/documentation/operators/timer.html">ReactiveX operators documentation: Timer</a> */ public final static Observable<Long> timer(long delay, TimeUnit unit) { return timer(delay, unit, Schedulers.computation()); } /** * Returns an Observable that emits one item after a specified delay, on a specified Scheduler, and then * completes. * <p> * <img width="640" height="200" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/timer.s.png" alt=""> * <dl> * <dt><b>Backpressure Support:</b></dt> * <dd>This operator does not support backpressure as it uses time. If the downstream needs a slower rate * it should slow the timer or use something like {@link #onBackpressureDrop}.</dd> * <dt><b>Scheduler:</b></dt> * <dd>you specify which {@link 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 {@link Scheduler} to use for scheduling the item * @return an Observable that emits one item after a specified delay, on a specified Scheduler, and then * completes * @see <a href="http://reactivex.io/documentation/operators/timer.html">ReactiveX operators documentation: Timer</a> */ public final static Observable<Long> timer(long delay, TimeUnit unit, Scheduler scheduler) { return create(new OnSubscribeTimerOnce(delay, unit, scheduler)); } /** * Constructs an Observable that creates a dependent resource object which is disposed of on unsubscription. * <p> * <img width="640" height="400" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/using.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code using} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param resourceFactory * the factory function to create a resource object that depends on the Observable * @param observableFactory * the factory function to create an Observable * @param disposeAction * the function that will dispose of the resource * @return the Observable whose lifetime controls the lifetime of the dependent resource object * @see <a href="http://reactivex.io/documentation/operators/using.html">ReactiveX operators documentation: Using</a> */ public final static <T, Resource> Observable<T> using( final Func0<Resource> resourceFactory, final Func1<? super Resource, ? extends Observable<? extends T>> observableFactory, final Action1<? super Resource> disposeAction) { return using(resourceFactory, observableFactory, disposeAction, false); } /** * Constructs an Observable that creates a dependent resource object which is disposed of just before * termination if you have set {@code disposeEagerly} to {@code true} and unsubscription does not occur * before termination. Otherwise resource disposal will occur on unsubscription. Eager disposal is * particularly appropriate for a synchronous Observable that resuses resources. {@code disposeAction} will * only be called once per subscription. * <p> * <img width="640" height="400" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/using.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code using} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @warn "Backpressure Support" section missing from javadoc * @param resourceFactory * the factory function to create a resource object that depends on the Observable * @param observableFactory * the factory function to create an Observable * @param disposeAction * the function that will dispose of the resource * @param disposeEagerly * if {@code true} then disposal will happen either on unsubscription or just before emission of * a terminal event ({@code onComplete} or {@code onError}). * @return the Observable whose lifetime controls the lifetime of the dependent resource object * @see <a href="http://reactivex.io/documentation/operators/using.html">ReactiveX operators documentation: Using</a> * @Experimental The behavior of this can change at any time. * @since (if this graduates from Experimental/Beta to supported, replace this parenthetical with the release number) */ @Experimental public final static <T, Resource> Observable<T> using( final Func0<Resource> resourceFactory, final Func1<? super Resource, ? extends Observable<? extends T>> observableFactory, final Action1<? super Resource> disposeAction, boolean disposeEagerly) { return create(new OnSubscribeUsing<T, Resource>(resourceFactory, observableFactory, disposeAction, disposeEagerly)); } /** * Returns an Observable that emits the results of a specified combiner function applied to combinations of * items emitted, in sequence, by an Iterable of other Observables. * <p> * {@code zip} applies this function in strict sequence, so the first item emitted by the new Observable * will be the result of the function applied to the first item emitted by each of the source Observables; * the second item emitted by the new Observable will be the result of the function applied to the second * item emitted by each of those Observables; 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} invokations of the source Observable that emits the fewest items. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/zip.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code zip} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param ws * an Iterable of source Observables * @param zipFunction * a function that, when applied to an item emitted by each of the source Observables, results in * an item that will be emitted by the resulting Observable * @return an Observable that emits the zipped results * @see <a href="http://reactivex.io/documentation/operators/zip.html">ReactiveX operators documentation: Zip</a> */ public final static <R> Observable<R> zip(Iterable<? extends Observable<?>> ws, FuncN<? extends R> zipFunction) { List<Observable<?>> os = new ArrayList<Observable<?>>(); for (Observable<?> o : ws) { os.add(o); } return Observable.just(os.toArray(new Observable<?>[os.size()])).lift(new OperatorZip<R>(zipFunction)); } /** * Returns an Observable that emits the results of a specified combiner function applied to combinations of * <i>n</i> items emitted, in sequence, by the <i>n</i> Observables emitted by a specified Observable. * <p> * {@code zip} applies this function in strict sequence, so the first item emitted by the new Observable * will be the result of the function applied to the first item emitted by each of the Observables emitted * by the source Observable; the second item emitted by the new Observable will be the result of the * function applied to the second item emitted by each of those Observables; 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} invokations of the source Observable that emits the fewest items. * <p> * <img width="640" height="370" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/zip.o.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code zip} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param ws * an Observable of source Observables * @param zipFunction * a function that, when applied to an item emitted by each of the Observables emitted by * {@code ws}, results in an item that will be emitted by the resulting Observable * @return an Observable that emits the zipped results * @see <a href="http://reactivex.io/documentation/operators/zip.html">ReactiveX operators documentation: Zip</a> */ public final static <R> Observable<R> zip(Observable<? extends Observable<?>> ws, final FuncN<? extends R> zipFunction) { return ws.toList().map(new Func1<List<? extends Observable<?>>, Observable<?>[]>() { @Override public Observable<?>[] call(List<? extends Observable<?>> o) { return o.toArray(new Observable<?>[o.size()]); } }).lift(new OperatorZip<R>(zipFunction)); } /** * Returns an Observable that emits the results of a specified combiner function applied to combinations of * two items emitted, in sequence, by two other Observables. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/zip.png" alt=""> * <p> * {@code zip} applies this function in strict sequence, so the first item emitted by the new 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 new 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 source Observable that emits the fewest * items. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code zip} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param o1 * the first source Observable * @param o2 * a second source Observable * @param zipFunction * a function that, when applied to an item emitted by each of the source Observables, results * in an item that will be emitted by the resulting Observable * @return an Observable that emits the zipped results * @see <a href="http://reactivex.io/documentation/operators/zip.html">ReactiveX operators documentation: Zip</a> */ public final static <T1, T2, R> Observable<R> zip(Observable<? extends T1> o1, Observable<? extends T2> o2, final Func2<? super T1, ? super T2, ? extends R> zipFunction) { return just(new Observable<?>[] { o1, o2 }).lift(new OperatorZip<R>(zipFunction)); } /** * Returns an Observable that emits the results of a specified combiner function applied to combinations of * three items emitted, in sequence, by three other Observables. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/zip.png" alt=""> * <p> * {@code zip} applies this function in strict sequence, so the first item emitted by the new 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 new * 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 source Observable that emits the fewest * items. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code zip} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param o1 * the first source Observable * @param o2 * a second source Observable * @param o3 * a third source Observable * @param zipFunction * a function that, when applied to an item emitted by each of the source Observables, results in * an item that will be emitted by the resulting Observable * @return an Observable that emits the zipped results * @see <a href="http://reactivex.io/documentation/operators/zip.html">ReactiveX operators documentation: Zip</a> */ public final static <T1, T2, T3, R> Observable<R> zip(Observable<? extends T1> o1, Observable<? extends T2> o2, Observable<? extends T3> o3, Func3<? super T1, ? super T2, ? super T3, ? extends R> zipFunction) { return just(new Observable<?>[] { o1, o2, o3 }).lift(new OperatorZip<R>(zipFunction)); } /** * Returns an Observable that emits the results of a specified combiner function applied to combinations of * four items emitted, in sequence, by four other Observables. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/zip.png" alt=""> * <p> * {@code zip} applies this function in strict sequence, so the first item emitted by the new 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 new Observable will be the result of the function applied to the second * item emitted by each of those Observables; 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 source Observable that emits the fewest * items. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code zip} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param o1 * the first source Observable * @param o2 * a second source Observable * @param o3 * a third source Observable * @param o4 * a fourth source Observable * @param zipFunction * a function that, when applied to an item emitted by each of the source Observables, results in * an item that will be emitted by the resulting Observable * @return an Observable that emits the zipped results * @see <a href="http://reactivex.io/documentation/operators/zip.html">ReactiveX operators documentation: Zip</a> */ public final static <T1, T2, T3, T4, R> Observable<R> zip(Observable<? extends T1> o1, Observable<? extends T2> o2, Observable<? extends T3> o3, Observable<? extends T4> o4, Func4<? super T1, ? super T2, ? super T3, ? super T4, ? extends R> zipFunction) { return just(new Observable<?>[] { o1, o2, o3, o4 }).lift(new OperatorZip<R>(zipFunction)); } /** * Returns an Observable that emits the results of a specified combiner function applied to combinations of * five items emitted, in sequence, by five other Observables. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/zip.png" alt=""> * <p> * {@code zip} applies this function in strict sequence, so the first item emitted by the new 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 new Observable will be the result of * the function applied to the second item emitted by each of those Observables; 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 source Observable that emits the fewest * items. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code zip} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param o1 * the first source Observable * @param o2 * a second source Observable * @param o3 * a third source Observable * @param o4 * a fourth source Observable * @param o5 * a fifth source Observable * @param zipFunction * a function that, when applied to an item emitted by each of the source Observables, results in * an item that will be emitted by the resulting Observable * @return an Observable that emits the zipped results * @see <a href="http://reactivex.io/documentation/operators/zip.html">ReactiveX operators documentation: Zip</a> */ public final static <T1, T2, T3, T4, T5, R> Observable<R> zip(Observable<? extends T1> o1, Observable<? extends T2> o2, Observable<? extends T3> o3, Observable<? extends T4> o4, Observable<? extends T5> o5, Func5<? super T1, ? super T2, ? super T3, ? super T4, ? super T5, ? extends R> zipFunction) { return just(new Observable<?>[] { o1, o2, o3, o4, o5 }).lift(new OperatorZip<R>(zipFunction)); } /** * Returns an Observable that emits the results of a specified combiner function applied to combinations of * six items emitted, in sequence, by six other Observables. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/zip.png" alt=""> * <p> * {@code zip} applies this function in strict sequence, so the first item emitted by the new Observable * will be the result of the function applied to the first item emitted by each source Observable, the * second item emitted by the new Observable will be the result of the function applied to the second item * emitted by each of those Observables, 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 source Observable that emits the fewest * items. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code zip} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param o1 * the first source Observable * @param o2 * a second source Observable * @param o3 * a third source Observable * @param o4 * a fourth source Observable * @param o5 * a fifth source Observable * @param o6 * a sixth source Observable * @param zipFunction * a function that, when applied to an item emitted by each of the source Observables, results in * an item that will be emitted by the resulting Observable * @return an Observable that emits the zipped results * @see <a href="http://reactivex.io/documentation/operators/zip.html">ReactiveX operators documentation: Zip</a> */ public final static <T1, T2, T3, T4, T5, T6, R> Observable<R> zip(Observable<? extends T1> o1, Observable<? extends T2> o2, Observable<? extends T3> o3, Observable<? extends T4> o4, Observable<? extends T5> o5, Observable<? extends T6> o6, Func6<? super T1, ? super T2, ? super T3, ? super T4, ? super T5, ? super T6, ? extends R> zipFunction) { return just(new Observable<?>[] { o1, o2, o3, o4, o5, o6 }).lift(new OperatorZip<R>(zipFunction)); } /** * Returns an Observable that emits the results of a specified combiner function applied to combinations of * seven items emitted, in sequence, by seven other Observables. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/zip.png" alt=""> * <p> * {@code zip} applies this function in strict sequence, so the first item emitted by the new Observable * will be the result of the function applied to the first item emitted by each source Observable, the * second item emitted by the new Observable will be the result of the function applied to the second item * emitted by each of those Observables, 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 source Observable that emits the fewest * items. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code zip} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param o1 * the first source Observable * @param o2 * a second source Observable * @param o3 * a third source Observable * @param o4 * a fourth source Observable * @param o5 * a fifth source Observable * @param o6 * a sixth source Observable * @param o7 * a seventh source Observable * @param zipFunction * a function that, when applied to an item emitted by each of the source Observables, results in * an item that will be emitted by the resulting Observable * @return an Observable that emits the zipped results * @see <a href="http://reactivex.io/documentation/operators/zip.html">ReactiveX operators documentation: Zip</a> */ public final static <T1, T2, T3, T4, T5, T6, T7, R> Observable<R> zip(Observable<? extends T1> o1, Observable<? extends T2> o2, Observable<? extends T3> o3, Observable<? extends T4> o4, Observable<? extends T5> o5, Observable<? extends T6> o6, Observable<? extends T7> o7, Func7<? super T1, ? super T2, ? super T3, ? super T4, ? super T5, ? super T6, ? super T7, ? extends R> zipFunction) { return just(new Observable<?>[] { o1, o2, o3, o4, o5, o6, o7 }).lift(new OperatorZip<R>(zipFunction)); } /** * Returns an Observable that emits the results of a specified combiner function applied to combinations of * eight items emitted, in sequence, by eight other Observables. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/zip.png" alt=""> * <p> * {@code zip} applies this function in strict sequence, so the first item emitted by the new Observable * will be the result of the function applied to the first item emitted by each source Observable, the * second item emitted by the new Observable will be the result of the function applied to the second item * emitted by each of those Observables, 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 source Observable that emits the fewest * items. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code zip} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param o1 * the first source Observable * @param o2 * a second source Observable * @param o3 * a third source Observable * @param o4 * a fourth source Observable * @param o5 * a fifth source Observable * @param o6 * a sixth source Observable * @param o7 * a seventh source Observable * @param o8 * an eighth source Observable * @param zipFunction * a function that, when applied to an item emitted by each of the source Observables, results in * an item that will be emitted by the resulting Observable * @return an Observable that emits the zipped results * @see <a href="http://reactivex.io/documentation/operators/zip.html">ReactiveX operators documentation: Zip</a> */ public final static <T1, T2, T3, T4, T5, T6, T7, T8, R> Observable<R> zip(Observable<? extends T1> o1, Observable<? extends T2> o2, Observable<? extends T3> o3, Observable<? extends T4> o4, Observable<? extends T5> o5, Observable<? extends T6> o6, Observable<? extends T7> o7, Observable<? extends T8> o8, Func8<? super T1, ? super T2, ? super T3, ? super T4, ? super T5, ? super T6, ? super T7, ? super T8, ? extends R> zipFunction) { return just(new Observable<?>[] { o1, o2, o3, o4, o5, o6, o7, o8 }).lift(new OperatorZip<R>(zipFunction)); } /** * Returns an Observable that emits the results of a specified combiner function applied to combinations of * nine items emitted, in sequence, by nine other Observables. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/zip.png" alt=""> * <p> * {@code zip} applies this function in strict sequence, so the first item emitted by the new Observable * will be the result of the function applied to the first item emitted by each source Observable, the * second item emitted by the new Observable will be the result of the function applied to the second item * emitted by each of those Observables, 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 source Observable that emits the fewest * items. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code zip} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param o1 * the first source Observable * @param o2 * a second source Observable * @param o3 * a third source Observable * @param o4 * a fourth source Observable * @param o5 * a fifth source Observable * @param o6 * a sixth source Observable * @param o7 * a seventh source Observable * @param o8 * an eighth source Observable * @param o9 * a ninth source Observable * @param zipFunction * a function that, when applied to an item emitted by each of the source Observables, results in * an item that will be emitted by the resulting Observable * @return an Observable that emits the zipped results * @see <a href="http://reactivex.io/documentation/operators/zip.html">ReactiveX operators documentation: Zip</a> */ public final static <T1, T2, T3, T4, T5, T6, T7, T8, T9, R> Observable<R> zip(Observable<? extends T1> o1, Observable<? extends T2> o2, Observable<? extends T3> o3, Observable<? extends T4> o4, Observable<? extends T5> o5, Observable<? extends T6> o6, Observable<? extends T7> o7, Observable<? extends T8> o8, Observable<? extends T9> o9, Func9<? super T1, ? super T2, ? super T3, ? super T4, ? super T5, ? super T6, ? super T7, ? super T8, ? super T9, ? extends R> zipFunction) { return just(new Observable<?>[] { o1, o2, o3, o4, o5, o6, o7, o8, o9 }).lift(new OperatorZip<R>(zipFunction)); } /** * Returns an Observable that emits a Boolean that indicates whether all of the items emitted by the source * Observable satisfy a condition. * <p> * <img width="640" height="315" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/all.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 Boolean * @return an Observable that emits {@code true} if all items emitted by the source Observable satisfy the * predicate; otherwise, {@code false} * @see <a href="http://reactivex.io/documentation/operators/all.html">ReactiveX operators documentation: All</a> */ public final Observable<Boolean> all(Func1<? super T, Boolean> predicate) { return lift(new OperatorAll<T>(predicate)); } /** * Mirrors the Observable (current or provided) that first either emits an item or sends a termination * notification. * <p> * <img width="640" height="385" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/amb.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code amb} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param t1 * an Observable competing to react first * @return an Observable that emits the same sequence as whichever of the source Observables first * emitted an item or sent a termination notification * @see <a href="http://reactivex.io/documentation/operators/amb.html">ReactiveX operators documentation: Amb</a> */ public final Observable<T> ambWith(Observable<? extends T> t1) { return amb(this, t1); } /** * Portrays a object of an Observable subclass as a simple Observable object. This is useful, for instance, * when you have an implementation of a subclass of Observable but you want to hide the properties and * methods of this subclass from whomever you are passing the Observable to. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code asObservable} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @return an Observable that hides the identity of this Observable */ public final Observable<T> asObservable() { return lift(OperatorAsObservable.<T>instance()); } /** * Returns an Observable that emits buffers of items it collects from the source Observable. The resulting * Observable emits connected, non-overlapping buffers. It emits the current buffer and replaces it with a * new buffer whenever the Observable produced by the specified {@code bufferClosingSelector} emits an item. * <p> * <img width="640" height="395" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/buffer1.png" alt=""> * <dl> * <dt><b>Backpressure Support:</b></dt> * <dd>This operator does not support backpressure as it is instead controlled by the given Observables and * buffers data. It requests {@code Long.MAX_VALUE} upstream and does not obey downstream requests.</dd> * <dt><b>Scheduler:</b></dt> * <dd>This version of {@code buffer} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param bufferClosingSelector * a {@link Func0} that produces an Observable that governs the boundary between buffers. * Whenever this {@code Observable} emits an item, {@code buffer} emits the current buffer and * begins to fill a new one * @return an Observable that emits a connected, non-overlapping buffer of items from the source Observable * each time the Observable created with the {@code bufferClosingSelector} argument emits an item * @see <a href="http://reactivex.io/documentation/operators/buffer.html">ReactiveX operators documentation: Buffer</a> */ public final <TClosing> Observable<List<T>> buffer(Func0<? extends Observable<? extends TClosing>> bufferClosingSelector) { return lift(new OperatorBufferWithSingleObservable<T, TClosing>(bufferClosingSelector, 16)); } /** * Returns an Observable that emits buffers of items it collects from the source Observable. The resulting * Observable emits connected, non-overlapping buffers, each containing {@code count} items. When the source * Observable completes or encounters an error, the resulting Observable emits the current buffer and * propagates the notification from the source Observable. * <p> * <img width="640" height="320" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/buffer3.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 an Observable that emits connected, non-overlapping buffers, each containing at most * {@code count} items from the source Observable * @see <a href="http://reactivex.io/documentation/operators/buffer.html">ReactiveX operators documentation: Buffer</a> */ public final Observable<List<T>> buffer(int count) { return buffer(count, count); } /** * Returns an Observable that emits buffers of items it collects from the source Observable. The resulting * Observable emits buffers every {@code skip} items, each containing {@code count} items. When the source * Observable completes or encounters an error, the resulting Observable emits the current buffer and * propagates the notification from the source Observable. * <p> * <img width="640" height="320" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/buffer4.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 source 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 an Observable that emits buffers for every {@code skip} item from the source Observable and * containing at most {@code count} items * @see <a href="http://reactivex.io/documentation/operators/buffer.html">ReactiveX operators documentation: Buffer</a> */ public final Observable<List<T>> buffer(int count, int skip) { return lift(new OperatorBufferWithSize<T>(count, skip)); } /** * Returns an Observable that emits buffers of items it collects from the source Observable. The resulting * Observable starts a new buffer periodically, as determined by the {@code timeshift} argument. It emits * each buffer after a fixed timespan, specified by the {@code timespan} argument. When the source * Observable completes or encounters an error, the resulting Observable emits the current buffer and * propagates the notification from the source Observable. * <p> * <img width="640" height="320" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/buffer7.png" alt=""> * <dl> * <dt><b>Backpressure Support:</b></dt> * <dd>This operator does not support backpressure as it uses time. It requests {@code Long.MAX_VALUE} * upstream and does not obey downstream requests.</dd> * <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 timeshift * 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 timeshift} arguments * @return an Observable that emits new buffers of items emitted by the source Observable periodically after * a fixed timespan has elapsed * @see <a href="http://reactivex.io/documentation/operators/buffer.html">ReactiveX operators documentation: Buffer</a> */ public final Observable<List<T>> buffer(long timespan, long timeshift, TimeUnit unit) { return buffer(timespan, timeshift, unit, Schedulers.computation()); } /** * Returns an Observable that emits buffers of items it collects from the source Observable. The resulting * Observable starts a new buffer periodically, as determined by the {@code timeshift} argument, and on the * specified {@code scheduler}. It emits each buffer after a fixed timespan, specified by the * {@code timespan} argument. When the source Observable completes or encounters an error, the resulting * Observable emits the current buffer and propagates the notification from the source Observable. * <p> * <img width="640" height="320" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/buffer7.s.png" alt=""> * <dl> * <dt><b>Backpressure Support:</b></dt> * <dd>This operator does not support backpressure as it uses time. It requests {@code Long.MAX_VALUE} * upstream and does not obey downstream requests.</dd> * <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 timeshift * 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 timeshift} arguments * @param scheduler * the {@link Scheduler} to use when determining the end and start of a buffer * @return an Observable that emits new buffers of items emitted by the source Observable periodically after * a fixed timespan has elapsed * @see <a href="http://reactivex.io/documentation/operators/buffer.html">ReactiveX operators documentation: Buffer</a> */ public final Observable<List<T>> buffer(long timespan, long timeshift, TimeUnit unit, Scheduler scheduler) { return lift(new OperatorBufferWithTime<T>(timespan, timeshift, unit, Integer.MAX_VALUE, scheduler)); } /** * Returns an Observable that emits buffers of items it collects from the source Observable. The resulting * Observable emits connected, non-overlapping buffers, each of a fixed duration specified by the * {@code timespan} argument. When the source Observable completes or encounters an error, the resulting * Observable emits the current buffer and propagates the notification from the source Observable. * <p> * <img width="640" height="320" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/buffer5.png" alt=""> * <dl> * <dt><b>Backpressure Support:</b></dt> * <dd>This operator does not support backpressure as it uses time. It requests {@code Long.MAX_VALUE} * upstream and does not obey downstream requests.</dd> * <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 an Observable that emits connected, non-overlapping buffers of items emitted by the source * Observable within a fixed duration * @see <a href="http://reactivex.io/documentation/operators/buffer.html">ReactiveX operators documentation: Buffer</a> */ public final Observable<List<T>> buffer(long timespan, TimeUnit unit) { return buffer(timespan, unit, Integer.MAX_VALUE, Schedulers.computation()); } /** * Returns an Observable that emits buffers of items it collects from the source Observable. The resulting * 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 source Observable completes or encounters an error, the resulting Observable emits the * current buffer and propagates the notification from the source Observable. * <p> * <img width="640" height="320" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/buffer6.png" alt=""> * <dl> * <dt><b>Backpressure Support:</b></dt> * <dd>This operator does not support backpressure as it uses time. It requests {@code Long.MAX_VALUE} * upstream and does not obey downstream requests.</dd> * <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 an Observable that emits connected, non-overlapping buffers of items emitted by the source * Observable, after a fixed duration or when the buffer reaches maximum capacity (whichever occurs * first) * @see <a href="http://reactivex.io/documentation/operators/buffer.html">ReactiveX operators documentation: Buffer</a> */ public final Observable<List<T>> buffer(long timespan, TimeUnit unit, int count) { return lift(new OperatorBufferWithTime<T>(timespan, timespan, unit, count, Schedulers.computation())); } /** * Returns an Observable that emits buffers of items it collects from the source Observable. The resulting * 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 source Observable completes or * encounters an error, the resulting Observable emits the current buffer and propagates the notification * from the source Observable. * <p> * <img width="640" height="320" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/buffer6.s.png" alt=""> * <dl> * <dt><b>Backpressure Support:</b></dt> * <dd>This operator does not support backpressure as it uses time. It requests {@code Long.MAX_VALUE} * upstream and does not obey downstream requests.</dd> * <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 count * the maximum size of each buffer before it is emitted * @param scheduler * the {@link Scheduler} to use when determining the end and start of a buffer * @return an Observable that emits connected, non-overlapping buffers of items emitted by the source * Observable after a fixed duration or when the buffer reaches maximum capacity (whichever occurs * first) * @see <a href="http://reactivex.io/documentation/operators/buffer.html">ReactiveX operators documentation: Buffer</a> */ public final Observable<List<T>> buffer(long timespan, TimeUnit unit, int count, Scheduler scheduler) { return lift(new OperatorBufferWithTime<T>(timespan, timespan, unit, count, scheduler)); } /** * Returns an Observable that emits buffers of items it collects from the source Observable. The resulting * 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 source Observable completes or * encounters an error, the resulting Observable emits the current buffer and propagates the notification * from the source Observable. * <p> * <img width="640" height="320" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/buffer5.s.png" alt=""> * <dl> * <dt><b>Backpressure Support:</b></dt> * <dd>This operator does not support backpressure as it uses time. It requests {@code Long.MAX_VALUE} * upstream and does not obey downstream requests.</dd> * <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 {@link Scheduler} to use when determining the end and start of a buffer * @return an Observable that emits connected, non-overlapping buffers of items emitted by the source * Observable within a fixed duration * @see <a href="http://reactivex.io/documentation/operators/buffer.html">ReactiveX operators documentation: Buffer</a> */ public final Observable<List<T>> buffer(long timespan, TimeUnit unit, Scheduler scheduler) { return buffer(timespan, timespan, unit, scheduler); } /** * Returns an Observable that emits buffers of items it collects from the source Observable. The resulting * Observable emits buffers that it creates when the specified {@code bufferOpenings} Observable emits an * item, and closes when the Observable returned from {@code bufferClosingSelector} emits an item. * <p> * <img width="640" height="470" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/buffer2.png" alt=""> * <dl> * <dt><b>Backpressure Support:</b></dt> * <dd>This operator does not support backpressure as it is instead controlled by the given Observables and * buffers data. It requests {@code Long.MAX_VALUE} upstream and does not obey downstream requests.</dd> * <dt><b>Scheduler:</b></dt> * <dd>This version of {@code buffer} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param bufferOpenings * the Observable that, when it emits an item, causes a new buffer to be created * @param bufferClosingSelector * the {@link Func1} that is used to produce an Observable for every buffer created. When this * Observable emits an item, the associated buffer is emitted. * @return an Observable that emits buffers, containing items from the source Observable, that are created * and closed when the specified Observables emit items * @see <a href="http://reactivex.io/documentation/operators/buffer.html">ReactiveX operators documentation: Buffer</a> */ public final <TOpening, TClosing> Observable<List<T>> buffer(Observable<? extends TOpening> bufferOpenings, Func1<? super TOpening, ? extends Observable<? extends TClosing>> bufferClosingSelector) { return lift(new OperatorBufferWithStartEndObservable<T, TOpening, TClosing>(bufferOpenings, bufferClosingSelector)); } /** * Returns an Observable that emits non-overlapping buffered items from the source Observable each time the * specified boundary Observable emits an item. * <p> * <img width="640" height="395" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/buffer8.png" alt=""> * <p> * Completion of either the source or the boundary Observable causes the returned Observable to emit the * latest buffer and complete. * <dl> * <dt><b>Backpressure Support:</b></dt> * <dd>This operator does not support backpressure as it is instead controlled by the {@code Observable} * {@code boundary} and buffers data. It requests {@code Long.MAX_VALUE} upstream and does not obey * downstream requests.</dd> * <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 boundary * the boundary Observable * @return an Observable that emits buffered items from the source Observable when the boundary Observable * emits an item * @see #buffer(rx.Observable, int) * @see <a href="http://reactivex.io/documentation/operators/buffer.html">ReactiveX operators documentation: Buffer</a> */ public final <B> Observable<List<T>> buffer(Observable<B> boundary) { return buffer(boundary, 16); } /** * Returns an Observable that emits non-overlapping buffered items from the source Observable each time the * specified boundary Observable emits an item. * <p> * <img width="640" height="395" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/buffer8.png" alt=""> * <p> * Completion of either the source or the boundary Observable causes the returned Observable to emit the * latest buffer and complete. * <dl> * <dt><b>Backpressure Support:</b></dt> * <dd>This operator does not support backpressure as it is instead controlled by the {@code Observable} * {@code boundary} and buffers data. It requests {@code Long.MAX_VALUE} upstream and does not obey * downstream requests.</dd> * <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 boundary * the boundary Observable * @param initialCapacity * the initial capacity of each buffer chunk * @return an Observable that emits buffered items from the source Observable when the boundary Observable * emits an item * @see <a href="http://reactivex.io/documentation/operators/buffer.html">ReactiveX operators documentation: Buffer</a> * @see #buffer(rx.Observable, int) */ public final <B> Observable<List<T>> buffer(Observable<B> boundary, int initialCapacity) { return lift(new OperatorBufferWithSingleObservable<T, B>(boundary, initialCapacity)); } /** * Caches the emissions from the source Observable and replays them in order to any subsequent Subscribers. * This method has similar behavior to {@link #replay} except that this auto-subscribes to the source * Observable rather than returning a {@link ConnectableObservable} for which you must call * {@code connect} to activate the subscription. * <p> * <img width="640" height="410" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/cache.png" alt=""> * <p> * This is useful when you want an Observable to cache responses and you can't control the * subscribe/unsubscribe behavior of all the {@link Subscriber}s. * <p> * When you call {@code cache}, it does not yet subscribe to the source Observable and so does not yet * begin cacheing items. This only happens when the first Subscriber calls the resulting Observable's * {@code subscribe} method. * <p> * <em>Note:</em> You sacrifice the ability to unsubscribe from the origin when you use the {@code cache} * Observer so be careful not to use this Observer on Observables that emit an infinite or very large number * of items that will use up memory. * <dl> * <dt><b>Backpressure Support:</b></dt> * <dd>This operator does not support upstream backpressure as it is purposefully requesting and caching * everything emitted.</dd> * <dt><b>Scheduler:</b></dt> * <dd>{@code cache} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @return an Observable that, when first subscribed to, caches all of its items and notifications for the * benefit of subsequent subscribers * @see <a href="http://reactivex.io/documentation/operators/replay.html">ReactiveX operators documentation: Replay</a> */ public final Observable<T> cache() { return CachedObservable.from(this); } /** * Caches emissions from the source Observable and replays them in order to any subsequent Subscribers. * This method has similar behavior to {@link #replay} except that this auto-subscribes to the source * Observable rather than returning a {@link ConnectableObservable} for which you must call * {@code connect} to activate the subscription. * <p> * <img width="640" height="410" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/cache.png" alt=""> * <p> * This is useful when you want an Observable to cache responses and you can't control the * subscribe/unsubscribe behavior of all the {@link Subscriber}s. * <p> * When you call {@code cache}, it does not yet subscribe to the source Observable and so does not yet * begin cacheing items. This only happens when the first Subscriber calls the resulting Observable's * {@code subscribe} method. * <p> * <em>Note:</em> You sacrifice the ability to unsubscribe from the origin when you use the {@code cache} * Observer so be careful not to use this Observer on Observables that emit an infinite or very large number * of items that will use up memory. * <dl> * <dt><b>Backpressure Support:</b></dt> * <dd>This operator does not support upstream backpressure as it is purposefully requesting and caching * everything emitted.</dd> * <dt><b>Scheduler:</b></dt> * <dd>{@code cache} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param capacityHint hint for number of items to cache (for optimizing underlying data structure) * @return an Observable that, when first subscribed to, caches all of its items and notifications for the * benefit of subsequent subscribers * @see <a href="http://reactivex.io/documentation/operators/replay.html">ReactiveX operators documentation: Replay</a> */ public final Observable<T> cache(int capacityHint) { return CachedObservable.from(this, capacityHint); } /** * Returns an Observable that emits the items emitted by the source Observable, converted to the specified * type. * <p> * <img width="640" height="305" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/cast.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code cast} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param klass * the target class type that {@code cast} will cast the items emitted by the source Observable * into before emitting them from the resulting Observable * @return an Observable that emits each item from the source Observable after converting it to the * specified type * @see <a href="http://reactivex.io/documentation/operators/map.html">ReactiveX operators documentation: Map</a> */ public final <R> Observable<R> cast(final Class<R> klass) { return lift(new OperatorCast<T, R>(klass)); } /** * Collects items emitted by the source Observable into a single mutable data structure and returns an * Observable that emits this structure. * <p> * <img width="640" height="330" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/collect.png" alt=""> * <p> * This is a simplified version of {@code reduce} that does not need to return the state on each pass. * <dl> * <dt><b>Backpressure Support:</b></dt> * <dd>This operator does not support backpressure because by intent it will receive all values and reduce * them to a single {@code onNext}.</dd> * <dt><b>Scheduler:</b></dt> * <dd>{@code collect} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param stateFactory * the mutable data structure that will collect the items * @param collector * a function that accepts the {@code state} and an emitted item, and modifies {@code state} * accordingly * @return an Observable that emits the result of collecting the values emitted by the source Observable * into a single mutable data structure * @see <a href="http://reactivex.io/documentation/operators/reduce.html">ReactiveX operators documentation: Reduce</a> */ public final <R> Observable<R> collect(Func0<R> stateFactory, final Action2<R, ? super T> collector) { Func2<R, T, R> accumulator = new Func2<R, T, R>() { @Override public final R call(R state, T value) { collector.call(state, value); return state; } }; /* * Discussion and confirmation of implementation at * https://github.com/ReactiveX/RxJava/issues/423#issuecomment-27642532 * * It should use last() not takeLast(1) since it needs to emit an error if the sequence is empty. */ return lift(new OperatorScan<R, T>(stateFactory, accumulator)).last(); } /** * Returns a new Observable that emits items resulting from applying a function that you supply to each item * emitted by the source Observable, where that function returns an Observable, and then emitting the items * that result from concatinating those resulting Observables. * <p> * <img width="640" height="305" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/concatMap.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code concatMap} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param func * a function that, when applied to an item emitted by the source Observable, returns an * Observable * @return an Observable that emits the result of applying the transformation function to each item emitted * by the source Observable and concatinating the Observables obtained from this transformation * @see <a href="http://reactivex.io/documentation/operators/flatmap.html">ReactiveX operators documentation: FlatMap</a> */ public final <R> Observable<R> concatMap(Func1<? super T, ? extends Observable<? extends R>> func) { return concat(map(func)); } /** * Returns an Observable that emits the items emitted from the current Observable, then the next, 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.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code concat} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param t1 * an Observable to be concatenated after the current * @return an Observable that emits items emitted by the two source Observables, one after the other, * without interleaving them * @see <a href="http://reactivex.io/documentation/operators/concat.html">ReactiveX operators documentation: Concat</a> */ public final Observable<T> concatWith(Observable<? extends T> t1) { return concat(this, t1); } /** * Returns an Observable that emits a Boolean that indicates whether the source Observable emitted a * specified item. * <p> * <img width="640" height="320" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/contains.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code contains} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param element * the item to search for in the emissions from the source Observable * @return an Observable that emits {@code true} if the specified item is emitted by the source Observable, * or {@code false} if the source Observable completes without emitting that item * @see <a href="http://reactivex.io/documentation/operators/contains.html">ReactiveX operators documentation: Contains</a> */ public final Observable<Boolean> contains(final Object element) { return exists(new Func1<T, Boolean>() { @Override public final Boolean call(T t1) { return element == null ? t1 == null : element.equals(t1); } }); } /** * Returns an Observable that emits the count of the total number of items emitted by the source Observable. * <p> * <img width="640" height="310" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/count.png" alt=""> * <dl> * <dt><b>Backpressure Support:</b></dt> * <dd>This operator does not support backpressure because by intent it will receive all values and reduce * them to a single {@code onNext}.</dd> * <dt><b>Scheduler:</b></dt> * <dd>{@code count} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @return an Observable that emits a single item: the number of elements emitted by the source Observable * @see <a href="http://reactivex.io/documentation/operators/count.html">ReactiveX operators documentation: Count</a> * @see #countLong() */ public final Observable<Integer> count() { return reduce(0, CountHolder.INSTANCE); } private static final class CountHolder { static final Func2<Integer, Object, Integer> INSTANCE = new Func2<Integer, Object, Integer>() { @Override public final Integer call(Integer count, Object o) { return count + 1; } }; } /** * Returns an Observable that counts the total number of items emitted by the source Observable and emits * this count as a 64-bit Long. * <p> * <img width="640" height="310" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/longCount.png" alt=""> * <dl> * <dt><b>Backpressure Support:</b></dt> * <dd>This operator does not support backpressure because by intent it will receive all values and reduce * them to a single {@code onNext}.</dd> * <dt><b>Scheduler:</b></dt> * <dd>{@code countLong} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @return an Observable that emits a single item: the number of items emitted by the source Observable as a * 64-bit Long item * @see <a href="http://reactivex.io/documentation/operators/count.html">ReactiveX operators documentation: Count</a> * @see #count() */ public final Observable<Long> countLong() { return reduce(0L, CountLongHolder.INSTANCE); } private static final class CountLongHolder { static final Func2<Long, Object, Long> INSTANCE = new Func2<Long, Object, Long>() { @Override public final Long call(Long count, Object o) { return count + 1; } }; } /** * Returns an Observable that mirrors the source Observable, except that it drops items emitted by the * source Observable that are followed by another item within a computed debounce duration. * <p> * <img width="640" height="425" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/debounce.f.png" alt=""> * <dl> * <dt><b>Backpressure Support:</b></dt> * <dd>This operator does not support backpressure as it uses the {@code debounceSelector} to mark * boundaries.</dd> * <dt><b>Scheduler:</b></dt> * <dd>This version of {@code debounce} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param <U> * the debounce value type (ignored) * @param debounceSelector * function to retrieve a sequence that indicates the throttle duration for each item * @return an Observable that omits items emitted by the source Observable that are followed by another item * within a computed debounce duration * @see <a href="http://reactivex.io/documentation/operators/debounce.html">ReactiveX operators documentation: Debounce</a> * @see <a href="https://github.com/ReactiveX/RxJava/wiki/Backpressure">RxJava wiki: Backpressure</a> */ public final <U> Observable<T> debounce(Func1<? super T, ? extends Observable<U>> debounceSelector) { return lift(new OperatorDebounceWithSelector<T, U>(debounceSelector)); } /** * Returns an Observable that mirrors the source Observable, except that it drops items emitted by the * source Observable that are followed by newer items before a timeout value expires. The timer resets on * each emission. * <p> * <em>Note:</em> If items keep being emitted by the source Observable faster than the timeout then no items * will be emitted by the resulting Observable. * <p> * <img width="640" height="310" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/debounce.png" alt=""> * <p> * Information on debounce vs throttle: * <p> * <ul> * <li><a href="http://drupalmotion.com/article/debounce-and-throttle-visual-explanation">Debounce and Throttle: visual explanation</a></li> * <li><a href="http://unscriptable.com/2009/03/20/debouncing-javascript-methods/">Debouncing: javascript methods</a></li> * <li><a href="http://www.illyriad.co.uk/blog/index.php/2011/09/javascript-dont-spam-your-server-debounce-and-throttle/">Javascript - don't spam your server: debounce and throttle</a></li> * </ul> * <dl> * <dt><b>Backpressure Support:</b></dt> * <dd>This operator does not support backpressure as it uses time to control data flow.</dd> * <dt><b>Scheduler:</b></dt> * <dd>This version of {@code debounce} operates by default on the {@code computation} {@link Scheduler}.</dd> * </dl> * * @param timeout * the time each item has to be "the most recent" of those emitted by the source Observable to * ensure that it's not dropped * @param unit * the {@link TimeUnit} for the timeout * @return an Observable that filters out items from the source Observable that are too quickly followed by * newer items * @see <a href="http://reactivex.io/documentation/operators/debounce.html">ReactiveX operators documentation: Debounce</a> * @see <a href="https://github.com/ReactiveX/RxJava/wiki/Backpressure">RxJava wiki: Backpressure</a> * @see #throttleWithTimeout(long, TimeUnit) */ public final Observable<T> debounce(long timeout, TimeUnit unit) { return debounce(timeout, unit, Schedulers.computation()); } /** * Returns an Observable that mirrors the source Observable, except that it drops items emitted by the * source Observable that are followed by newer items before a timeout value expires on a specified * Scheduler. The timer resets on each emission. * <p> * <em>Note:</em> If items keep being emitted by the source Observable faster than the timeout then no items * will be emitted by the resulting Observable. * <p> * <img width="640" height="310" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/debounce.s.png" alt=""> * <p> * Information on debounce vs throttle: * <p> * <ul> * <li><a href="http://drupalmotion.com/article/debounce-and-throttle-visual-explanation">Debounce and Throttle: visual explanation</a></li> * <li><a href="http://unscriptable.com/2009/03/20/debouncing-javascript-methods/">Debouncing: javascript methods</a></li> * <li><a href="http://www.illyriad.co.uk/blog/index.php/2011/09/javascript-dont-spam-your-server-debounce-and-throttle/">Javascript - don't spam your server: debounce and throttle</a></li> * </ul> * <dl> * <dt><b>Backpressure Support:</b></dt> * <dd>This operator does not support backpressure as it uses time to control data flow.</dd> * <dt><b>Scheduler:</b></dt> * <dd>you specify which {@link Scheduler} this operator will use</dd> * </dl> * * @param timeout * the time each item has to be "the most recent" of those emitted by the source Observable to * ensure that it's not dropped * @param unit * the unit of time for the specified timeout * @param scheduler * the {@link Scheduler} to use internally to manage the timers that handle the timeout for each * item * @return an Observable that filters out items from the source Observable that are too quickly followed by * newer items * @see <a href="http://reactivex.io/documentation/operators/debounce.html">ReactiveX operators documentation: Debounce</a> * @see <a href="https://github.com/ReactiveX/RxJava/wiki/Backpressure">RxJava wiki: Backpressure</a> * @see #throttleWithTimeout(long, TimeUnit, Scheduler) */ public final Observable<T> debounce(long timeout, TimeUnit unit, Scheduler scheduler) { return lift(new OperatorDebounceWithTime<T>(timeout, unit, scheduler)); } /** * Returns an Observable that emits the items emitted by the source Observable or a specified default item * if the source Observable is empty. * <p> * <img width="640" height="305" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/defaultIfEmpty.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code defaultIfEmpty} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param defaultValue * the item to emit if the source Observable emits no items * @return an Observable that emits either the specified default item if the source Observable emits no * items, or the items emitted by the source Observable * @see <a href="http://reactivex.io/documentation/operators/defaultifempty.html">ReactiveX operators documentation: DefaultIfEmpty</a> */ public final Observable<T> defaultIfEmpty(final T defaultValue) { //if empty switch to an observable that emits defaultValue and supports backpressure return switchIfEmpty(Observable.create(new OnSubscribe<T>() { @Override public void call(Subscriber<? super T> subscriber) { subscriber.setProducer(new SingleProducer<T>(subscriber, defaultValue)); }})); } /** * Returns an Observable that emits the items emitted by the source Observable or the items of an alternate * Observable if the source Observable is empty. * <p/> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code switchIfEmpty} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param alternate * the alternate Observable to subscribe to if the source does not emit any items * @return an Observable that emits the items emitted by the source Observable or the items of an * alternate Observable if the source Observable is empty. * @since (if this graduates from Experimental/Beta to supported, replace this parenthetical with the release number) */ @Experimental public final Observable<T> switchIfEmpty(Observable<? extends T> alternate) { return lift(new OperatorSwitchIfEmpty<T>(alternate)); } /** * Returns an Observable that delays the subscription to and emissions from the souce Observable via another * Observable on a per-item basis. * <p> * <img width="640" height="450" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/delay.oo.png" alt=""> * <p> * <em>Note:</em> the resulting Observable will immediately propagate any {@code onError} notification * from the source Observable. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>This version of {@code delay} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param <U> * the subscription delay value type (ignored) * @param <V> * the item delay value type (ignored) * @param subscriptionDelay * a function that returns an Observable that triggers the subscription to the source Observable * once it emits any item * @param itemDelay * a function that returns an Observable for each item emitted by the source Observable, which is * then used to delay the emission of that item by the resulting Observable until the Observable * returned from {@code itemDelay} emits an item * @return an Observable that delays the subscription and emissions of the source Observable via another * Observable on a per-item basis * @see <a href="http://reactivex.io/documentation/operators/delay.html">ReactiveX operators documentation: Delay</a> */ public final <U, V> Observable<T> delay( Func0<? extends Observable<U>> subscriptionDelay, Func1<? super T, ? extends Observable<V>> itemDelay) { return delaySubscription(subscriptionDelay).lift(new OperatorDelayWithSelector<T, V>(this, itemDelay)); } /** * Returns an Observable that delays the emissions of the source Observable via another Observable on a * per-item basis. * <p> * <img width="640" height="450" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/delay.o.png" alt=""> * <p> * <em>Note:</em> the resulting Observable will immediately propagate any {@code onError} notification * from the source Observable. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>This version of {@code delay} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param <U> * the item delay value type (ignored) * @param itemDelay * a function that returns an Observable for each item emitted by the source Observable, which is * then used to delay the emission of that item by the resulting Observable until the Observable * returned from {@code itemDelay} emits an item * @return an Observable that delays the emissions of the source Observable via another Observable on a * per-item basis * @see <a href="http://reactivex.io/documentation/operators/delay.html">ReactiveX operators documentation: Delay</a> */ public final <U> Observable<T> delay(Func1<? super T, ? extends Observable<U>> itemDelay) { return lift(new OperatorDelayWithSelector<T, U>(this, itemDelay)); } /** * Returns an Observable that emits the items emitted by the source Observable shifted forward in time by a * specified delay. Error notifications from the source Observable are not delayed. * <p> * <img width="640" height="310" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/delay.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>This version of {@code delay} operates by default on the {@code compuation} {@link Scheduler}.</dd> * </dl> * * @param delay * the delay to shift the source by * @param unit * the {@link TimeUnit} in which {@code period} is defined * @return the source Observable shifted in time by the specified delay * @see <a href="http://reactivex.io/documentation/operators/delay.html">ReactiveX operators documentation: Delay</a> */ public final Observable<T> delay(long delay, TimeUnit unit) { return delay(delay, unit, Schedulers.computation()); } /** * Returns an Observable that emits the items emitted by the source Observable shifted forward in time by a * specified delay. Error notifications from the source Observable are not delayed. * <p> * <img width="640" height="310" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/delay.s.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>you specify which {@link Scheduler} this operator will use</dd> * </dl> * * @param delay * the delay to shift the source by * @param unit * the time unit of {@code delay} * @param scheduler * the {@link Scheduler} to use for delaying * @return the source Observable shifted in time by the specified delay * @see <a href="http://reactivex.io/documentation/operators/delay.html">ReactiveX operators documentation: Delay</a> */ public final Observable<T> delay(long delay, TimeUnit unit, Scheduler scheduler) { return lift(new OperatorDelay<T>(this, delay, unit, scheduler)); } /** * Returns an Observable that delays the subscription to the source Observable by a given amount of time. * <p> * <img width="640" height="310" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/delaySubscription.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>This version of {@code delay} operates by default on the {@code compuation} {@link Scheduler}.</dd> * </dl> * * @param delay * the time to delay the subscription * @param unit * the time unit of {@code delay} * @return an Observable that delays the subscription to the source Observable by the given amount * @see <a href="http://reactivex.io/documentation/operators/delay.html">ReactiveX operators documentation: Delay</a> */ public final Observable<T> delaySubscription(long delay, TimeUnit unit) { return delaySubscription(delay, unit, Schedulers.computation()); } /** * Returns an Observable that delays the subscription to the source Observable by a given amount of time, * both waiting and subscribing on a given Scheduler. * <p> * <img width="640" height="310" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/delaySubscription.s.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>you specify which {@link Scheduler} this operator will use</dd> * </dl> * * @param delay * the time to delay the subscription * @param unit * the time unit of {@code delay} * @param scheduler * the Scheduler on which the waiting and subscription will happen * @return an Observable that delays the subscription to the source Observable by a given * amount, waiting and subscribing on the given Scheduler * @see <a href="http://reactivex.io/documentation/operators/delay.html">ReactiveX operators documentation: Delay</a> */ public final Observable<T> delaySubscription(long delay, TimeUnit unit, Scheduler scheduler) { return create(new OnSubscribeDelaySubscription<T>(this, delay, unit, scheduler)); } /** * Returns an Observable that delays the subscription to the source Observable until a second Observable * emits an item. * <p> * <img width="640" height="310" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/delaySubscription.o.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>This version of {@code delay} operates by default on the {@code compuation} {@link Scheduler}.</dd> * </dl> * * @param subscriptionDelay * a function that returns an Observable that triggers the subscription to the source Observable * once it emits any item * @return an Observable that delays the subscription to the source Observable until the Observable returned * by {@code subscriptionDelay} emits an item * @see <a href="http://reactivex.io/documentation/operators/delay.html">ReactiveX operators documentation: Delay</a> */ public final <U> Observable<T> delaySubscription(Func0<? extends Observable<U>> subscriptionDelay) { return create(new OnSubscribeDelaySubscriptionWithSelector<T, U>(this, subscriptionDelay)); } /** * Returns an Observable that reverses the effect of {@link #materialize materialize} by transforming the * {@link Notification} objects emitted by the source Observable into the items or notifications they * represent. * <p> * <img width="640" height="335" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/dematerialize.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code dematerialize} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @return an Observable that emits the items and notifications embedded in the {@link Notification} objects * emitted by the source Observable * @throws OnErrorNotImplementedException * if the source Observable is not of type {@code Observable<Notification<T>>} * @see <a href="http://reactivex.io/documentation/operators/materialize-dematerialize.html">ReactiveX operators documentation: Dematerialize</a> */ @SuppressWarnings({"unchecked"}) public final <T2> Observable<T2> dematerialize() { return lift(OperatorDematerialize.instance()); } /** * Returns an Observable that emits all items emitted by the source Observable that are distinct. * <p> * <img width="640" height="310" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/distinct.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code distinct} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @return an Observable that emits only those items emitted by the source Observable that are distinct from * each other * @see <a href="http://reactivex.io/documentation/operators/distinct.html">ReactiveX operators documentation: Distinct</a> */ public final Observable<T> distinct() { return lift(OperatorDistinct.<T> instance()); } /** * Returns an Observable that emits all items emitted by the source Observable that are distinct according * to a key selector function. * <p> * <img width="640" height="310" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/distinct.key.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code distinct} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param keySelector * a function that projects an emitted item to a key value that is used to decide whether an item * is distinct from another one or not * @return an Observable that emits those items emitted by the source Observable that have distinct keys * @see <a href="http://reactivex.io/documentation/operators/distinct.html">ReactiveX operators documentation: Distinct</a> */ public final <U> Observable<T> distinct(Func1<? super T, ? extends U> keySelector) { return lift(new OperatorDistinct<T, U>(keySelector)); } /** * Returns an Observable that emits all items emitted by the source Observable that are distinct from their * immediate predecessors. * <p> * <img width="640" height="310" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/distinctUntilChanged.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code distinctUntilChanged} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @return an Observable that emits those items from the source Observable that are distinct from their * immediate predecessors * @see <a href="http://reactivex.io/documentation/operators/distinct.html">ReactiveX operators documentation: Distinct</a> */ public final Observable<T> distinctUntilChanged() { return lift(OperatorDistinctUntilChanged.<T> instance()); } /** * Returns an Observable that emits all items emitted by the source Observable that are distinct from their * immediate predecessors, according to a key selector function. * <p> * <img width="640" height="310" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/distinctUntilChanged.key.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code distinctUntilChanged} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param keySelector * a function that projects an emitted item to a key value that is used to decide whether an item * is distinct from another one or not * @return an Observable that emits those items from the source Observable whose keys are distinct from * those of their immediate predecessors * @see <a href="http://reactivex.io/documentation/operators/distinct.html">ReactiveX operators documentation: Distinct</a> */ public final <U> Observable<T> distinctUntilChanged(Func1<? super T, ? extends U> keySelector) { return lift(new OperatorDistinctUntilChanged<T, U>(keySelector)); } /** * Modifies the source Observable so that it invokes an action when it calls {@code onCompleted}. * <p> * <img width="640" height="305" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/doOnCompleted.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code doOnCompleted} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param onCompleted * the action to invoke when the source Observable calls {@code onCompleted} * @return the source Observable with the side-effecting behavior applied * @see <a href="http://reactivex.io/documentation/operators/do.html">ReactiveX operators documentation: Do</a> */ public final Observable<T> doOnCompleted(final Action0 onCompleted) { Observer<T> observer = new Observer<T>() { @Override public final void onCompleted() { onCompleted.call(); } @Override public final void onError(Throwable e) { } @Override public final void onNext(T args) { } }; return lift(new OperatorDoOnEach<T>(observer)); } /** * Modifies the source Observable so that it invokes an action for each item it emits. * <p> * <img width="640" height="310" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/doOnEach.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code doOnEach} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param onNotification * the action to invoke for each item emitted by the source Observable * @return the source Observable with the side-effecting behavior applied * @see <a href="http://reactivex.io/documentation/operators/do.html">ReactiveX operators documentation: Do</a> */ public final Observable<T> doOnEach(final Action1<Notification<? super T>> onNotification) { Observer<T> observer = new Observer<T>() { @Override public final void onCompleted() { onNotification.call(Notification.createOnCompleted()); } @Override public final void onError(Throwable e) { onNotification.call(Notification.createOnError(e)); } @Override public final void onNext(T v) { onNotification.call(Notification.createOnNext(v)); } }; return lift(new OperatorDoOnEach<T>(observer)); } /** * Modifies the source Observable so that it notifies an Observer for each item it emits. * <p> * In case the {@code onError} of the supplied observer throws, the downstream will receive a composite * exception containing the original exception and the exception thrown by {@code onError}. If either the * {@code onNext} or the {@code onCompleted} method of the supplied observer throws, the downstream will be * terminated and will receive this thrown exception. * <p> * <img width="640" height="310" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/doOnEach.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code doOnEach} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param observer * the action to invoke for each item emitted by the source Observable * @return the source Observable with the side-effecting behavior applied * @see <a href="http://reactivex.io/documentation/operators/do.html">ReactiveX operators documentation: Do</a> */ public final Observable<T> doOnEach(Observer<? super T> observer) { return lift(new OperatorDoOnEach<T>(observer)); } /** * Modifies the source Observable so that it invokes an action if it calls {@code onError}. * <p> * In case the {@code onError} action throws, the downstream will receive a composite exception containing * the original exception and the exception thrown by {@code onError}. * <p> * <img width="640" height="305" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/doOnError.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code doOnError} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param onError * the action to invoke if the source Observable calls {@code onError} * @return the source Observable with the side-effecting behavior applied * @see <a href="http://reactivex.io/documentation/operators/do.html">ReactiveX operators documentation: Do</a> */ public final Observable<T> doOnError(final Action1<Throwable> onError) { Observer<T> observer = new Observer<T>() { @Override public final void onCompleted() { } @Override public final void onError(Throwable e) { onError.call(e); } @Override public final void onNext(T args) { } }; return lift(new OperatorDoOnEach<T>(observer)); } /** * Modifies the source Observable so that it invokes an action when it calls {@code onNext}. * <p> * <img width="640" height="310" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/doOnNext.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code doOnNext} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param onNext * the action to invoke when the source Observable calls {@code onNext} * @return the source Observable with the side-effecting behavior applied * @see <a href="http://reactivex.io/documentation/operators/do.html">ReactiveX operators documentation: Do</a> */ public final Observable<T> doOnNext(final Action1<? super T> onNext) { Observer<T> observer = new Observer<T>() { @Override public final void onCompleted() { } @Override public final void onError(Throwable e) { } @Override public final void onNext(T args) { onNext.call(args); } }; return lift(new OperatorDoOnEach<T>(observer)); } /** * Modifies the source {@code Observable} so that it invokes the given action when it receives a * request for more items. * <p> * <b>Note:</b> This operator is for tracing the internal behavior of back-pressure request * patterns and generally intended for debugging use. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code doOnRequest} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param onRequest * the action that gets called when an observer requests items from this * {@code Observable} * @return the source {@code Observable} modified so as to call this Action when appropriate * @see <a href="http://reactivex.io/documentation/operators/do.html">ReactiveX operators * documentation: Do</a> * @since (if this graduates from Experimental/Beta to supported, replace this parenthetical * with the release number) */ @Beta public final Observable<T> doOnRequest(final Action1<Long> onRequest) { return lift(new OperatorDoOnRequest<T>(onRequest)); } /** * Modifies the source {@code Observable} so that it invokes the given action when it is subscribed from * its subscribers. Each subscription will result in an invocation of the given action except when the * source {@code Observable} is reference counted, in which case the source {@code Observable} will invoke * the given action for the first subscription. * <p> * <img width="640" height="390" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/doOnSubscribe.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code doOnSubscribe} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param subscribe * the action that gets called when an observer subscribes to this {@code Observable} * @return the source {@code Observable} modified so as to call this Action when appropriate * @see <a href="http://reactivex.io/documentation/operators/do.html">ReactiveX operators documentation: Do</a> */ public final Observable<T> doOnSubscribe(final Action0 subscribe) { return lift(new OperatorDoOnSubscribe<T>(subscribe)); } /** * Modifies the source Observable so that it invokes an action when it calls {@code onCompleted} or * {@code onError}. * <p> * <img width="640" height="305" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/doOnTerminate.png" alt=""> * <p> * This differs from {@code finallyDo} in that this happens <em>before</em> the {@code onCompleted} or * {@code onError} notification. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code doOnTerminate} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param onTerminate * the action to invoke when the source Observable calls {@code onCompleted} or {@code onError} * @return the source Observable with the side-effecting behavior applied * @see <a href="http://reactivex.io/documentation/operators/do.html">ReactiveX operators documentation: Do</a> * @see #finallyDo(Action0) */ public final Observable<T> doOnTerminate(final Action0 onTerminate) { Observer<T> observer = new Observer<T>() { @Override public final void onCompleted() { onTerminate.call(); } @Override public final void onError(Throwable e) { onTerminate.call(); } @Override public final void onNext(T args) { } }; return lift(new OperatorDoOnEach<T>(observer)); } /** * Modifies the source {@code Observable} so that it invokes the given action when it is unsubscribed from * its subscribers. Each un-subscription will result in an invocation of the given action except when the * source {@code Observable} is reference counted, in which case the source {@code Observable} will invoke * the given action for the very last un-subscription. * <p> * <img width="640" height="310" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/doOnUnsubscribe.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code doOnUnsubscribe} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param unsubscribe * the action that gets called when this {@code Observable} is unsubscribed * @return the source {@code Observable} modified so as to call this Action when appropriate * @see <a href="http://reactivex.io/documentation/operators/do.html">ReactiveX operators documentation: Do</a> */ public final Observable<T> doOnUnsubscribe(final Action0 unsubscribe) { return lift(new OperatorDoOnUnsubscribe<T>(unsubscribe)); } /** * Concatenates two source Observables eagerly into a single stream of values. * <p> * Eager concatenation means that once a subscriber subscribes, this operator subscribes to all of the * source Observables. The operator buffers the values emitted by these Observables and then drains them * in order, each one after the previous one completes. * <dl> * <dt><b>Backpressure:</b></dt> * <dd>Backpressure is honored towards the downstream, however, due to the eagerness requirement, sources * are subscribed to in unbounded mode and their values are queued up in an unbounded buffer.</dd> * <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 o1 the first source * @param o2 the second source * @return * @warn javadoc fails to describe the return value * @since (if this graduates from Experimental/Beta to supported, replace this parenthetical with the release number) */ @Experimental @SuppressWarnings("unchecked") public static <T> Observable<T> concatEager(Observable<? extends T> o1, Observable<? extends T> o2) { return concatEager(Arrays.asList(o1, o2)); } /** * Concatenates three sources eagerly into a single stream of values. * <p> * Eager concatenation means that once a subscriber subscribes, this operator subscribes to all of the * source Observables. The operator buffers the values emitted by these Observables and then drains them * in order, each one after the previous one completes. * <dl> * <dt><b>Backpressure:</b></dt> * <dd>Backpressure is honored towards the downstream, however, due to the eagerness requirement, sources * are subscribed to in unbounded mode and their values are queued up in an unbounded buffer.</dd> * <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 o1 the first source * @param o2 the second source * @param o3 the third source * @return * @warn javadoc fails to describe the return value * @since (if this graduates from Experimental/Beta to supported, replace this parenthetical with the release number) */ @Experimental @SuppressWarnings("unchecked") public static <T> Observable<T> concatEager( Observable<? extends T> o1, Observable<? extends T> o2, Observable<? extends T> o3 ) { return concatEager(Arrays.asList(o1, o2, o3)); } /** * Concatenates four sources eagerly into a single stream of values. * <p> * Eager concatenation means that once a subscriber subscribes, this operator subscribes to all of the * source Observables. The operator buffers the values emitted by these Observables and then drains them * in order, each one after the previous one completes. * <dl> * <dt><b>Backpressure:</b></dt> * <dd>Backpressure is honored towards the downstream, however, due to the eagerness requirement, sources * are subscribed to in unbounded mode and their values are queued up in an unbounded buffer.</dd> * <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 o1 the first source * @param o2 the second source * @param o3 the third source * @param o4 the fourth source * @return * @warn javadoc fails to describe the return value * @since (if this graduates from Experimental/Beta to supported, replace this parenthetical with the release number) */ @Experimental @SuppressWarnings("unchecked") public static <T> Observable<T> concatEager( Observable<? extends T> o1, Observable<? extends T> o2, Observable<? extends T> o3, Observable<? extends T> o4 ) { return concatEager(Arrays.asList(o1, o2, o3, o4)); } /** * Concatenates five sources eagerly into a single stream of values. * <p> * Eager concatenation means that once a subscriber subscribes, this operator subscribes to all of the * source Observables. The operator buffers the values emitted by these Observables and then drains them * in order, each one after the previous one completes. * <dl> * <dt><b>Backpressure:</b></dt> * <dd>Backpressure is honored towards the downstream, however, due to the eagerness requirement, sources * are subscribed to in unbounded mode and their values are queued up in an unbounded buffer.</dd> * <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 o1 the first source * @param o2 the second source * @param o3 the third source * @param o4 the fourth source * @param o5 the fifth source * @return * @warn javadoc fails to describe the return value * @since (if this graduates from Experimental/Beta to supported, replace this parenthetical with the release number) */ @Experimental @SuppressWarnings("unchecked") public static <T> Observable<T> concatEager( Observable<? extends T> o1, Observable<? extends T> o2, Observable<? extends T> o3, Observable<? extends T> o4, Observable<? extends T> o5 ) { return concatEager(Arrays.asList(o1, o2, o3, o4, o5)); } /** * Concatenates six sources eagerly into a single stream of values. * <p> * Eager concatenation means that once a subscriber subscribes, this operator subscribes to all of the * source Observables. The operator buffers the values emitted by these Observables and then drains them * in order, each one after the previous one completes. * <dl> * <dt><b>Backpressure:</b></dt> * <dd>Backpressure is honored towards the downstream, however, due to the eagerness requirement, sources * are subscribed to in unbounded mode and their values are queued up in an unbounded buffer.</dd> * <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 o1 the first source * @param o2 the second source * @param o3 the third source * @param o4 the fourth source * @param o5 the fifth source * @param o6 the sixth source * @return * @warn javadoc fails to describe the return value * @since (if this graduates from Experimental/Beta to supported, replace this parenthetical with the release number) */ @Experimental @SuppressWarnings("unchecked") public static <T> Observable<T> concatEager( Observable<? extends T> o1, Observable<? extends T> o2, Observable<? extends T> o3, Observable<? extends T> o4, Observable<? extends T> o5, Observable<? extends T> o6 ) { return concatEager(Arrays.asList(o1, o2, o3, o4, o5, o6)); } /** * Concatenates seven sources eagerly into a single stream of values. * <p> * Eager concatenation means that once a subscriber subscribes, this operator subscribes to all of the * source Observables. The operator buffers the values emitted by these Observables and then drains them * in order, each one after the previous one completes. * <dl> * <dt><b>Backpressure:</b></dt> * <dd>Backpressure is honored towards the downstream, however, due to the eagerness requirement, sources * are subscribed to in unbounded mode and their values are queued up in an unbounded buffer.</dd> * <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 o1 the first source * @param o2 the second source * @param o3 the third source * @param o4 the fourth source * @param o5 the fifth source * @param o6 the sixth source * @param o7 the seventh source * @return * @warn javadoc fails to describe the return value * @since (if this graduates from Experimental/Beta to supported, replace this parenthetical with the release number) */ @Experimental @SuppressWarnings("unchecked") public static <T> Observable<T> concatEager( Observable<? extends T> o1, Observable<? extends T> o2, Observable<? extends T> o3, Observable<? extends T> o4, Observable<? extends T> o5, Observable<? extends T> o6, Observable<? extends T> o7 ) { return concatEager(Arrays.asList(o1, o2, o3, o4, o5, o6, o7)); } /** * Concatenates eight sources eagerly into a single stream of values. * <p> * Eager concatenation means that once a subscriber subscribes, this operator subscribes to all of the * source Observables. The operator buffers the values emitted by these Observables and then drains them * in order, each one after the previous one completes. * <dl> * <dt><b>Backpressure:</b></dt> * <dd>Backpressure is honored towards the downstream, however, due to the eagerness requirement, sources * are subscribed to in unbounded mode and their values are queued up in an unbounded buffer.</dd> * <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 o1 the first source * @param o2 the second source * @param o3 the third source * @param o4 the fourth source * @param o5 the fifth source * @param o6 the sixth source * @param o7 the seventh source * @param o8 the eighth source * @return * @warn javadoc fails to describe the return value * @since (if this graduates from Experimental/Beta to supported, replace this parenthetical with the release number) */ @Experimental @SuppressWarnings("unchecked") public static <T> Observable<T> concatEager( Observable<? extends T> o1, Observable<? extends T> o2, Observable<? extends T> o3, Observable<? extends T> o4, Observable<? extends T> o5, Observable<? extends T> o6, Observable<? extends T> o7, Observable<? extends T> o8 ) { return concatEager(Arrays.asList(o1, o2, o3, o4, o5, o6, o7, o8)); } /** * Concatenates nine sources eagerly into a single stream of values. * <p> * Eager concatenation means that once a subscriber subscribes, this operator subscribes to all of the * source Observables. The operator buffers the values emitted by these Observables and then drains them * in order, each one after the previous one completes. * <dl> * <dt><b>Backpressure:</b></dt> * <dd>Backpressure is honored towards the downstream, however, due to the eagerness requirement, sources * are subscribed to in unbounded mode and their values are queued up in an unbounded buffer.</dd> * <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 o1 the first source * @param o2 the second source * @param o3 the third source * @param o4 the fourth source * @param o5 the fifth source * @param o6 the sixth source * @param o7 the seventh source * @param o8 the eighth source * @param o9 the ninth source * @return * @warn javadoc fails to describe the return value * @since (if this graduates from Experimental/Beta to supported, replace this parenthetical with the release number) */ @Experimental @SuppressWarnings("unchecked") public static <T> Observable<T> concatEager( Observable<? extends T> o1, Observable<? extends T> o2, Observable<? extends T> o3, Observable<? extends T> o4, Observable<? extends T> o5, Observable<? extends T> o6, Observable<? extends T> o7, Observable<? extends T> o8, Observable<? extends T> o9 ) { return concatEager(Arrays.asList(o1, o2, o3, o4, o5, o6, o7, o8, o9)); } /** * Concatenates a sequence of Observables eagerly into a single stream of values. * <p> * Eager concatenation means that once a subscriber subscribes, this operator subscribes to all of the * source Observables. The operator buffers the values emitted by these Observables and then drains them * in order, each one after the previous one completes. * <dl> * <dt><b>Backpressure:</b></dt> * <dd>Backpressure is honored towards the downstream, however, due to the eagerness requirement, sources * are subscribed to in unbounded mode and their values are queued up in an unbounded buffer.</dd> * <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 Observables that need to be eagerly concatenated * @return * @warn javadoc fails to describe the return value * @since (if this graduates from Experimental/Beta to supported, replace this parenthetical with the release number) */ @Experimental @SuppressWarnings({ "unchecked", "rawtypes" }) public static <T> Observable<T> concatEager(Iterable<? extends Observable<? extends T>> sources) { return Observable.from(sources).concatMapEager((Func1)UtilityFunctions.identity()); } /** * Concatenates a sequence of Observables eagerly into a single stream of values. * <p> * Eager concatenation means that once a subscriber subscribes, this operator subscribes to all of the * source Observables. The operator buffers the values emitted by these Observables and then drains them * in order, each one after the previous one completes. * <dl> * <dt><b>Backpressure:</b></dt> * <dd>Backpressure is honored towards the downstream, however, due to the eagerness requirement, sources * are subscribed to in unbounded mode and their values are queued up in an unbounded buffer.</dd> * <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 Observables that need to be eagerly concatenated * @param capacityHint hints about the number of expected source sequence values * @return * @warn javadoc fails to describe the return value * @since (if this graduates from Experimental/Beta to supported, replace this parenthetical with the release number) */ @Experimental @SuppressWarnings({ "unchecked", "rawtypes" }) public static <T> Observable<T> concatEager(Iterable<? extends Observable<? extends T>> sources, int capacityHint) { return Observable.from(sources).concatMapEager((Func1)UtilityFunctions.identity(), capacityHint); } /** * Concatenates an Observable sequence of Observables eagerly into a single stream of values. * <p> * Eager concatenation means that once a subscriber subscribes, this operator subscribes to all of the * emitted source Observables as they are observed. The operator buffers the values emitted by these * Observables and then drains them in order, each one after the previous one completes. * <dl> * <dt><b>Backpressure:</b></dt> * <dd>Backpressure is honored towards the downstream, however, due to the eagerness requirement, sources * are subscribed to in unbounded mode and their values are queued up in an unbounded buffer.</dd> * <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 Observables that need to be eagerly concatenated * @return * @warn javadoc fails to describe the return value * @since (if this graduates from Experimental/Beta to supported, replace this parenthetical with the release number) */ @Experimental @SuppressWarnings({ "unchecked", "rawtypes" }) public static <T> Observable<T> concatEager(Observable<? extends Observable<? extends T>> sources) { return sources.concatMapEager((Func1)UtilityFunctions.identity()); } /** * Concatenates an Observable sequence of Observables eagerly into a single stream of values. * <p> * Eager concatenation means that once a subscriber subscribes, this operator subscribes to all of the * emitted source Observables as they are observed. The operator buffers the values emitted by these * Observables and then drains them in order, each one after the previous one completes. * <dl> * <dt><b>Backpressure:</b></dt> * <dd>Backpressure is honored towards the downstream, however, due to the eagerness requirement, sources * are subscribed to in unbounded mode and their values are queued up in an unbounded buffer.</dd> * <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 Observables that need to be eagerly concatenated * @param capacityHint hints about the number of expected source sequence values * @return * @warn javadoc fails to describe the return value * @since (if this graduates from Experimental/Beta to supported, replace this parenthetical with the release number) */ @Experimental @SuppressWarnings({ "unchecked", "rawtypes" }) public static <T> Observable<T> concatEager(Observable<? extends Observable<? extends T>> sources, int capacityHint) { return sources.concatMapEager((Func1)UtilityFunctions.identity(), capacityHint); } /** * Maps a sequence of values into Observables and concatenates these Observables eagerly into a single * Observable. * <p> * Eager concatenation means that once a subscriber subscribes, this operator subscribes to all of the * source Observables. The operator buffers the values emitted by these Observables and then drains them in * order, each one after the previous one completes. * <dl> * <dt><b>Backpressure:</b></dt> * <dd>Backpressure is honored towards the downstream, however, due to the eagerness requirement, sources * are subscribed to in unbounded mode and their values are queued up in an unbounded buffer.</dd> * <dt><b>Scheduler:</b></dt> * <dd>This method does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * @param <R> the value type * @param mapper the function that maps a sequence of values into a sequence of Observables that will be * eagerly concatenated * @return * @warn javadoc fails to describe the return value * @since (if this graduates from Experimental/Beta to supported, replace this parenthetical with the release number) */ @Experimental public final <R> Observable<R> concatMapEager(Func1<? super T, ? extends Observable<? extends R>> mapper) { return concatMapEager(mapper, RxRingBuffer.SIZE); } /** * Maps a sequence of values into Observables and concatenates these Observables eagerly into a single * Observable. * <p> * Eager concatenation means that once a subscriber subscribes, this operator subscribes to all of the * source Observables. The operator buffers the values emitted by these Observables and then drains them in * order, each one after the previous one completes. * <dl> * <dt><b>Backpressure:</b></dt> * <dd>Backpressure is honored towards the downstream, however, due to the eagerness requirement, sources * are subscribed to in unbounded mode and their values are queued up in an unbounded buffer.</dd> * <dt><b>Scheduler:</b></dt> * <dd>This method does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * @param <R> the value type * @param mapper the function that maps a sequence of values into a sequence of Observables that will be * eagerly concatenated * @param capacityHint hints about the number of expected source sequence values * @return * @warn javadoc fails to describe the return value * @since (if this graduates from Experimental/Beta to supported, replace this parenthetical with the release number) */ @Experimental public final <R> Observable<R> concatMapEager(Func1<? super T, ? extends Observable<? extends R>> mapper, int capacityHint) { if (capacityHint < 1) { throw new IllegalArgumentException("capacityHint > 0 required but it was " + capacityHint); } return lift(new OperatorEagerConcatMap<T, R>(mapper, capacityHint)); } /** * Returns an Observable that emits the single item at a specified index in a sequence of emissions from a * source Observbable. * <p> * <img width="640" height="310" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/elementAt.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code elementAt} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param index * the zero-based index of the item to retrieve * @return an Observable that emits a single item: the item at the specified position in the sequence of * those emitted by the source Observable * @throws IndexOutOfBoundsException * if {@code index} is greater than or equal to the number of items emitted by the source * Observable, or * if {@code index} is less than 0 * @see <a href="http://reactivex.io/documentation/operators/elementat.html">ReactiveX operators documentation: ElementAt</a> */ public final Observable<T> elementAt(int index) { return lift(new OperatorElementAt<T>(index)); } /** * Returns an Observable that emits the item found at a specified index in a sequence of emissions from a * source Observable, or a default item if that index is out of range. * <p> * <img width="640" height="310" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/elementAtOrDefault.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code elementAtOrDefault} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param index * the zero-based index of the item to retrieve * @param defaultValue * the default item * @return an Observable that emits the item at the specified position in the sequence emitted by the source * Observable, or the default item if that index is outside the bounds of the source sequence * @throws IndexOutOfBoundsException * if {@code index} is less than 0 * @see <a href="http://reactivex.io/documentation/operators/elementat.html">ReactiveX operators documentation: ElementAt</a> */ public final Observable<T> elementAtOrDefault(int index, T defaultValue) { return lift(new OperatorElementAt<T>(index, defaultValue)); } /** * Returns an Observable that emits {@code true} if any item emitted by the source Observable satisfies a * specified condition, otherwise {@code false}. <em>Note:</em> this always emits {@code false} if the * source Observable is empty. * <p> * <img width="640" height="320" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/exists.png" alt=""> * <p> * In Rx.Net this is the {@code any} Observer but we renamed it in RxJava to better match Java naming * idioms. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code exists} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param predicate * the condition to test items emitted by the source Observable * @return an Observable that emits a Boolean that indicates whether any item emitted by the source * Observable satisfies the {@code predicate} * @see <a href="http://reactivex.io/documentation/operators/contains.html">ReactiveX operators documentation: Contains</a> */ public final Observable<Boolean> exists(Func1<? super T, Boolean> predicate) { return lift(new OperatorAny<T>(predicate, false)); } /** * Filters items emitted by an Observable by only emitting those that satisfy a specified predicate. * <p> * <img width="640" height="310" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/filter.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code filter} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param predicate * a function that evaluates each item emitted by the source Observable, returning {@code true} * if it passes the filter * @return an Observable that emits only those items emitted by the source Observable that the filter * evaluates as {@code true} * @see <a href="http://reactivex.io/documentation/operators/filter.html">ReactiveX operators documentation: Filter</a> */ public final Observable<T> filter(Func1<? super T, Boolean> predicate) { return lift(new OperatorFilter<T>(predicate)); } /** * Registers an {@link Action0} to be called when this Observable invokes either * {@link Observer#onCompleted onCompleted} or {@link Observer#onError onError}. * <p> * <img width="640" height="310" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/finallyDo.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code finallyDo} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param action * an {@link Action0} to be invoked when the source Observable finishes * @return an Observable that emits the same items as the source Observable, then invokes the * {@link Action0} * @see <a href="http://reactivex.io/documentation/operators/do.html">ReactiveX operators documentation: Do</a> * @see #doOnTerminate(Action0) */ public final Observable<T> finallyDo(Action0 action) { return lift(new OperatorFinally<T>(action)); } /** * Returns an Observable that emits only the very first item emitted by the source Observable, or notifies * of an {@code NoSuchElementException} if the source Observable is empty. * <p> * <img width="640" height="310" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/first.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code first} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @return an Observable that emits only the very first item emitted by the source Observable, or raises an * {@code NoSuchElementException} if the source Observable is empty * @see <a href="http://reactivex.io/documentation/operators/first.html">ReactiveX operators documentation: First</a> */ public final Observable<T> first() { return take(1).single(); } /** * Returns an Observable that emits only the very first item emitted by the source Observable that satisfies * a specified condition, or notifies of an {@code NoSuchElementException} if no such items are emitted. * <p> * <img width="640" height="310" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/firstN.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code first} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param predicate * the condition that an item emitted by the source Observable has to satisfy * @return an Observable that emits only the very first item emitted by the source Observable that satisfies * the {@code predicate}, or raises an {@code NoSuchElementException} if no such items are emitted * @see <a href="http://reactivex.io/documentation/operators/first.html">ReactiveX operators documentation: First</a> */ public final Observable<T> first(Func1<? super T, Boolean> predicate) { return takeFirst(predicate).single(); } /** * Returns an Observable that emits only the very first item emitted by the source Observable, or a default * item if the source Observable completes without emitting anything. * <p> * <img width="640" height="305" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/firstOrDefault.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code firstOrDefault} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param defaultValue * the default item to emit if the source Observable doesn't emit anything * @return an Observable that emits only the very first item from the source, or a default item if the * source Observable completes without emitting any items * @see <a href="http://reactivex.io/documentation/operators/first.html">ReactiveX operators documentation: First</a> */ public final Observable<T> firstOrDefault(T defaultValue) { return take(1).singleOrDefault(defaultValue); } /** * Returns an Observable that emits only the very first item emitted by the source Observable that satisfies * a specified condition, or a default item if the source Observable emits no such items. * <p> * <img width="640" height="310" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/firstOrDefaultN.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code firstOrDefault} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param predicate * the condition any item emitted by the source Observable has to satisfy * @param defaultValue * the default item to emit if the source Observable doesn't emit anything that satisfies the * {@code predicate} * @return an Observable that emits only the very first item emitted by the source Observable that satisfies * the {@code predicate}, or a default item if the source Observable emits no such items * @see <a href="http://reactivex.io/documentation/operators/first.html">ReactiveX operators documentation: First</a> */ public final Observable<T> firstOrDefault(T defaultValue, Func1<? super T, Boolean> predicate) { return takeFirst(predicate).singleOrDefault(defaultValue); } /** * Returns an Observable that emits items based on applying a function that you supply to each item emitted * by the source Observable, where that function returns an Observable, and then merging those resulting * Observables and emitting the results of this merger. * <p> * <img width="640" height="310" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/flatMap.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code flatMap} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param func * a function that, when applied to an item emitted by the source Observable, returns an * Observable * @return an Observable that emits the result of applying the transformation function to each item emitted * by the source Observable and merging the results of the Observables obtained from this * transformation * @see <a href="http://reactivex.io/documentation/operators/flatmap.html">ReactiveX operators documentation: FlatMap</a> */ public final <R> Observable<R> flatMap(Func1<? super T, ? extends Observable<? extends R>> func) { if (getClass() == ScalarSynchronousObservable.class) { return ((ScalarSynchronousObservable<T>)this).scalarFlatMap(func); } return merge(map(func)); } /** * Returns an Observable that emits items based on applying a function that you supply to each item emitted * by the source Observable, where that function returns an Observable, and then merging those resulting * Observables and emitting the results of this merger, while limiting the maximum number of concurrent * subscriptions to these Observables. * <p> * <!-- <img width="640" height="310" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/flatMap.png" alt=""> --> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code flatMap} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param func * a function that, when applied to an item emitted by the source Observable, returns an * Observable * @param maxConcurrent * the maximum number of Observables that may be subscribed to concurrently * @return an Observable that emits the result of applying the transformation function to each item emitted * by the source Observable and merging the results of the Observables obtained from this * transformation * @see <a href="http://reactivex.io/documentation/operators/flatmap.html">ReactiveX operators documentation: FlatMap</a> * @since (if this graduates from Experimental/Beta to supported, replace this parenthetical with the release number) */ @Beta public final <R> Observable<R> flatMap(Func1<? super T, ? extends Observable<? extends R>> func, int maxConcurrent) { if (getClass() == ScalarSynchronousObservable.class) { return ((ScalarSynchronousObservable<T>)this).scalarFlatMap(func); } return merge(map(func), maxConcurrent); } /** * Returns an Observable that applies a function to each item emitted or notification raised by the source * Observable and then flattens the Observables returned from these functions and emits the resulting items. * <p> * <img width="640" height="410" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/mergeMap.nce.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code flatMap} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param <R> * the result type * @param onNext * a function that returns an Observable to merge for each item emitted by the source Observable * @param onError * a function that returns an Observable to merge for an onError notification from the source * Observable * @param onCompleted * a function that returns an Observable to merge for an onCompleted notification from the source * Observable * @return an Observable that emits the results of merging the Observables returned from applying the * specified functions to the emissions and notifications of the source Observable * @see <a href="http://reactivex.io/documentation/operators/flatmap.html">ReactiveX operators documentation: FlatMap</a> */ public final <R> Observable<R> flatMap( Func1<? super T, ? extends Observable<? extends R>> onNext, Func1<? super Throwable, ? extends Observable<? extends R>> onError, Func0<? extends Observable<? extends R>> onCompleted) { return merge(mapNotification(onNext, onError, onCompleted)); } /** * Returns an Observable that applies a function to each item emitted or notification raised by the source * Observable and then flattens the Observables returned from these functions and emits the resulting items, * while limiting the maximum number of concurrent subscriptions to these Observables. * <p> * <!-- <img width="640" height="410" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/mergeMap.nce.png" alt=""> --> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code flatMap} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param <R> * the result type * @param onNext * a function that returns an Observable to merge for each item emitted by the source Observable * @param onError * a function that returns an Observable to merge for an onError notification from the source * Observable * @param onCompleted * a function that returns an Observable to merge for an onCompleted notification from the source * Observable * @param maxConcurrent * the maximum number of Observables that may be subscribed to concurrently * @return an Observable that emits the results of merging the Observables returned from applying the * specified functions to the emissions and notifications of the source Observable * @see <a href="http://reactivex.io/documentation/operators/flatmap.html">ReactiveX operators documentation: FlatMap</a> * @since (if this graduates from Experimental/Beta to supported, replace this parenthetical with the release number) */ @Beta public final <R> Observable<R> flatMap( Func1<? super T, ? extends Observable<? extends R>> onNext, Func1<? super Throwable, ? extends Observable<? extends R>> onError, Func0<? extends Observable<? extends R>> onCompleted, int maxConcurrent) { return merge(mapNotification(onNext, onError, onCompleted), maxConcurrent); } /** * Returns an Observable that emits the results of a specified function to the pair of values emitted by the * source Observable and a specified collection Observable. * <p> * <img width="640" height="390" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/mergeMap.r.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code flatMap} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param <U> * the type of items emitted by the collection Observable * @param <R> * the type of items emitted by the resulting Observable * @param collectionSelector * a function that returns an Observable for each item emitted by the source Observable * @param resultSelector * a function that combines one item emitted by each of the source and collection Observables and * returns an item to be emitted by the resulting Observable * @return an Observable that emits the results of applying a function to a pair of values emitted by the * source Observable and the collection Observable * @see <a href="http://reactivex.io/documentation/operators/flatmap.html">ReactiveX operators documentation: FlatMap</a> */ public final <U, R> Observable<R> flatMap(final Func1<? super T, ? extends Observable<? extends U>> collectionSelector, final Func2<? super T, ? super U, ? extends R> resultSelector) { return merge(lift(new OperatorMapPair<T, U, R>(collectionSelector, resultSelector))); } /** * Returns an Observable that emits the results of a specified function to the pair of values emitted by the * source Observable and a specified collection Observable, while limiting the maximum number of concurrent * subscriptions to these Observables. * <p> * <!-- <img width="640" height="390" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/mergeMap.r.png" alt=""> --> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code flatMap} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param <U> * the type of items emitted by the collection Observable * @param <R> * the type of items emitted by the resulting Observable * @param collectionSelector * a function that returns an Observable for each item emitted by the source Observable * @param resultSelector * a function that combines one item emitted by each of the source and collection Observables and * returns an item to be emitted by the resulting Observable * @param maxConcurrent * the maximum number of Observables that may be subscribed to concurrently * @return an Observable that emits the results of applying a function to a pair of values emitted by the * source Observable and the collection Observable * @see <a href="http://reactivex.io/documentation/operators/flatmap.html">ReactiveX operators documentation: FlatMap</a> * @since (if this graduates from Experimental/Beta to supported, replace this parenthetical with the release number) */ @Beta public final <U, R> Observable<R> flatMap(final Func1<? super T, ? extends Observable<? extends U>> collectionSelector, final Func2<? super T, ? super U, ? extends R> resultSelector, int maxConcurrent) { return merge(lift(new OperatorMapPair<T, U, R>(collectionSelector, resultSelector)), maxConcurrent); } /** * Returns an Observable that merges each item emitted by the source Observable with the values in an * Iterable corresponding to that item that is generated by a selector. * <p> * <img width="640" height="310" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/mergeMapIterable.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code flatMapIterable} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param <R> * the type of item emitted by the resulting Observable * @param collectionSelector * a function that returns an Iterable sequence of values for when given an item emitted by the * source Observable * @return an Observable that emits the results of merging the items emitted by the source Observable with * the values in the Iterables corresponding to those items, as generated by {@code collectionSelector} * @see <a href="http://reactivex.io/documentation/operators/flatmap.html">ReactiveX operators documentation: FlatMap</a> */ public final <R> Observable<R> flatMapIterable(Func1<? super T, ? extends Iterable<? extends R>> collectionSelector) { return merge(map(OperatorMapPair.convertSelector(collectionSelector))); } /** * Returns an Observable that emits the results of applying a function to the pair of values from the source * Observable and an Iterable corresponding to that item that is generated by a selector. * <p> * <img width="640" height="390" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/mergeMapIterable.r.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code flatMapIterable} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param <U> * the collection element type * @param <R> * the type of item emited by the resulting Observable * @param collectionSelector * a function that returns an Iterable sequence of values for each item emitted by the source * Observable * @param resultSelector * a function that returns an item based on the item emitted by the source Observable and the * Iterable returned for that item by the {@code collectionSelector} * @return an Observable that emits the items returned by {@code resultSelector} for each item in the source * Observable * @see <a href="http://reactivex.io/documentation/operators/flatmap.html">ReactiveX operators documentation: FlatMap</a> */ public final <U, R> Observable<R> flatMapIterable(Func1<? super T, ? extends Iterable<? extends U>> collectionSelector, Func2<? super T, ? super U, ? extends R> resultSelector) { return flatMap(OperatorMapPair.convertSelector(collectionSelector), resultSelector); } /** * Subscribes to the {@link Observable} and receives notifications for each element. * <p> * Alias to {@link #subscribe(Action1)} * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code forEach} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param onNext * {@link Action1} to execute for each item. * @throws IllegalArgumentException * if {@code onNext} is null * @throws OnErrorNotImplementedException * if the Observable calls {@code onError} * @see <a href="http://reactivex.io/documentation/operators/subscribe.html">ReactiveX operators documentation: Subscribe</a> */ public final void forEach(final Action1<? super T> onNext) { subscribe(onNext); } /** * Subscribes to the {@link Observable} and receives notifications for each element and error events. * <p> * Alias to {@link #subscribe(Action1, Action1)} * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code forEach} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param onNext * {@link Action1} to execute for each item. * @param onError * {@link Action1} to execute when an error is emitted. * @throws IllegalArgumentException * if {@code onNext} is null, or * if {@code onError} is null * @throws OnErrorNotImplementedException * if the Observable calls {@code onError} * @see <a href="http://reactivex.io/documentation/operators/subscribe.html">ReactiveX operators documentation: Subscribe</a> */ public final void forEach(final Action1<? super T> onNext, final Action1<Throwable> onError) { subscribe(onNext, onError); } /** * Subscribes to the {@link Observable} and receives notifications for each element and the terminal events. * <p> * Alias to {@link #subscribe(Action1, Action1, Action0)} * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code forEach} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param onNext * {@link Action1} to execute for each item. * @param onError * {@link Action1} to execute when an error is emitted. * @param onComplete * {@link Action0} to execute when completion is signalled. * @throws IllegalArgumentException * if {@code onNext} is null, or * if {@code onError} is null, or * if {@code onComplete} is null * @throws OnErrorNotImplementedException * if the Observable calls {@code onError} * @see <a href="http://reactivex.io/documentation/operators/subscribe.html">ReactiveX operators documentation: Subscribe</a> */ public final void forEach(final Action1<? super T> onNext, final Action1<Throwable> onError, final Action0 onComplete) { subscribe(onNext, onError, onComplete); } /** * Groups the items emitted by an {@code Observable} according to a specified criterion, and emits these * grouped items as {@link GroupedObservable}s, one {@code GroupedObservable} per group. * <p> * <img width="640" height="360" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/groupBy.png" alt=""> * <p> * <em>Note:</em> A {@link GroupedObservable} will cache the items it is to emit until such time as it * is subscribed to. For this reason, in order to avoid memory leaks, you should not simply ignore those * {@code GroupedObservable}s that do not concern you. Instead, you can signal to them that they may * discard their buffers by applying an operator like {@link #take}{@code (0)} to them. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code groupBy} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param keySelector * a function that extracts the key for each item * @param elementSelector * a function that extracts the return element for each item * @param <K> * the key type * @param <R> * the element type * @return an {@code Observable} that emits {@link GroupedObservable}s, each of which corresponds to a * unique key value and each of which emits those items from the source Observable that share that * key value * @see <a href="http://reactivex.io/documentation/operators/groupby.html">ReactiveX operators documentation: GroupBy</a> */ public final <K, R> Observable<GroupedObservable<K, R>> groupBy(final Func1<? super T, ? extends K> keySelector, final Func1<? super T, ? extends R> elementSelector) { return lift(new OperatorGroupBy<T, K, R>(keySelector, elementSelector)); } /** * Groups the items emitted by an {@code Observable} according to a specified criterion, and emits these * grouped items as {@link GroupedObservable}s, one {@code GroupedObservable} per group. * <p> * <img width="640" height="360" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/groupBy.png" alt=""> * <p> * <em>Note:</em> A {@link GroupedObservable} will cache the items it is to emit until such time as it * is subscribed to. For this reason, in order to avoid memory leaks, you should not simply ignore those * {@code GroupedObservable}s that do not concern you. Instead, you can signal to them that they may * discard their buffers by applying an operator like {@link #take}{@code (0)} to them. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code groupBy} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param keySelector * a function that extracts the key for each item * @param <K> * the key type * @return an {@code Observable} that emits {@link GroupedObservable}s, each of which corresponds to a * unique key value and each of which emits those items from the source Observable that share that * key value * @see <a href="http://reactivex.io/documentation/operators/groupby.html">ReactiveX operators documentation: GroupBy</a> */ public final <K> Observable<GroupedObservable<K, T>> groupBy(final Func1<? super T, ? extends K> keySelector) { return lift(new OperatorGroupBy<T, K, T>(keySelector)); } /** * Returns an Observable that correlates two Observables when they overlap in time and groups the results. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/groupJoin.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code groupJoin} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param right * the other Observable to correlate items from the source Observable with * @param leftDuration * a function that returns an Observable whose emissions indicate the duration of the values of * the source Observable * @param rightDuration * a function that returns an Observable whose emissions indicate the duration of the values of * the {@code right} Observable * @param resultSelector * a function that takes an item emitted by each Observable and returns the value to be emitted * by the resulting Observable * @return an Observable that emits items based on combining those items emitted by the source Observables * whose durations overlap * @see <a href="http://reactivex.io/documentation/operators/join.html">ReactiveX operators documentation: Join</a> */ public final <T2, D1, D2, R> Observable<R> groupJoin(Observable<T2> right, Func1<? super T, ? extends Observable<D1>> leftDuration, Func1<? super T2, ? extends Observable<D2>> rightDuration, Func2<? super T, ? super Observable<T2>, ? extends R> resultSelector) { return create(new OnSubscribeGroupJoin<T, T2, D1, D2, R>(this, right, leftDuration, rightDuration, resultSelector)); } /** * Ignores all items emitted by the source Observable and only calls {@code onCompleted} or {@code onError}. * <p> * <img width="640" height="305" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/ignoreElements.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code ignoreElements} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @return an empty Observable that only calls {@code onCompleted} or {@code onError}, based on which one is * called by the source Observable * @see <a href="http://reactivex.io/documentation/operators/ignoreelements.html">ReactiveX operators documentation: IgnoreElements</a> */ public final Observable<T> ignoreElements() { return lift(OperatorIgnoreElements.<T> instance()); } /** * Returns an Observable that emits {@code true} if the source Observable is empty, otherwise {@code false}. * <p> * In Rx.Net this is negated as the {@code any} Observer but we renamed this in RxJava to better match Java * naming idioms. * <p> * <img width="640" height="320" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/isEmpty.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code isEmpty} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @return an Observable that emits a Boolean * @see <a href="http://reactivex.io/documentation/operators/contains.html">ReactiveX operators documentation: Contains</a> */ @SuppressWarnings("unchecked") public final Observable<Boolean> isEmpty() { return lift((OperatorAny<T>) HolderAnyForEmpty.INSTANCE); } private static class HolderAnyForEmpty { static final OperatorAny<?> INSTANCE = new OperatorAny<Object>(UtilityFunctions.alwaysTrue(), true); } /** * Correlates the items emitted by two Observables based on overlapping durations. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/join_.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code join} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param right * the second Observable to join items from * @param leftDurationSelector * a function to select a duration for each item emitted by the source Observable, used to * determine overlap * @param rightDurationSelector * a function to select a duration for each item emitted by the {@code right} Observable, used to * determine overlap * @param resultSelector * a function that computes an item to be emitted by the resulting Observable for any two * overlapping items emitted by the two Observables * @return an Observable that emits items correlating to items emitted by the source Observables that have * overlapping durations * @see <a href="http://reactivex.io/documentation/operators/join.html">ReactiveX operators documentation: Join</a> */ public final <TRight, TLeftDuration, TRightDuration, R> Observable<R> join(Observable<TRight> right, Func1<T, Observable<TLeftDuration>> leftDurationSelector, Func1<TRight, Observable<TRightDuration>> rightDurationSelector, Func2<T, TRight, R> resultSelector) { return create(new OnSubscribeJoin<T, TRight, TLeftDuration, TRightDuration, R>(this, right, leftDurationSelector, rightDurationSelector, resultSelector)); } /** * Returns an Observable that emits the last item emitted by the source Observable or notifies observers of * a {@code NoSuchElementException} if the source Observable is empty. * <p> * <img width="640" height="305" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/last.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code last} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @return an Observable that emits the last item from the source Observable or notifies observers of an * error * @see <a href="http://reactivex.io/documentation/operators/last.html">ReactiveX operators documentation: Last</a> */ public final Observable<T> last() { return takeLast(1).single(); } /** * Returns an Observable that emits only the last item emitted by the source Observable that satisfies a * given condition, or notifies of a {@code NoSuchElementException} if no such items are emitted. * <p> * <img width="640" height="305" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/last.p.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code last} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param predicate * the condition any source emitted item has to satisfy * @return an Observable that emits only the last item satisfying the given condition from the source, or an * {@code NoSuchElementException} if no such items are emitted * @throws IllegalArgumentException * if no items that match the predicate are emitted by the source Observable * @see <a href="http://reactivex.io/documentation/operators/last.html">ReactiveX operators documentation: Last</a> */ public final Observable<T> last(Func1<? super T, Boolean> predicate) { return filter(predicate).takeLast(1).single(); } /** * Returns an Observable that emits only the last item emitted by the source Observable, or a default item * if the source Observable completes without emitting any items. * <p> * <img width="640" height="305" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/lastOrDefault.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code lastOrDefault} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param defaultValue * the default item to emit if the source Observable is empty * @return an Observable that emits only the last item emitted by the source Observable, or a default item * if the source Observable is empty * @see <a href="http://reactivex.io/documentation/operators/last.html">ReactiveX operators documentation: Last</a> */ public final Observable<T> lastOrDefault(T defaultValue) { return takeLast(1).singleOrDefault(defaultValue); } /** * Returns an Observable that emits only the last item emitted by the source Observable that satisfies a * specified condition, or a default item if no such item is emitted by the source Observable. * <p> * <img width="640" height="315" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/lastOrDefault.p.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code lastOrDefault} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param defaultValue * the default item to emit if the source Observable doesn't emit anything that satisfies the * specified {@code predicate} * @param predicate * the condition any item emitted by the source Observable has to satisfy * @return an Observable that emits only the last item emitted by the source Observable that satisfies the * given condition, or a default item if no such item is emitted by the source Observable * @see <a href="http://reactivex.io/documentation/operators/last.html">ReactiveX operators documentation: Last</a> */ public final Observable<T> lastOrDefault(T defaultValue, Func1<? super T, Boolean> predicate) { return filter(predicate).takeLast(1).singleOrDefault(defaultValue); } /** * Returns an Observable that emits only the first {@code count} items emitted by the source Observable. * <p> * Alias of {@link #take(int)} to match Java 8 Stream API naming convention. * <p> * <img width="640" height="305" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/take.png" alt=""> * <p> * This method returns an Observable that will invoke a subscribing {@link Observer}'s * {@link Observer#onNext onNext} function a maximum of {@code count} times before invoking * {@link Observer#onCompleted onCompleted}. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code limit} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param count * the maximum number of items to emit * @return an Observable that emits only the first {@code count} items emitted by the source Observable, or * all of the items from the source Observable if that Observable emits fewer than {@code count} items * @see <a href="http://reactivex.io/documentation/operators/take.html">ReactiveX operators documentation: Take</a> */ public final Observable<T> limit(int count) { return take(count); } /** * Returns an Observable that applies a specified function to each item emitted by the source Observable and * emits the results of these function applications. * <p> * <img width="640" height="305" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/map.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code map} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param func * a function to apply to each item emitted by the Observable * @return an Observable that emits the items from the source Observable, transformed by the specified * function * @see <a href="http://reactivex.io/documentation/operators/map.html">ReactiveX operators documentation: Map</a> */ public final <R> Observable<R> map(Func1<? super T, ? extends R> func) { return lift(new OperatorMap<T, R>(func)); } private final <R> Observable<R> mapNotification(Func1<? super T, ? extends R> onNext, Func1<? super Throwable, ? extends R> onError, Func0<? extends R> onCompleted) { return lift(new OperatorMapNotification<T, R>(onNext, onError, onCompleted)); } /** * Returns an Observable that represents all of the emissions <em>and</em> notifications from the source * Observable into emissions marked with their original types within {@link Notification} objects. * <p> * <img width="640" height="315" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/materialize.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code materialize} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @return an Observable that emits items that are the result of materializing the items and notifications * of the source Observable * @see <a href="http://reactivex.io/documentation/operators/materialize-dematerialize.html">ReactiveX operators documentation: Materialize</a> */ public final Observable<Notification<T>> materialize() { return lift(OperatorMaterialize.<T>instance()); } /** * Flattens this and another Observable into a single Observable, without any transformation. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/merge.png" alt=""> * <p> * You can combine items emitted by multiple Observables so that they appear as a single Observable, by * using the {@code mergeWith} method. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code mergeWith} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param t1 * an Observable to be merged * @return an Observable that emits all of the items emitted by the source Observables * @see <a href="http://reactivex.io/documentation/operators/merge.html">ReactiveX operators documentation: Merge</a> */ public final Observable<T> mergeWith(Observable<? extends T> t1) { return merge(this, t1); } /** * Modifies an Observable to perform its emissions and notifications on a specified {@link Scheduler}, * asynchronously with an unbounded buffer. * <p> * <img width="640" height="308" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/observeOn.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>you specify which {@link Scheduler} this operator will use</dd> * </dl> * * @param scheduler * the {@link Scheduler} to notify {@link Observer}s on * @return the source Observable modified so that its {@link Observer}s are notified on the specified * {@link Scheduler} * @see <a href="http://reactivex.io/documentation/operators/observeon.html">ReactiveX operators documentation: ObserveOn</a> * @see <a href="http://www.grahamlea.com/2014/07/rxjava-threading-examples/">RxJava Threading Examples</a> * @see #subscribeOn */ public final Observable<T> observeOn(Scheduler scheduler) { if (this instanceof ScalarSynchronousObservable) { return ((ScalarSynchronousObservable<T>)this).scalarScheduleOn(scheduler); } return lift(new OperatorObserveOn<T>(scheduler)); } /** * Filters the items emitted by an Observable, only emitting those of the specified type. * <p> * <img width="640" height="310" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/ofClass.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code ofType} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param klass * the class type to filter the items emitted by the source Observable * @return an Observable that emits items from the source Observable of type {@code klass} * @see <a href="http://reactivex.io/documentation/operators/filter.html">ReactiveX operators documentation: Filter</a> */ public final <R> Observable<R> ofType(final Class<R> klass) { return filter(new Func1<T, Boolean>() { @Override public final Boolean call(T t) { return klass.isInstance(t); } }).cast(klass); } /** * Instructs an Observable that is emitting items faster than its observer can consume them to buffer these * items indefinitely until they can be emitted. * <p> * <img width="640" height="300" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/bp.obp.buffer.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code onBackpressureBuffer} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @return the source Observable modified to buffer items to the extent system resources allow * @see <a href="http://reactivex.io/documentation/operators/backpressure.html">ReactiveX operators documentation: backpressure operators</a> */ public final Observable<T> onBackpressureBuffer() { return lift(OperatorOnBackpressureBuffer.<T> instance()); } /** * Instructs an Observable that is emitting items faster than its observer can consume them to buffer up to * a given amount of items until they can be emitted. The resulting Observable will {@code onError} emitting * a {@code BufferOverflowException} as soon as the buffer's capacity is exceeded, dropping all undelivered * items, and unsubscribing from the source. * <p> * <img width="640" height="300" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/bp.obp.buffer.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code onBackpressureBuffer} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @return the source Observable modified to buffer items up to the given capacity * @see <a href="http://reactivex.io/documentation/operators/backpressure.html">ReactiveX operators documentation: backpressure operators</a> * @since (if this graduates from Experimental/Beta to supported, replace this parenthetical with the release number) */ @Beta public final Observable<T> onBackpressureBuffer(long capacity) { return lift(new OperatorOnBackpressureBuffer<T>(capacity)); } /** * Instructs an Observable that is emitting items faster than its observer can consume them to buffer up to * a given amount of items until they can be emitted. The resulting Observable will {@code onError} emitting * a {@code BufferOverflowException} as soon as the buffer's capacity is exceeded, dropping all undelivered * items, unsubscribing from the source, and notifying the producer with {@code onOverflow}. * <p> * <img width="640" height="300" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/bp.obp.buffer.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code onBackpressureBuffer} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @return the source Observable modified to buffer items up to the given capacity * @see <a href="http://reactivex.io/documentation/operators/backpressure.html">ReactiveX operators documentation: backpressure operators</a> * @since (if this graduates from Experimental/Beta to supported, replace this parenthetical with the release number) */ @Beta public final Observable<T> onBackpressureBuffer(long capacity, Action0 onOverflow) { return lift(new OperatorOnBackpressureBuffer<T>(capacity, onOverflow)); } /** * Instructs an Observable that is emitting items faster than its observer can consume them to discard, * rather than emit, those items that its observer is not prepared to observe. * <p> * <img width="640" height="245" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/bp.obp.drop.png" alt=""> * <p> * If the downstream request count hits 0 then the Observable will refrain from calling {@code onNext} until * the observer invokes {@code request(n)} again to increase the request count. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code onBackpressureDrop} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param onDrop the action to invoke for each item dropped. onDrop action should be fast and should never block. * @return the source Observable modified to drop {@code onNext} notifications on overflow * @see <a href="http://reactivex.io/documentation/operators/backpressure.html">ReactiveX operators documentation: backpressure operators</a> * @Experimental The behavior of this can change at any time. * @since (if this graduates from Experimental/Beta to supported, replace this parenthetical with the release number) */ @Experimental public final Observable<T> onBackpressureDrop(Action1<? super T> onDrop) { return lift(new OperatorOnBackpressureDrop<T>(onDrop)); } /** * Instructs an Observable that is emitting items faster than its observer can consume them to discard, * rather than emit, those items that its observer is not prepared to observe. * <p> * <img width="640" height="245" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/bp.obp.drop.png" alt=""> * <p> * If the downstream request count hits 0 then the Observable will refrain from calling {@code onNext} until * the observer invokes {@code request(n)} again to increase the request count. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code onBackpressureDrop} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @return the source Observable modified to drop {@code onNext} notifications on overflow * @see <a href="http://reactivex.io/documentation/operators/backpressure.html">ReactiveX operators documentation: backpressure operators</a> */ public final Observable<T> onBackpressureDrop() { return lift(OperatorOnBackpressureDrop.<T>instance()); } /** * Instructs an Observable that is emitting items faster than its observer can consume them to * block the producer thread. * <p> * <img width="640" height="245" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/bp.obp.block.png" alt=""> * <p> * The producer side can emit up to {@code maxQueueLength} onNext elements without blocking, but the * consumer side considers the amount its downstream requested through {@code Producer.request(n)} * and doesn't emit more than requested even if more is available. For example, using * {@code onBackpressureBlock(384).observeOn(Schedulers.io())} will not throw a MissingBackpressureException. * <p> * Note that if the upstream Observable does support backpressure, this operator ignores that capability * and doesn't propagate any backpressure requests from downstream. * <p> * Warning! Using a chain like {@code source.onBackpressureBlock().subscribeOn(scheduler)} is prone to * deadlocks because the consumption of the internal queue is scheduled behind a blocked emission by * the subscribeOn. In order to avoid this, the operators have to be swapped in the chain: * {@code source.subscribeOn(scheduler).onBackpressureBlock()} and in general, no subscribeOn operator should follow * this operator. * * @param maxQueueLength the maximum number of items the producer can emit without blocking * @return the source Observable modified to block {@code onNext} notifications on overflow * @see <a href="http://reactivex.io/documentation/operators/backpressure.html">ReactiveX operators documentation: backpressure operators</a> * @Experimental The behavior of this can change at any time. * @deprecated The operator doesn't work properly with {@link #subscribeOn(Scheduler)} and is prone to * deadlocks. It will be removed/unavailable starting from 1.1. * @since (if this graduates from Experimental/Beta to supported, replace this parenthetical with the release number) */ @Experimental @Deprecated public final Observable<T> onBackpressureBlock(int maxQueueLength) { return lift(new OperatorOnBackpressureBlock<T>(maxQueueLength)); } /** * Instructs an Observable that is emitting items faster than its observer can consume them to block the * producer thread if the number of undelivered onNext events reaches the system-wide ring buffer size. * <p> * <img width="640" height="245" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/bp.obp.block.png" alt=""> * <p> * The producer side can emit up to the system-wide ring buffer size onNext elements without blocking, but * the consumer side considers the amount its downstream requested through {@code Producer.request(n)} * and doesn't emit more than requested even if available. * <p> * Note that if the upstream Observable does support backpressure, this operator ignores that capability * and doesn't propagate any backpressure requests from downstream. * <p> * Warning! Using a chain like {@code source.onBackpressureBlock().subscribeOn(scheduler)} is prone to * deadlocks because the consumption of the internal queue is scheduled behind a blocked emission by * the subscribeOn. In order to avoid this, the operators have to be swapped in the chain: * {@code source.subscribeOn(scheduler).onBackpressureBlock()} and in general, no subscribeOn operator should follow * this operator. * * @return the source Observable modified to block {@code onNext} notifications on overflow * @see <a href="http://reactivex.io/documentation/operators/backpressure.html">ReactiveX operators documentation: backpressure operators</a> * @Experimental The behavior of this can change at any time. * @deprecated The operator doesn't work properly with {@link #subscribeOn(Scheduler)} and is prone to * deadlocks. It will be removed/unavailable starting from 1.1. * @since (if this graduates from Experimental/Beta to supported, replace this parenthetical with the release number) */ @Experimental @Deprecated public final Observable<T> onBackpressureBlock() { return onBackpressureBlock(rx.internal.util.RxRingBuffer.SIZE); } /** * Instructs an Observable that is emitting items faster than its observer can consume them to * hold onto the latest value and emit that on request. * <p> * <img width="640" height="245" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/bp.obp.latest.png" alt=""> * <p> * Its behavior is logically equivalent to {@code toBlocking().latest()} with the exception that * the downstream is not blocking while requesting more values. * <p> * Note that if the upstream Observable does support backpressure, this operator ignores that capability * and doesn't propagate any backpressure requests from downstream. * <p> * Note that due to the nature of how backpressure requests are propagated through subscribeOn/observeOn, * requesting more than 1 from downstream doesn't guarantee a continuous delivery of onNext events. * * @return the source Observable modified so that it emits the most recently-received item upon request * @Experimental The behavior of this can change at any time. * @since (if this graduates from Experimental/Beta to supported, replace this parenthetical with the release number) */ @Experimental public final Observable<T> onBackpressureLatest() { return lift(OperatorOnBackpressureLatest.<T>instance()); } /** * Instructs an Observable to pass control to another Observable rather than invoking * {@link Observer#onError onError} if it encounters an error. * <p> * <img width="640" height="310" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/onErrorResumeNext.png" alt=""> * <p> * By default, when an Observable encounters an error that prevents it from emitting the expected item to * its {@link Observer}, the Observable invokes its Observer's {@code onError} method, and then quits * without invoking any more of its Observer's methods. The {@code onErrorResumeNext} method changes this * behavior. If you pass a function that returns an Observable ({@code resumeFunction}) to * {@code onErrorResumeNext}, if the original Observable encounters an error, instead of invoking its * Observer's {@code onError} method, it will instead relinquish control to the Observable returned from * {@code resumeFunction}, which will invoke the Observer's {@link Observer#onNext onNext} method if it is * able to do so. In such a case, because no Observable necessarily invokes {@code onError}, the Observer * may never know that an error happened. * <p> * You can use this to prevent errors from propagating or to supply fallback data should errors be * encountered. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code onErrorResumeNext} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param resumeFunction * a function that returns an Observable that will take over if the source Observable encounters * an error * @return the original Observable, with appropriately modified behavior * @see <a href="http://reactivex.io/documentation/operators/catch.html">ReactiveX operators documentation: Catch</a> */ public final Observable<T> onErrorResumeNext(final Func1<Throwable, ? extends Observable<? extends T>> resumeFunction) { return lift(new OperatorOnErrorResumeNextViaFunction<T>(resumeFunction)); } /** * Instructs an Observable to pass control to another Observable rather than invoking * {@link Observer#onError onError} if it encounters an error. * <p> * <img width="640" height="310" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/onErrorResumeNext.png" alt=""> * <p> * By default, when an Observable encounters an error that prevents it from emitting the expected item to * its {@link Observer}, the Observable invokes its Observer's {@code onError} method, and then quits * without invoking any more of its Observer's methods. The {@code onErrorResumeNext} method changes this * behavior. If you pass another Observable ({@code resumeSequence}) to an Observable's * {@code onErrorResumeNext} method, if the original Observable encounters an error, instead of invoking its * Observer's {@code onError} method, it will instead relinquish control to {@code resumeSequence} which * will invoke the Observer's {@link Observer#onNext onNext} method if it is able to do so. In such a case, * because no Observable necessarily invokes {@code onError}, the Observer may never know that an error * happened. * <p> * You can use this to prevent errors from propagating or to supply fallback data should errors be * encountered. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code onErrorResumeNext} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param resumeSequence * a function that returns an Observable that will take over if the source Observable encounters * an error * @return the original Observable, with appropriately modified behavior * @see <a href="http://reactivex.io/documentation/operators/catch.html">ReactiveX operators documentation: Catch</a> */ public final Observable<T> onErrorResumeNext(final Observable<? extends T> resumeSequence) { return lift(new OperatorOnErrorResumeNextViaObservable<T>(resumeSequence)); } /** * Instructs an Observable to emit an item (returned by a specified function) rather than invoking * {@link Observer#onError onError} if it encounters an error. * <p> * <img width="640" height="310" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/onErrorReturn.png" alt=""> * <p> * By default, when an Observable encounters an error that prevents it from emitting the expected item to * its {@link Observer}, the Observable invokes its Observer's {@code onError} method, and then quits * without invoking any more of its Observer's methods. The {@code onErrorReturn} method changes this * behavior. If you pass a function ({@code resumeFunction}) to an Observable's {@code onErrorReturn} * method, if the original Observable encounters an error, instead of invoking its Observer's * {@code onError} method, it will instead emit the return value of {@code resumeFunction}. * <p> * You can use this to prevent errors from propagating or to supply fallback data should errors be * encountered. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code onErrorReturn} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param resumeFunction * a function that returns an item that the new Observable will emit if the source Observable * encounters an error * @return the original Observable with appropriately modified behavior * @see <a href="http://reactivex.io/documentation/operators/catch.html">ReactiveX operators documentation: Catch</a> */ public final Observable<T> onErrorReturn(Func1<Throwable, ? extends T> resumeFunction) { return lift(new OperatorOnErrorReturn<T>(resumeFunction)); } /** * Instructs an Observable to pass control to another Observable rather than invoking * {@link Observer#onError onError} if it encounters an {@link java.lang.Exception}. * <p> * This differs from {@link #onErrorResumeNext} in that this one does not handle {@link java.lang.Throwable} * or {@link java.lang.Error} but lets those continue through. * <p> * <img width="640" height="310" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/onExceptionResumeNextViaObservable.png" alt=""> * <p> * By default, when an Observable encounters an exception that prevents it from emitting the expected item * to its {@link Observer}, the Observable invokes its Observer's {@code onError} method, and then quits * without invoking any more of its Observer's methods. The {@code onExceptionResumeNext} method changes * this behavior. If you pass another Observable ({@code resumeSequence}) to an Observable's * {@code onExceptionResumeNext} method, if the original Observable encounters an exception, instead of * invoking its Observer's {@code onError} method, it will instead relinquish control to * {@code resumeSequence} which will invoke the Observer's {@link Observer#onNext onNext} method if it is * able to do so. In such a case, because no Observable necessarily invokes {@code onError}, the Observer * may never know that an exception happened. * <p> * You can use this to prevent exceptions from propagating or to supply fallback data should exceptions be * encountered. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code onErrorResumeNext} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param resumeSequence * a function that returns an Observable that will take over if the source Observable encounters * an exception * @return the original Observable, with appropriately modified behavior * @see <a href="http://reactivex.io/documentation/operators/catch.html">ReactiveX operators documentation: Catch</a> */ public final Observable<T> onExceptionResumeNext(final Observable<? extends T> resumeSequence) { return lift(new OperatorOnExceptionResumeNextViaObservable<T>(resumeSequence)); } /** * Returns a {@link ConnectableObservable}, which is a variety of Observable that waits until its * {@link ConnectableObservable#connect connect} method is called before it begins emitting items to those * {@link Observer}s that have subscribed to it. * <p> * <img width="640" height="510" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/publishConnect.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code publish} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @return a {@link ConnectableObservable} that upon connection causes the source Observable to emit items * to its {@link Observer}s * @see <a href="http://reactivex.io/documentation/operators/publish.html">ReactiveX operators documentation: Publish</a> */ public final ConnectableObservable<T> publish() { return OperatorPublish.create(this); } /** * Returns an Observable that emits the results of invoking a specified selector on items emitted by a * {@link ConnectableObservable} that shares a single subscription to the underlying sequence. * <p> * <img width="640" height="510" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/publishConnect.f.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code publish} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param <R> * the type of items emitted by the resulting Observable * @param selector * a function that can use the multicasted source sequence as many times as needed, without * causing multiple subscriptions to the source sequence. Subscribers to the given source will * receive all notifications of the source from the time of the subscription forward. * @return an Observable that emits the results of invoking the selector on the items emitted by a {@link ConnectableObservable} that shares a single subscription to the underlying sequence * @see <a href="http://reactivex.io/documentation/operators/publish.html">ReactiveX operators documentation: Publish</a> */ public final <R> Observable<R> publish(Func1<? super Observable<T>, ? extends Observable<R>> selector) { return OperatorPublish.create(this, selector); } /** * Returns an Observable that applies a specified accumulator function to the first item emitted by a source * Observable, then feeds the result of that function along with the second item emitted by the source * Observable into the same function, and so on until all items have been emitted by the source Observable, * and emits the final result from the final call to your function as its sole item. * <p> * <img width="640" height="320" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/reduce.png" alt=""> * <p> * This technique, which is called "reduce" here, is sometimes called "aggregate," "fold," "accumulate," * "compress," or "inject" in other programming contexts. Groovy, for instance, has an {@code inject} method * that does a similar operation on lists. * <dl> * <dt><b>Backpressure Support:</b></dt> * <dd>This operator does not support backpressure because by intent it will receive all values and reduce * them to a single {@code onNext}.</dd> * <dt><b>Scheduler:</b></dt> * <dd>{@code reduce} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param accumulator * an accumulator function to be invoked on each item emitted by the source Observable, whose * result will be used in the next accumulator call * @return an Observable that emits a single item that is the result of accumulating the items emitted by * the source Observable * @throws IllegalArgumentException * if the source Observable emits no items * @see <a href="http://reactivex.io/documentation/operators/reduce.html">ReactiveX operators documentation: Reduce</a> * @see <a href="http://en.wikipedia.org/wiki/Fold_(higher-order_function)">Wikipedia: Fold (higher-order function)</a> */ public final Observable<T> reduce(Func2<T, T, T> accumulator) { /* * Discussion and confirmation of implementation at * https://github.com/ReactiveX/RxJava/issues/423#issuecomment-27642532 * * It should use last() not takeLast(1) since it needs to emit an error if the sequence is empty. */ return scan(accumulator).last(); } /** * Returns an Observable that applies a specified accumulator function to the first item emitted by a source * Observable and a specified seed value, then feeds the result of that function along with the second item * emitted by an Observable into the same function, and so on until all items have been emitted by the * source Observable, emitting the final result from the final call to your function as its sole item. * <p> * <img width="640" height="325" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/reduceSeed.png" alt=""> * <p> * This technique, which is called "reduce" here, is sometimec called "aggregate," "fold," "accumulate," * "compress," or "inject" in other programming contexts. Groovy, for instance, has an {@code inject} method * that does a similar operation on lists. * <dl> * <dt><b>Backpressure Support:</b></dt> * <dd>This operator does not support backpressure because by intent it will receive all values and reduce * them to a single {@code onNext}.</dd> * <dt><b>Scheduler:</b></dt> * <dd>{@code reduce} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param initialValue * the initial (seed) accumulator value * @param accumulator * an accumulator function to be invoked on each item emitted by the source Observable, the * result of which will be used in the next accumulator call * @return an Observable that emits a single item that is the result of accumulating the output from the * items emitted by the source Observable * @see <a href="http://reactivex.io/documentation/operators/reduce.html">ReactiveX operators documentation: Reduce</a> * @see <a href="http://en.wikipedia.org/wiki/Fold_(higher-order_function)">Wikipedia: Fold (higher-order function)</a> */ public final <R> Observable<R> reduce(R initialValue, Func2<R, ? super T, R> accumulator) { return scan(initialValue, accumulator).takeLast(1); } /** * Returns an Observable that repeats the sequence of items emitted by the source Observable indefinitely. * <p> * <img width="640" height="309" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/repeat.o.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code repeat} operates by default on the {@code trampoline} {@link Scheduler}.</dd> * </dl> * * @return an Observable that emits the items emitted by the source Observable repeatedly and in sequence * @see <a href="http://reactivex.io/documentation/operators/repeat.html">ReactiveX operators documentation: Repeat</a> */ public final Observable<T> repeat() { return OnSubscribeRedo.<T>repeat(this); } /** * Returns an Observable that repeats the sequence of items emitted by the source Observable indefinitely, * on a particular Scheduler. * <p> * <img width="640" height="310" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/repeat.os.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>you specify which {@link Scheduler} this operator will use</dd> * </dl> * * @param scheduler * the Scheduler to emit the items on * @return an Observable that emits the items emitted by the source Observable repeatedly and in sequence * @see <a href="http://reactivex.io/documentation/operators/repeat.html">ReactiveX operators documentation: Repeat</a> */ public final Observable<T> repeat(Scheduler scheduler) { return OnSubscribeRedo.<T>repeat(this, scheduler); } /** * Returns an Observable that repeats the sequence of items emitted by the source Observable at most * {@code count} times. * <p> * <img width="640" height="310" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/repeat.on.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code repeat} operates by default on the {@code trampoline} {@link Scheduler}.</dd> * </dl> * * @param count * the number of times the source Observable items are repeated, a count of 0 will yield an empty * sequence * @return an Observable that repeats the sequence of items emitted by the source Observable at most * {@code count} times * @throws IllegalArgumentException * if {@code count} is less than zero * @see <a href="http://reactivex.io/documentation/operators/repeat.html">ReactiveX operators documentation: Repeat</a> */ public final Observable<T> repeat(final long count) { return OnSubscribeRedo.<T>repeat(this, count); } /** * Returns an Observable that repeats the sequence of items emitted by the source Observable at most * {@code count} times, on a particular Scheduler. * <p> * <img width="640" height="310" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/repeat.ons.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>you specify which {@link Scheduler} this operator will use</dd> * </dl> * * @param count * the number of times the source Observable items are repeated, a count of 0 will yield an empty * sequence * @param scheduler * the {@link Scheduler} to emit the items on * @return an Observable that repeats the sequence of items emitted by the source Observable at most * {@code count} times on a particular Scheduler * @see <a href="http://reactivex.io/documentation/operators/repeat.html">ReactiveX operators documentation: Repeat</a> */ public final Observable<T> repeat(final long count, Scheduler scheduler) { return OnSubscribeRedo.<T>repeat(this, count, scheduler); } /** * Returns an Observable that emits the same values as the source Observable with the exception of an * {@code onCompleted}. An {@code onCompleted} notification from the source will result in the emission of * a {@code void} item to the Observable provided as an argument to the {@code notificationHandler} * function. If that Observable calls {@code onComplete} or {@code onError} then {@code repeatWhen} will * call {@code onCompleted} or {@code onError} on the child subscription. Otherwise, this Observable will * resubscribe to the source Observable, on a particular Scheduler. * <p> * <img width="640" height="430" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/repeatWhen.f.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>you specify which {@link Scheduler} this operator will use</dd> * </dl> * * @param notificationHandler * receives an Observable of notifications with which a user can complete or error, aborting the repeat. * @param scheduler * the {@link Scheduler} to emit the items on * @return the source Observable modified with repeat logic * @see <a href="http://reactivex.io/documentation/operators/repeat.html">ReactiveX operators documentation: Repeat</a> */ public final Observable<T> repeatWhen(final Func1<? super Observable<? extends Void>, ? extends Observable<?>> notificationHandler, Scheduler scheduler) { Func1<? super Observable<? extends Notification<?>>, ? extends Observable<?>> dematerializedNotificationHandler = new Func1<Observable<? extends Notification<?>>, Observable<?>>() { @Override public Observable<?> call(Observable<? extends Notification<?>> notifications) { return notificationHandler.call(notifications.map(new Func1<Notification<?>, Void>() { @Override public Void call(Notification<?> notification) { return null; } })); } }; return OnSubscribeRedo.repeat(this, dematerializedNotificationHandler, scheduler); } /** * Returns an Observable that emits the same values as the source Observable with the exception of an * {@code onCompleted}. An {@code onCompleted} notification from the source will result in the emission of * a {@code void} item to the Observable provided as an argument to the {@code notificationHandler} * function. If that Observable calls {@code onComplete} or {@code onError} then {@code repeatWhen} will * call {@code onCompleted} or {@code onError} on the child subscription. Otherwise, this Observable will * resubscribe to the source observable. * <p> * <img width="640" height="430" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/repeatWhen.f.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code repeatWhen} operates by default on the {@code trampoline} {@link Scheduler}.</dd> * </dl> * * @param notificationHandler * receives an Observable of notifications with which a user can complete or error, aborting the repeat. * @return the source Observable modified with repeat logic * @see <a href="http://reactivex.io/documentation/operators/repeat.html">ReactiveX operators documentation: Repeat</a> */ public final Observable<T> repeatWhen(final Func1<? super Observable<? extends Void>, ? extends Observable<?>> notificationHandler) { Func1<? super Observable<? extends Notification<?>>, ? extends Observable<?>> dematerializedNotificationHandler = new Func1<Observable<? extends Notification<?>>, Observable<?>>() { @Override public Observable<?> call(Observable<? extends Notification<?>> notifications) { return notificationHandler.call(notifications.map(new Func1<Notification<?>, Void>() { @Override public Void call(Notification<?> notification) { return null; } })); } }; return OnSubscribeRedo.repeat(this, dematerializedNotificationHandler); } /** * Returns a {@link ConnectableObservable} that shares a single subscription to the underlying Observable * that will replay all of its items and notifications to any future {@link Observer}. A Connectable * Observable resembles an ordinary Observable, except that it does not begin emitting items when it is * subscribed to, but only when its {@code connect} method is called. * <p> * <img width="640" height="515" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/replay.png" alt=""> * <dl> * <dt><b>Backpressure Support:</b></dt> * <dd>This operator supports backpressure. Note that the upstream requests are determined by the child * Subscriber which requests the largest amount: i.e., two child Subscribers with requests of 10 and 100 will * request 100 elements from the underlying Observable sequence.</dd> * <dt><b>Scheduler:</b></dt> * <dd>This version of {@code replay} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @return a {@link ConnectableObservable} that upon connection causes the source Observable to emit its * items to its {@link Observer}s * @see <a href="http://reactivex.io/documentation/operators/replay.html">ReactiveX operators documentation: Replay</a> */ public final ConnectableObservable<T> replay() { return OperatorReplay.create(this); } /** * Returns an Observable that emits items that are the results of invoking a specified selector on the items * emitted by a {@link ConnectableObservable} that shares a single subscription to the source Observable. * <p> * <img width="640" height="450" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/replay.f.png" alt=""> * <dl> * <dt><b>Backpressure Support:</b></dt> * <dd>This operator supports backpressure. Note that the upstream requests are determined by the child * Subscriber which requests the largest amount: i.e., two child Subscribers with requests of 10 and 100 will * request 100 elements from the underlying Observable sequence.</dd> * <dt><b>Scheduler:</b></dt> * <dd>This version of {@code replay} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param <R> * the type of items emitted by the resulting Observable * @param selector * the selector function, which can use the multicasted sequence as many times as needed, without * causing multiple subscriptions to the Observable * @return an Observable that emits items that are the results of invoking the selector on a * {@link ConnectableObservable} that shares a single subscription to the source Observable * @see <a href="http://reactivex.io/documentation/operators/replay.html">ReactiveX operators documentation: Replay</a> */ public final <R> Observable<R> replay(Func1<? super Observable<T>, ? extends Observable<R>> selector) { return OperatorReplay.multicastSelector(new Func0<ConnectableObservable<T>>() { @Override public ConnectableObservable<T> call() { return Observable.this.replay(); } }, selector); } /** * Returns an Observable that emits items that are the results of invoking a specified selector on items * emitted by a {@link ConnectableObservable} that shares a single subscription to the source Observable, * replaying {@code bufferSize} notifications. * <p> * <img width="640" height="440" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/replay.fn.png" alt=""> * <dl> * <dt><b>Backpressure Support:</b></dt> * <dd>This operator supports backpressure. Note that the upstream requests are determined by the child * Subscriber which requests the largest amount: i.e., two child Subscribers with requests of 10 and 100 will * request 100 elements from the underlying Observable sequence.</dd> * <dt><b>Scheduler:</b></dt> * <dd>This version of {@code replay} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param <R> * the type of items emitted by the resulting Observable * @param selector * the selector function, which can use the multicasted sequence as many times as needed, without * causing multiple subscriptions to the Observable * @param bufferSize * the buffer size that limits the number of items the connectable observable can replay * @return an Observable that emits items that are the results of invoking the selector on items emitted by * a {@link ConnectableObservable} that shares a single subscription to the source Observable * replaying no more than {@code bufferSize} items * @see <a href="http://reactivex.io/documentation/operators/replay.html">ReactiveX operators documentation: Replay</a> */ public final <R> Observable<R> replay(Func1<? super Observable<T>, ? extends Observable<R>> selector, final int bufferSize) { return OperatorReplay.multicastSelector(new Func0<ConnectableObservable<T>>() { @Override public ConnectableObservable<T> call() { return Observable.this.replay(bufferSize); } }, selector); } /** * Returns an Observable that emits items that are the results of invoking a specified selector on items * emitted by a {@link ConnectableObservable} that shares a single subscription to the source Observable, * replaying no more than {@code bufferSize} items that were emitted within a specified time window. * <p> * <img width="640" height="445" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/replay.fnt.png" alt=""> * <dl> * <dt><b>Backpressure Support:</b></dt> * <dd>This operator supports backpressure. Note that the upstream requests are determined by the child * Subscriber which requests the largest amount: i.e., two child Subscribers with requests of 10 and 100 will * request 100 elements from the underlying Observable sequence.</dd> * <dt><b>Scheduler:</b></dt> * <dd>This version of {@code replay} operates by default on the {@code computation} {@link Scheduler}.</dd> * </dl> * * @param <R> * the type of items emitted by the resulting Observable * @param selector * a selector function, which can use the multicasted sequence as many times as needed, without * causing multiple subscriptions to the Observable * @param bufferSize * the buffer size that limits the number of items the connectable observable can replay * @param time * the duration of the window in which the replayed items must have been emitted * @param unit * the time unit of {@code time} * @return an Observable that emits items that are the results of invoking the selector on items emitted by * a {@link ConnectableObservable} that shares a single subscription to the source Observable, and * replays no more than {@code bufferSize} items that were emitted within the window defined by * {@code time} * @see <a href="http://reactivex.io/documentation/operators/replay.html">ReactiveX operators documentation: Replay</a> */ public final <R> Observable<R> replay(Func1<? super Observable<T>, ? extends Observable<R>> selector, int bufferSize, long time, TimeUnit unit) { return replay(selector, bufferSize, time, unit, Schedulers.computation()); } /** * Returns an Observable that emits items that are the results of invoking a specified selector on items * emitted by a {@link ConnectableObservable} that shares a single subscription to the source Observable, * replaying no more than {@code bufferSize} items that were emitted within a specified time window. * <p> * <img width="640" height="445" height="440" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/replay.fnts.png" alt=""> * <dl> * <dt><b>Backpressure Support:</b></dt> * <dd>This operator supports backpressure. Note that the upstream requests are determined by the child * Subscriber which requests the largest amount: i.e., two child Subscribers with requests of 10 and 100 will * request 100 elements from the underlying Observable sequence.</dd> * <dt><b>Scheduler:</b></dt> * <dd>you specify which {@link Scheduler} this operator will use</dd> * </dl> * * @param <R> * the type of items emitted by the resulting Observable * @param selector * a selector function, which can use the multicasted sequence as many times as needed, without * causing multiple subscriptions to the Observable * @param bufferSize * the buffer size that limits the number of items the connectable observable can replay * @param time * the duration of the window in which the replayed items must have been emitted * @param unit * the time unit of {@code time} * @param scheduler * the Scheduler that is the time source for the window * @return an Observable that emits items that are the results of invoking the selector on items emitted by * a {@link ConnectableObservable} that shares a single subscription to the source Observable, and * replays no more than {@code bufferSize} items that were emitted within the window defined by * {@code time} * @throws IllegalArgumentException * if {@code bufferSize} is less than zero * @see <a href="http://reactivex.io/documentation/operators/replay.html">ReactiveX operators documentation: Replay</a> */ public final <R> Observable<R> replay(Func1<? super Observable<T>, ? extends Observable<R>> selector, final int bufferSize, final long time, final TimeUnit unit, final Scheduler scheduler) { if (bufferSize < 0) { throw new IllegalArgumentException("bufferSize < 0"); } return OperatorReplay.multicastSelector(new Func0<ConnectableObservable<T>>() { @Override public ConnectableObservable<T> call() { return Observable.this.replay(bufferSize, time, unit, scheduler); } }, selector); } /** * Returns an Observable that emits items that are the results of invoking a specified selector on items * emitted by a {@link ConnectableObservable} that shares a single subscription to the source Observable, * replaying a maximum of {@code bufferSize} items. * <p> * <img width="640" height="440" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/replay.fns.png" alt=""> * <dl> * <dt><b>Backpressure Support:</b></dt> * <dd>This operator supports backpressure. Note that the upstream requests are determined by the child * Subscriber which requests the largest amount: i.e., two child Subscribers with requests of 10 and 100 will * request 100 elements from the underlying Observable sequence.</dd> * <dt><b>Scheduler:</b></dt> * <dd>you specify which {@link Scheduler} this operator will use</dd> * </dl> * * @param <R> * the type of items emitted by the resulting Observable * @param selector * a selector function, which can use the multicasted sequence as many times as needed, without * causing multiple subscriptions to the Observable * @param bufferSize * the buffer size that limits the number of items the connectable observable can replay * @param scheduler * the Scheduler on which the replay is observed * @return an Observable that emits items that are the results of invoking the selector on items emitted by * a {@link ConnectableObservable} that shares a single subscription to the source Observable, * replaying no more than {@code bufferSize} notifications * @see <a href="http://reactivex.io/documentation/operators/replay.html">ReactiveX operators documentation: Replay</a> */ public final <R> Observable<R> replay(final Func1<? super Observable<T>, ? extends Observable<R>> selector, final int bufferSize, final Scheduler scheduler) { return OperatorReplay.multicastSelector(new Func0<ConnectableObservable<T>>() { @Override public ConnectableObservable<T> call() { return Observable.this.replay(bufferSize); } }, new Func1<Observable<T>, Observable<R>>() { @Override public Observable<R> call(Observable<T> t) { return selector.call(t).observeOn(scheduler); } }); } /** * Returns an Observable that emits items that are the results of invoking a specified selector on items * emitted by a {@link ConnectableObservable} that shares a single subscription to the source Observable, * replaying all items that were emitted within a specified time window. * <p> * <img width="640" height="435" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/replay.ft.png" alt=""> * <dl> * <dt><b>Backpressure Support:</b></dt> * <dd>This operator supports backpressure. Note that the upstream requests are determined by the child * Subscriber which requests the largest amount: i.e., two child Subscribers with requests of 10 and 100 will * request 100 elements from the underlying Observable sequence.</dd> * <dt><b>Scheduler:</b></dt> * <dd>This version of {@code replay} operates by default on the {@code computation} {@link Scheduler}.</dd> * </dl> * * @param <R> * the type of items emitted by the resulting Observable * @param selector * a selector function, which can use the multicasted sequence as many times as needed, without * causing multiple subscriptions to the Observable * @param time * the duration of the window in which the replayed items must have been emitted * @param unit * the time unit of {@code time} * @return an Observable that emits items that are the results of invoking the selector on items emitted by * a {@link ConnectableObservable} that shares a single subscription to the source Observable, * replaying all items that were emitted within the window defined by {@code time} * @see <a href="http://reactivex.io/documentation/operators/replay.html">ReactiveX operators documentation: Replay</a> */ public final <R> Observable<R> replay(Func1<? super Observable<T>, ? extends Observable<R>> selector, long time, TimeUnit unit) { return replay(selector, time, unit, Schedulers.computation()); } /** * Returns an Observable that emits items that are the results of invoking a specified selector on items * emitted by a {@link ConnectableObservable} that shares a single subscription to the source Observable, * replaying all items that were emitted within a specified time window. * <p> * <img width="640" height="440" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/replay.fts.png" alt=""> * <dl> * <dt><b>Backpressure Support:</b></dt> * <dd>This operator supports backpressure. Note that the upstream requests are determined by the child * Subscriber which requests the largest amount: i.e., two child Subscribers with requests of 10 and 100 will * request 100 elements from the underlying Observable sequence.</dd> * <dt><b>Scheduler:</b></dt> * <dd>you specify which {@link Scheduler} this operator will use</dd> * </dl> * * @param <R> * the type of items emitted by the resulting Observable * @param selector * a selector function, which can use the multicasted sequence as many times as needed, without * causing multiple subscriptions to the Observable * @param time * the duration of the window in which the replayed items must have been emitted * @param unit * the time unit of {@code time} * @param scheduler * the scheduler that is the time source for the window * @return an Observable that emits items that are the results of invoking the selector on items emitted by * a {@link ConnectableObservable} that shares a single subscription to the source Observable, * replaying all items that were emitted within the window defined by {@code time} * @see <a href="http://reactivex.io/documentation/operators/replay.html">ReactiveX operators documentation: Replay</a> */ public final <R> Observable<R> replay(Func1<? super Observable<T>, ? extends Observable<R>> selector, final long time, final TimeUnit unit, final Scheduler scheduler) { return OperatorReplay.multicastSelector(new Func0<ConnectableObservable<T>>() { @Override public ConnectableObservable<T> call() { return Observable.this.replay(time, unit, scheduler); } }, selector); } /** * Returns an Observable that emits items that are the results of invoking a specified selector on items * emitted by a {@link ConnectableObservable} that shares a single subscription to the source Observable. * <p> * <img width="640" height="445" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/replay.fs.png" alt=""> * <dl> * <dt><b>Backpressure Support:</b></dt> * <dd>This operator supports backpressure. Note that the upstream requests are determined by the child * Subscriber which requests the largest amount: i.e., two child Subscribers with requests of 10 and 100 will * request 100 elements from the underlying Observable sequence.</dd> * <dt><b>Scheduler:</b></dt> * <dd>you specify which {@link Scheduler} this operator will use</dd> * </dl> * * @param <R> * the type of items emitted by the resulting Observable * @param selector * a selector function, which can use the multicasted sequence as many times as needed, without * causing multiple subscriptions to the Observable * @param scheduler * the Scheduler where the replay is observed * @return an Observable that emits items that are the results of invoking the selector on items emitted by * a {@link ConnectableObservable} that shares a single subscription to the source Observable, * replaying all items * @see <a href="http://reactivex.io/documentation/operators/replay.html">ReactiveX operators documentation: Replay</a> */ public final <R> Observable<R> replay(final Func1<? super Observable<T>, ? extends Observable<R>> selector, final Scheduler scheduler) { return OperatorReplay.multicastSelector(new Func0<ConnectableObservable<T>>() { @Override public ConnectableObservable<T> call() { return Observable.this.replay(); } }, new Func1<Observable<T>, Observable<R>>() { @Override public Observable<R> call(Observable<T> t) { return selector.call(t).observeOn(scheduler); } }); } /** * Returns a {@link ConnectableObservable} that shares a single subscription to the source Observable that * replays at most {@code bufferSize} items emitted by that Observable. A Connectable Observable resembles * an ordinary Observable, except that it does not begin emitting items when it is subscribed to, but only * when its {@code connect} method is called. * <p> * <img width="640" height="515" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/replay.n.png" alt=""> * <dl> * <dt><b>Backpressure Support:</b></dt> * <dd>This operator supports backpressure. Note that the upstream requests are determined by the child * Subscriber which requests the largest amount: i.e., two child Subscribers with requests of 10 and 100 will * request 100 elements from the underlying Observable sequence.</dd> * <dt><b>Scheduler:</b></dt> * <dd>This version of {@code replay} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param bufferSize * the buffer size that limits the number of items that can be replayed * @return a {@link ConnectableObservable} that shares a single subscription to the source Observable and * replays at most {@code bufferSize} items emitted by that Observable * @see <a href="http://reactivex.io/documentation/operators/replay.html">ReactiveX operators documentation: Replay</a> */ public final ConnectableObservable<T> replay(final int bufferSize) { return OperatorReplay.create(this, bufferSize); } /** * Returns a {@link ConnectableObservable} that shares a single subscription to the source Observable and * replays at most {@code bufferSize} items that were emitted during a specified time window. A Connectable * Observable resembles an ordinary Observable, except that it does not begin emitting items when it is * subscribed to, but only when its {@code connect} method is called. * <p> * <img width="640" height="515" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/replay.nt.png" alt=""> * <dl> * <dt><b>Backpressure Support:</b></dt> * <dd>This operator supports backpressure. Note that the upstream requests are determined by the child * Subscriber which requests the largest amount: i.e., two child Subscribers with requests of 10 and 100 will * request 100 elements from the underlying Observable sequence.</dd> * <dt><b>Scheduler:</b></dt> * <dd>This version of {@code replay} operates by default on the {@code computation} {@link Scheduler}.</dd> * </dl> * * @param bufferSize * the buffer size that limits the number of items that can be replayed * @param time * the duration of the window in which the replayed items must have been emitted * @param unit * the time unit of {@code time} * @return a {@link ConnectableObservable} that shares a single subscription to the source Observable and * replays at most {@code bufferSize} items that were emitted during the window defined by * {@code time} * @see <a href="http://reactivex.io/documentation/operators/replay.html">ReactiveX operators documentation: Replay</a> */ public final ConnectableObservable<T> replay(int bufferSize, long time, TimeUnit unit) { return replay(bufferSize, time, unit, Schedulers.computation()); } /** * Returns a {@link ConnectableObservable} that shares a single subscription to the source Observable and * that replays a maximum of {@code bufferSize} items that are emitted within a specified time window. A * Connectable Observable resembles an ordinary Observable, except that it does not begin emitting items * when it is subscribed to, but only when its {@code connect} method is called. * <p> * <img width="640" height="515" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/replay.nts.png" alt=""> * <dl> * <dt><b>Backpressure Support:</b></dt> * <dd>This operator supports backpressure. Note that the upstream requests are determined by the child * Subscriber which requests the largest amount: i.e., two child Subscribers with requests of 10 and 100 will * request 100 elements from the underlying Observable sequence.</dd> * <dt><b>Scheduler:</b></dt> * <dd>you specify which {@link Scheduler} this operator will use</dd> * </dl> * * @param bufferSize * the buffer size that limits the number of items that can be replayed * @param time * the duration of the window in which the replayed items must have been emitted * @param unit * the time unit of {@code time} * @param scheduler * the scheduler that is used as a time source for the window * @return a {@link ConnectableObservable} that shares a single subscription to the source Observable and * replays at most {@code bufferSize} items that were emitted during the window defined by * {@code time} * @throws IllegalArgumentException * if {@code bufferSize} is less than zero * @see <a href="http://reactivex.io/documentation/operators/replay.html">ReactiveX operators documentation: Replay</a> */ public final ConnectableObservable<T> replay(final int bufferSize, final long time, final TimeUnit unit, final Scheduler scheduler) { if (bufferSize < 0) { throw new IllegalArgumentException("bufferSize < 0"); } return OperatorReplay.create(this, time, unit, scheduler, bufferSize); } /** * Returns a {@link ConnectableObservable} that shares a single subscription to the source Observable and * replays at most {@code bufferSize} items emitted by that Observable. A Connectable Observable resembles * an ordinary Observable, except that it does not begin emitting items when it is subscribed to, but only * when its {@code connect} method is called. * <p> * <img width="640" height="515" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/replay.ns.png" alt=""> * <dl> * <dt><b>Backpressure Support:</b></dt> * <dd>This operator supports backpressure. Note that the upstream requests are determined by the child * Subscriber which requests the largest amount: i.e., two child Subscribers with requests of 10 and 100 will * request 100 elements from the underlying Observable sequence.</dd> * <dt><b>Scheduler:</b></dt> * <dd>you specify which {@link Scheduler} this operator will use</dd> * </dl> * * @param bufferSize * the buffer size that limits the number of items that can be replayed * @param scheduler * the scheduler on which the Observers will observe the emitted items * @return a {@link ConnectableObservable} that shares a single subscription to the source Observable and * replays at most {@code bufferSize} items that were emitted by the Observable * @see <a href="http://reactivex.io/documentation/operators/replay.html">ReactiveX operators documentation: Replay</a> */ public final ConnectableObservable<T> replay(final int bufferSize, final Scheduler scheduler) { return OperatorReplay.observeOn(replay(bufferSize), scheduler); } /** * Returns a {@link ConnectableObservable} that shares a single subscription to the source Observable and * replays all items emitted by that Observable within a specified time window. A Connectable Observable * resembles an ordinary Observable, except that it does not begin emitting items when it is subscribed to, * but only when its {@code connect} method is called. * <p> * <img width="640" height="515" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/replay.t.png" alt=""> * <dl> * <dt><b>Backpressure Support:</b></dt> * <dd>This operator supports backpressure. Note that the upstream requests are determined by the child * Subscriber which requests the largest amount: i.e., two child Subscribers with requests of 10 and 100 will * request 100 elements from the underlying Observable sequence.</dd> * <dt><b>Scheduler:</b></dt> * <dd>This version of {@code replay} operates by default on the {@code computation} {@link Scheduler}.</dd> * </dl> * * @param time * the duration of the window in which the replayed items must have been emitted * @param unit * the time unit of {@code time} * @return a {@link ConnectableObservable} that shares a single subscription to the source Observable and * replays the items that were emitted during the window defined by {@code time} * @see <a href="http://reactivex.io/documentation/operators/replay.html">ReactiveX operators documentation: Replay</a> */ public final ConnectableObservable<T> replay(long time, TimeUnit unit) { return replay(time, unit, Schedulers.computation()); } /** * Returns a {@link ConnectableObservable} that shares a single subscription to the source Observable and * replays all items emitted by that Observable within a specified time window. A Connectable Observable * resembles an ordinary Observable, except that it does not begin emitting items when it is subscribed to, * but only when its {@code connect} method is called. * <p> * <img width="640" height="515" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/replay.ts.png" alt=""> * <dl> * <dt><b>Backpressure Support:</b></dt> * <dd>This operator supports backpressure. Note that the upstream requests are determined by the child * Subscriber which requests the largest amount: i.e., two child Subscribers with requests of 10 and 100 will * request 100 elements from the underlying Observable sequence.</dd> * <dt><b>Scheduler:</b></dt> * <dd>you specify which {@link Scheduler} this operator will use</dd> * </dl> * * @param time * the duration of the window in which the replayed items must have been emitted * @param unit * the time unit of {@code time} * @param scheduler * the Scheduler that is the time source for the window * @return a {@link ConnectableObservable} that shares a single subscription to the source Observable and * replays the items that were emitted during the window defined by {@code time} * @see <a href="http://reactivex.io/documentation/operators/replay.html">ReactiveX operators documentation: Replay</a> */ public final ConnectableObservable<T> replay(final long time, final TimeUnit unit, final Scheduler scheduler) { return OperatorReplay.create(this, time, unit, scheduler); } /** * Returns a {@link ConnectableObservable} that shares a single subscription to the source Observable that * will replay all of its items and notifications to any future {@link Observer} on the given * {@link Scheduler}. A Connectable Observable resembles an ordinary Observable, except that it does not * begin emitting items when it is subscribed to, but only when its {@code connect} method is called. * <p> * <img width="640" height="515" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/replay.s.png" alt=""> * <dl> * <dt><b>Backpressure Support:</b></dt> * <dd>This operator supports backpressure. Note that the upstream requests are determined by the child * Subscriber which requests the largest amount: i.e., two child Subscribers with requests of 10 and 100 will * request 100 elements from the underlying Observable sequence.</dd> * <dt><b>Scheduler:</b></dt> * <dd>you specify which {@link Scheduler} this operator will use</dd> * </dl> * * @param scheduler * the Scheduler on which the Observers will observe the emitted items * @return a {@link ConnectableObservable} that shares a single subscription to the source Observable that * will replay all of its items and notifications to any future {@link Observer} on the given * {@link Scheduler} * @see <a href="http://reactivex.io/documentation/operators/replay.html">ReactiveX operators documentation: Replay</a> */ public final ConnectableObservable<T> replay(final Scheduler scheduler) { return OperatorReplay.observeOn(replay(), scheduler); } /** * Returns an Observable that mirrors the source Observable, resubscribing to it if it calls {@code onError} * (infinite retry count). * <p> * <img width="640" height="315" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/retry.png" alt=""> * <p> * If the source Observable calls {@link Observer#onError}, this method will resubscribe to the source * Observable rather than propagating the {@code onError} call. * <p> * Any and all items emitted by the source Observable will be emitted by the resulting Observable, even * those emitted during failed subscriptions. For example, if an Observable fails at first but emits * {@code [1, 2]} then succeeds the second time and emits {@code [1, 2, 3, 4, 5]} then the complete sequence * of emissions and notifications would be {@code [1, 2, 1, 2, 3, 4, 5, onCompleted]}. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code retry} operates by default on the {@code trampoline} {@link Scheduler}.</dd> * </dl> * * @return the source Observable modified with retry logic * @see <a href="http://reactivex.io/documentation/operators/retry.html">ReactiveX operators documentation: Retry</a> */ public final Observable<T> retry() { return OnSubscribeRedo.<T>retry(this); } /** * Returns an Observable that mirrors the source Observable, resubscribing to it if it calls {@code onError} * up to a specified number of retries. * <p> * <img width="640" height="315" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/retry.png" alt=""> * <p> * If the source Observable calls {@link Observer#onError}, this method will resubscribe to the source * Observable for a maximum of {@code count} resubscriptions rather than propagating the * {@code onError} call. * <p> * Any and all items emitted by the source Observable will be emitted by the resulting Observable, even * those emitted during failed subscriptions. For example, if an Observable fails at first but emits * {@code [1, 2]} then succeeds the second time and emits {@code [1, 2, 3, 4, 5]} then the complete sequence * of emissions and notifications would be {@code [1, 2, 1, 2, 3, 4, 5, onCompleted]}. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code retry} operates by default on the {@code trampoline} {@link Scheduler}.</dd> * </dl> * * @param count * number of retry attempts before failing * @return the source Observable modified with retry logic * @see <a href="http://reactivex.io/documentation/operators/retry.html">ReactiveX operators documentation: Retry</a> */ public final Observable<T> retry(final long count) { return OnSubscribeRedo.<T>retry(this, count); } /** * Returns an Observable that mirrors the source Observable, resubscribing to it if it calls {@code onError} * and the predicate returns true for that specific exception and retry count. * <p> * <img width="640" height="315" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/retry.png" alt=""> * <dl> * <dt><b>Backpressure Support:</b></dt> * <dd>This operator honors backpressure.</td> * <dt><b>Scheduler:</b></dt> * <dd>{@code retry} operates by default on the {@code trampoline} {@link Scheduler}.</dd> * </dl> * * @param predicate * the predicate that determines if a resubscription may happen in case of a specific exception * and retry count * @return the source Observable modified with retry logic * @see #retry() * @see <a href="http://reactivex.io/documentation/operators/retry.html">ReactiveX operators documentation: Retry</a> */ public final Observable<T> retry(Func2<Integer, Throwable, Boolean> predicate) { return nest().lift(new OperatorRetryWithPredicate<T>(predicate)); } /** * Returns an Observable that emits the same values as the source observable with the exception of an * {@code onError}. An {@code onError} notification from the source will result in the emission of a * {@link Throwable} item to the Observable provided as an argument to the {@code notificationHandler} * function. If that Observable calls {@code onComplete} or {@code onError} then {@code retry} will call * {@code onCompleted} or {@code onError} on the child subscription. Otherwise, this Observable will * resubscribe to the source Observable. * <p> * <img width="640" height="430" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/retryWhen.f.png" alt=""> * * Example: * * This retries 3 times, each time incrementing the number of seconds it waits. * * <pre> {@code * Observable.create((Subscriber<? super String> s) -> { * System.out.println("subscribing"); * s.onError(new RuntimeException("always fails")); * }).retryWhen(attempts -> { * return attempts.zipWith(Observable.range(1, 3), (n, i) -> i).flatMap(i -> { * System.out.println("delay retry by " + i + " second(s)"); * return Observable.timer(i, TimeUnit.SECONDS); * }); * }).toBlocking().forEach(System.out::println); * } </pre> * * Output is: * * <pre> {@code * subscribing * delay retry by 1 second(s) * subscribing * delay retry by 2 second(s) * subscribing * delay retry by 3 second(s) * subscribing * } </pre> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code retryWhen} operates by default on the {@code trampoline} {@link Scheduler}.</dd> * </dl> * * @param notificationHandler * receives an Observable of notifications with which a user can complete or error, aborting the * retry * @return the source Observable modified with retry logic * @see <a href="http://reactivex.io/documentation/operators/retry.html">ReactiveX operators documentation: Retry</a> */ public final Observable<T> retryWhen(final Func1<? super Observable<? extends Throwable>, ? extends Observable<?>> notificationHandler) { Func1<? super Observable<? extends Notification<?>>, ? extends Observable<?>> dematerializedNotificationHandler = new Func1<Observable<? extends Notification<?>>, Observable<?>>() { @Override public Observable<?> call(Observable<? extends Notification<?>> notifications) { return notificationHandler.call(notifications.map(new Func1<Notification<?>, Throwable>() { @Override public Throwable call(Notification<?> notification) { return notification.getThrowable(); } })); } }; return OnSubscribeRedo.<T> retry(this, dematerializedNotificationHandler); } /** * Returns an Observable that emits the same values as the source observable with the exception of an * {@code onError}. An {@code onError} will cause the emission of the {@link Throwable} that cause the * error to the Observable returned from {@code notificationHandler}. If that Observable calls * {@code onComplete} or {@code onError} then {@code retry} will call {@code onCompleted} or {@code onError} * on the child subscription. Otherwise, this Observable will resubscribe to the source observable, on a * particular Scheduler. * <p> * <img width="640" height="430" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/retryWhen.f.png" alt=""> * <p> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>you specify which {@link Scheduler} this operator will use</dd> * </dl> * * @param notificationHandler * receives an Observable of notifications with which a user can complete or error, aborting the * retry * @param scheduler * the {@link Scheduler} on which to subscribe to the source Observable * @return the source Observable modified with retry logic * @see <a href="http://reactivex.io/documentation/operators/retry.html">ReactiveX operators documentation: Retry</a> */ public final Observable<T> retryWhen(final Func1<? super Observable<? extends Throwable>, ? extends Observable<?>> notificationHandler, Scheduler scheduler) { Func1<? super Observable<? extends Notification<?>>, ? extends Observable<?>> dematerializedNotificationHandler = new Func1<Observable<? extends Notification<?>>, Observable<?>>() { @Override public Observable<?> call(Observable<? extends Notification<?>> notifications) { return notificationHandler.call(notifications.map(new Func1<Notification<?>, Throwable>() { @Override public Throwable call(Notification<?> notification) { return notification.getThrowable(); } })); } }; return OnSubscribeRedo.<T> retry(this, dematerializedNotificationHandler, scheduler); } /** * Returns an Observable that emits the most recently emitted item (if any) emitted by the source Observable * within periodic time intervals. * <p> * <img width="640" height="305" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/sample.png" alt=""> * <dl> * <dt><b>Backpressure Support:</b></dt> * <dd>This operator does not support backpressure as it uses time to control data flow.</dd> * <dt><b>Scheduler:</b></dt> * <dd>{@code sample} operates by default on the {@code computation} {@link Scheduler}.</dd> * </dl> * * @param period * the sampling rate * @param unit * the {@link TimeUnit} in which {@code period} is defined * @return an Observable that emits the results of sampling the items emitted by the source Observable at * the specified time interval * @see <a href="http://reactivex.io/documentation/operators/sample.html">ReactiveX operators documentation: Sample</a> * @see <a href="https://github.com/ReactiveX/RxJava/wiki/Backpressure">RxJava wiki: Backpressure</a> * @see #throttleLast(long, TimeUnit) */ public final Observable<T> sample(long period, TimeUnit unit) { return sample(period, unit, Schedulers.computation()); } /** * Returns an Observable that emits the most recently emitted item (if any) emitted by the source Observable * within periodic time intervals, where the intervals are defined on a particular Scheduler. * <p> * <img width="640" height="305" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/sample.s.png" alt=""> * <dl> * <dt><b>Backpressure Support:</b></dt> * <dd>This operator does not support backpressure as it uses time to control data flow.</dd> * <dt><b>Scheduler:</b></dt> * <dd>you specify which {@link Scheduler} this operator will use</dd> * </dl> * * @param period * the sampling rate * @param unit * the {@link TimeUnit} in which {@code period} is defined * @param scheduler * the {@link Scheduler} to use when sampling * @return an Observable that emits the results of sampling the items emitted by the source Observable at * the specified time interval * @see <a href="http://reactivex.io/documentation/operators/sample.html">ReactiveX operators documentation: Sample</a> * @see <a href="https://github.com/ReactiveX/RxJava/wiki/Backpressure">RxJava wiki: Backpressure</a> * @see #throttleLast(long, TimeUnit, Scheduler) */ public final Observable<T> sample(long period, TimeUnit unit, Scheduler scheduler) { return lift(new OperatorSampleWithTime<T>(period, unit, scheduler)); } /** * Returns an Observable that, when the specified {@code sampler} Observable emits an item or completes, * emits the most recently emitted item (if any) emitted by the source Observable since the previous * emission from the {@code sampler} Observable. * <p> * <img width="640" height="305" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/sample.o.png" alt=""> * <dl> * <dt><b>Backpressure Support:</b></dt> * <dd>This operator does not support backpressure as it uses the emissions of the {@code sampler} * Observable to control data flow.</dd> * <dt><b>Scheduler:</b></dt> * <dd>This version of {@code sample} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param sampler * the Observable to use for sampling the source Observable * @return an Observable that emits the results of sampling the items emitted by this Observable whenever * the {@code sampler} Observable emits an item or completes * @see <a href="http://reactivex.io/documentation/operators/sample.html">ReactiveX operators documentation: Sample</a> * @see <a href="https://github.com/ReactiveX/RxJava/wiki/Backpressure">RxJava wiki: Backpressure</a> */ public final <U> Observable<T> sample(Observable<U> sampler) { return lift(new OperatorSampleWithObservable<T, U>(sampler)); } /** * Returns an Observable that applies a specified accumulator function to the first item emitted by a source * Observable, then feeds the result of that function along with the second item emitted by the source * Observable into the same function, and so on until all items have been emitted by the source Observable, * emitting the result of each of these iterations. * <p> * <img width="640" height="320" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/scan.png" alt=""> * <p> * This sort of function is sometimes called an accumulator. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code scan} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param accumulator * an accumulator function to be invoked on each item emitted by the source Observable, whose * result will be emitted to {@link Observer}s via {@link Observer#onNext onNext} and used in the * next accumulator call * @return an Observable that emits the results of each call to the accumulator function * @see <a href="http://reactivex.io/documentation/operators/scan.html">ReactiveX operators documentation: Scan</a> */ public final Observable<T> scan(Func2<T, T, T> accumulator) { return lift(new OperatorScan<T, T>(accumulator)); } /** * Returns an Observable that applies a specified accumulator function to the first item emitted by a source * Observable and a seed value, then feeds the result of that function along with the second item emitted by * the source Observable into the same function, and so on until all items have been emitted by the source * Observable, emitting the result of each of these iterations. * <p> * <img width="640" height="320" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/scanSeed.png" alt=""> * <p> * This sort of function is sometimes called an accumulator. * <p> * Note that the Observable that results from this method will emit {@code initialValue} as its first * emitted item. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code scan} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param initialValue * the initial (seed) accumulator item * @param accumulator * an accumulator function to be invoked on each item emitted by the source Observable, whose * result will be emitted to {@link Observer}s via {@link Observer#onNext onNext} and used in the * next accumulator call * @return an Observable that emits {@code initialValue} followed by the results of each call to the * accumulator function * @see <a href="http://reactivex.io/documentation/operators/scan.html">ReactiveX operators documentation: Scan</a> */ public final <R> Observable<R> scan(R initialValue, Func2<R, ? super T, R> accumulator) { return lift(new OperatorScan<R, T>(initialValue, accumulator)); } /** * Forces an Observable's emissions and notifications to be serialized and for it to obey * <a href="http://reactivex.io/documentation/contract.html">the Observable contract</a> in other ways. * <p> * It is possible for an Observable to invoke its Subscribers' methods asynchronously, perhaps from * different threads. This could make such an Observable poorly-behaved, in that it might try to invoke * {@code onCompleted} or {@code onError} before one of its {@code onNext} invocations, or it might call * {@code onNext} from two different threads concurrently. You can force such an Observable to be * well-behaved and sequential by applying the {@code serialize} method to it. * <p> * <img width="640" height="400" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/synchronize.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code serialize} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @return an {@link Observable} that is guaranteed to be well-behaved and to make only serialized calls to * its observers * @see <a href="http://reactivex.io/documentation/operators/serialize.html">ReactiveX operators documentation: Serialize</a> */ public final Observable<T> serialize() { return lift(OperatorSerialize.<T>instance()); } /** * Returns a new {@link Observable} that multicasts (shares) the original {@link Observable}. As long as * there is at least one {@link Subscriber} this {@link Observable} will be subscribed and emitting data. * When all subscribers have unsubscribed it will unsubscribe from the source {@link Observable}. * <p> * This is an alias for {@link #publish()}.{@link ConnectableObservable#refCount()}. * <p> * <img width="640" height="510" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/publishRefCount.png" alt=""> * <dl> * <dt><b>Backpressure Support:</b></dt> * <dd>This operator does not support backpressure because multicasting means the stream is "hot" with * multiple subscribers. Each child will need to manage backpressure independently using operators such * as {@link #onBackpressureDrop} and {@link #onBackpressureBuffer}.</dd> * <dt><b>Scheduler:</b></dt> * <dd>{@code share} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @return an {@code Observable} that upon connection causes the source {@code Observable} to emit items * to its {@link Observer}s * @see <a href="http://reactivex.io/documentation/operators/refcount.html">ReactiveX operators documentation: RefCount</a> */ public final Observable<T> share() { return publish().refCount(); } /** * Returns an Observable that emits the single item emitted by the source Observable, if that Observable * emits only a single item. If the source Observable emits more than one item or no items, notify of an * {@code IllegalArgumentException} or {@code NoSuchElementException} respectively. * <p> * <img width="640" height="315" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/single.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code single} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @return an Observable that emits the single item emitted by the source Observable * @throws IllegalArgumentException * if the source emits more than one item * @throws NoSuchElementException * if the source emits no items * @see <a href="http://reactivex.io/documentation/operators/first.html">ReactiveX operators documentation: First</a> */ public final Observable<T> single() { return lift(OperatorSingle.<T> instance()); } /** * Returns an Observable that emits the single item emitted by the source Observable that matches a * specified predicate, if that Observable emits one such item. If the source Observable emits more than one * such item or no such items, notify of an {@code IllegalArgumentException} or * {@code NoSuchElementException} respectively. * <p> * <img width="640" height="315" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/single.p.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code single} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param predicate * a predicate function to evaluate items emitted by the source Observable * @return an Observable that emits the single item emitted by the source Observable that matches the * predicate * @throws IllegalArgumentException * if the source Observable emits more than one item that matches the predicate * @throws NoSuchElementException * if the source Observable emits no item that matches the predicate * @see <a href="http://reactivex.io/documentation/operators/first.html">ReactiveX operators documentation: First</a> */ public final Observable<T> single(Func1<? super T, Boolean> predicate) { return filter(predicate).single(); } /** * Returns an Observable that emits the single item emitted by the source Observable, if that Observable * emits only a single item, or a default item if the source Observable emits no items. If the source * Observable emits more than one item, throw an {@code IllegalArgumentException}. * <p> * <img width="640" height="315" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/singleOrDefault.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code singleOrDefault} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param defaultValue * a default value to emit if the source Observable emits no item * @return an Observable that emits the single item emitted by the source Observable, or a default item if * the source Observable is empty * @throws IllegalArgumentException * if the source Observable emits more than one item * @see <a href="http://reactivex.io/documentation/operators/first.html">ReactiveX operators documentation: First</a> */ public final Observable<T> singleOrDefault(T defaultValue) { return lift(new OperatorSingle<T>(defaultValue)); } /** * Returns an Observable that emits the single item emitted by the source Observable that matches a * predicate, if that Observable emits only one such item, or a default item if the source Observable emits * no such items. If the source Observable emits more than one such item, throw an * {@code IllegalArgumentException}. * <p> * <img width="640" height="315" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/singleOrDefault.p.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code singleOrDefault} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param defaultValue * a default item to emit if the source Observable emits no matching items * @param predicate * a predicate function to evaluate items emitted by the source Observable * @return an Observable that emits the single item emitted by the source Observable that matches the * predicate, or the default item if no emitted item matches the predicate * @throws IllegalArgumentException * if the source Observable emits more than one item that matches the predicate * @see <a href="http://reactivex.io/documentation/operators/first.html">ReactiveX operators documentation: First</a> */ public final Observable<T> singleOrDefault(T defaultValue, Func1<? super T, Boolean> predicate) { return filter(predicate).singleOrDefault(defaultValue); } /** * Returns an Observable that skips the first {@code count} items emitted by the source Observable and emits * the remainder. * <p> * <img width="640" height="305" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/skip.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>This version of {@code skip} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param count * the number of items to skip * @return an Observable that is identical to the source Observable except that it does not emit the first * {@code count} items that the source Observable emits * @see <a href="http://reactivex.io/documentation/operators/skip.html">ReactiveX operators documentation: Skip</a> */ public final Observable<T> skip(int count) { return lift(new OperatorSkip<T>(count)); } /** * Returns an Observable that skips values emitted by the source Observable before a specified time window * elapses. * <p> * <img width="640" height="305" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/skip.t.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>This version of {@code skip} operates by default on the {@code computation} {@link Scheduler}.</dd> * </dl> * * @param time * the length of the time window to skip * @param unit * the time unit of {@code time} * @return an Observable that skips values emitted by the source Observable before the time window defined * by {@code time} elapses and the emits the remainder * @see <a href="http://reactivex.io/documentation/operators/skip.html">ReactiveX operators documentation: Skip</a> */ public final Observable<T> skip(long time, TimeUnit unit) { return skip(time, unit, Schedulers.computation()); } /** * Returns an Observable that skips values emitted by the source Observable before a specified time window * on a specified {@link Scheduler} elapses. * <p> * <img width="640" height="305" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/skip.ts.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>you specify which {@link Scheduler} this operator will use</dd> * </dl> * * @param time * the length of the time window to skip * @param unit * the time unit of {@code time} * @param scheduler * the {@link Scheduler} on which the timed wait happens * @return an Observable that skips values emitted by the source Observable before the time window defined * by {@code time} and {@code scheduler} elapses, and then emits the remainder * @see <a href="http://reactivex.io/documentation/operators/skip.html">ReactiveX operators documentation: Skip</a> */ public final Observable<T> skip(long time, TimeUnit unit, Scheduler scheduler) { return lift(new OperatorSkipTimed<T>(time, unit, scheduler)); } /** * Returns an Observable that drops a specified number of items from the end of the sequence emitted by the * source Observable. * <p> * <img width="640" height="305" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/skipLast.png" alt=""> * <p> * This Observer accumulates a queue long enough to store the first {@code count} items. As more items are * received, items are taken from the front of the queue and emitted by the returned Observable. This causes * such items to be delayed. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>This version of {@code skipLast} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param count * number of items to drop from the end of the source sequence * @return an Observable that emits the items emitted by the source Observable except for the dropped ones * at the end * @throws IndexOutOfBoundsException * if {@code count} is less than zero * @see <a href="http://reactivex.io/documentation/operators/skiplast.html">ReactiveX operators documentation: SkipLast</a> */ public final Observable<T> skipLast(int count) { return lift(new OperatorSkipLast<T>(count)); } /** * Returns an Observable that drops items emitted by the source Observable during a specified time window * before the source completes. * <p> * <img width="640" height="305" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/skipLast.t.png" alt=""> * <p> * Note: this action will cache the latest items arriving in the specified time window. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>This version of {@code skipLast} operates by default on the {@code computation} {@link Scheduler}.</dd> * </dl> * * @param time * the length of the time window * @param unit * the time unit of {@code time} * @return an Observable that drops those items emitted by the source Observable in a time window before the * source completes defined by {@code time} * @see <a href="http://reactivex.io/documentation/operators/skiplast.html">ReactiveX operators documentation: SkipLast</a> */ public final Observable<T> skipLast(long time, TimeUnit unit) { return skipLast(time, unit, Schedulers.computation()); } /** * Returns an Observable that drops items emitted by the source Observable during a specified time window * (defined on a specified scheduler) before the source completes. * <p> * <img width="640" height="340" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/skipLast.ts.png" alt=""> * <p> * Note: this action will cache the latest items arriving in the specified time window. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>you specify which {@link Scheduler} this operator will use</dd> * </dl> * * @param time * the length of the time window * @param unit * the time unit of {@code time} * @param scheduler * the scheduler used as the time source * @return an Observable that drops those items emitted by the source Observable in a time window before the * source completes defined by {@code time} and {@code scheduler} * @see <a href="http://reactivex.io/documentation/operators/skiplast.html">ReactiveX operators documentation: SkipLast</a> */ public final Observable<T> skipLast(long time, TimeUnit unit, Scheduler scheduler) { return lift(new OperatorSkipLastTimed<T>(time, unit, scheduler)); } /** * Returns an Observable that skips items emitted by the source Observable until a second Observable emits * an item. * <p> * <img width="640" height="375" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/skipUntil.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code skipUntil} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param other * the second Observable that has to emit an item before the source Observable's elements begin * to be mirrored by the resulting Observable * @return an Observable that skips items from the source Observable until the second Observable emits an * item, then emits the remaining items * @see <a href="http://reactivex.io/documentation/operators/skipuntil.html">ReactiveX operators documentation: SkipUntil</a> */ public final <U> Observable<T> skipUntil(Observable<U> other) { return lift(new OperatorSkipUntil<T, U>(other)); } /** * Returns an Observable that skips all items emitted by the source Observable as long as a specified * condition holds true, but emits all further source items as soon as the condition becomes false. * <p> * <img width="640" height="305" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/skipWhile.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code skipWhile} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param predicate * a function to test each item emitted from the source Observable * @return an Observable that begins emitting items emitted by the source Observable when the specified * predicate becomes false * @see <a href="http://reactivex.io/documentation/operators/skipwhile.html">ReactiveX operators documentation: SkipWhile</a> */ public final Observable<T> skipWhile(Func1<? super T, Boolean> predicate) { return lift(new OperatorSkipWhile<T>(OperatorSkipWhile.toPredicate2(predicate))); } /** * Returns an Observable that emits the items in a specified {@link Observable} before it begins to emit * items emitted by the source Observable. * <p> * <img width="640" height="315" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/startWith.o.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code startWith} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param values * an Observable that contains the items you want the modified Observable to emit first * @return an Observable that emits the items in the specified {@link Observable} and then emits the items * emitted by the source Observable * @see <a href="http://reactivex.io/documentation/operators/startwith.html">ReactiveX operators documentation: StartWith</a> */ public final Observable<T> startWith(Observable<T> values) { return concat(values, this); } /** * Returns an Observable that emits the items in a specified {@link Iterable} before it begins to emit items * emitted by the source Observable. * <p> * <img width="640" height="315" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/startWith.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code startWith} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param values * an Iterable that contains the items you want the modified Observable to emit first * @return an Observable that emits the items in the specified {@link Iterable} and then emits the items * emitted by the source Observable * @see <a href="http://reactivex.io/documentation/operators/startwith.html">ReactiveX operators documentation: StartWith</a> */ public final Observable<T> startWith(Iterable<T> values) { return concat(Observable.<T> from(values), this); } /** * Returns an Observable that emits a specified item before it begins to emit items emitted by the source * Observable. * <p> * <img width="640" height="315" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/startWith.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code startWith} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param t1 * the item to emit * @return an Observable that emits the specified item before it begins to emit items emitted by the source * Observable * @see <a href="http://reactivex.io/documentation/operators/startwith.html">ReactiveX operators documentation: StartWith</a> */ public final Observable<T> startWith(T t1) { return concat(just(t1), this); } /** * Returns an Observable that emits the specified items before it begins to emit items emitted by the source * Observable. * <p> * <img width="640" height="315" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/startWith.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code startWith} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param t1 * the first item to emit * @param t2 * the second item to emit * @return an Observable that emits the specified items before it begins to emit items emitted by the source * Observable * @see <a href="http://reactivex.io/documentation/operators/startwith.html">ReactiveX operators documentation: StartWith</a> */ public final Observable<T> startWith(T t1, T t2) { return concat(just(t1, t2), this); } /** * Returns an Observable that emits the specified items before it begins to emit items emitted by the source * Observable. * <p> * <img width="640" height="315" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/startWith.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code startWith} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param t1 * the first item to emit * @param t2 * the second item to emit * @param t3 * the third item to emit * @return an Observable that emits the specified items before it begins to emit items emitted by the source * Observable * @see <a href="http://reactivex.io/documentation/operators/startwith.html">ReactiveX operators documentation: StartWith</a> */ public final Observable<T> startWith(T t1, T t2, T t3) { return concat(just(t1, t2, t3), this); } /** * Returns an Observable that emits the specified items before it begins to emit items emitted by the source * Observable. * <p> * <img width="640" height="315" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/startWith.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code startWith} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param t1 * the first item to emit * @param t2 * the second item to emit * @param t3 * the third item to emit * @param t4 * the fourth item to emit * @return an Observable that emits the specified items before it begins to emit items emitted by the source * Observable * @see <a href="http://reactivex.io/documentation/operators/startwith.html">ReactiveX operators documentation: StartWith</a> */ public final Observable<T> startWith(T t1, T t2, T t3, T t4) { return concat(just(t1, t2, t3, t4), this); } /** * Returns an Observable that emits the specified items before it begins to emit items emitted by the source * Observable. * <p> * <img width="640" height="315" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/startWith.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code startWith} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param t1 * the first item to emit * @param t2 * the second item to emit * @param t3 * the third item to emit * @param t4 * the fourth item to emit * @param t5 * the fifth item to emit * @return an Observable that emits the specified items before it begins to emit items emitted by the source * Observable * @see <a href="http://reactivex.io/documentation/operators/startwith.html">ReactiveX operators documentation: StartWith</a> */ public final Observable<T> startWith(T t1, T t2, T t3, T t4, T t5) { return concat(just(t1, t2, t3, t4, t5), this); } /** * Returns an Observable that emits the specified items before it begins to emit items emitted by the source * Observable. * <p> * <img width="640" height="315" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/startWith.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code startWith} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param t1 * the first item to emit * @param t2 * the second item to emit * @param t3 * the third item to emit * @param t4 * the fourth item to emit * @param t5 * the fifth item to emit * @param t6 * the sixth item to emit * @return an Observable that emits the specified items before it begins to emit items emitted * by the source Observable * @see <a href="http://reactivex.io/documentation/operators/startwith.html">ReactiveX operators documentation: StartWith</a> */ public final Observable<T> startWith(T t1, T t2, T t3, T t4, T t5, T t6) { return concat(just(t1, t2, t3, t4, t5, t6), this); } /** * Returns an Observable that emits the specified items before it begins to emit items emitted by the source * Observable. * <p> * <img width="640" height="315" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/startWith.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code startWith} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param t1 * the first item to emit * @param t2 * the second item to emit * @param t3 * the third item to emit * @param t4 * the fourth item to emit * @param t5 * the fifth item to emit * @param t6 * the sixth item to emit * @param t7 * the seventh item to emit * @return an Observable that emits the specified items before it begins to emit items emitted by the source * Observable * @see <a href="http://reactivex.io/documentation/operators/startwith.html">ReactiveX operators documentation: StartWith</a> */ public final Observable<T> startWith(T t1, T t2, T t3, T t4, T t5, T t6, T t7) { return concat(just(t1, t2, t3, t4, t5, t6, t7), this); } /** * Returns an Observable that emits the specified items before it begins to emit items emitted by the source * Observable. * <p> * <img width="640" height="315" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/startWith.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code startWith} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param t1 * the first item to emit * @param t2 * the second item to emit * @param t3 * the third item to emit * @param t4 * the fourth item to emit * @param t5 * the fifth item to emit * @param t6 * the sixth item to emit * @param t7 * the seventh item to emit * @param t8 * the eighth item to emit * @return an Observable that emits the specified items before it begins to emit items emitted by the source * Observable * @see <a href="http://reactivex.io/documentation/operators/startwith.html">ReactiveX operators documentation: StartWith</a> */ public final Observable<T> startWith(T t1, T t2, T t3, T t4, T t5, T t6, T t7, T t8) { return concat(just(t1, t2, t3, t4, t5, t6, t7, t8), this); } /** * Returns an Observable that emits the specified items before it begins to emit items emitted by the source * Observable. * <p> * <img width="640" height="315" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/startWith.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code startWith} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param t1 * the first item to emit * @param t2 * the second item to emit * @param t3 * the third item to emit * @param t4 * the fourth item to emit * @param t5 * the fifth item to emit * @param t6 * the sixth item to emit * @param t7 * the seventh item to emit * @param t8 * the eighth item to emit * @param t9 * the ninth item to emit * @return an Observable that emits the specified items before it begins to emit items emitted by the source * Observable * @see <a href="http://reactivex.io/documentation/operators/startwith.html">ReactiveX operators documentation: StartWith</a> */ public final Observable<T> startWith(T t1, T t2, T t3, T t4, T t5, T t6, T t7, T t8, T t9) { return concat(just(t1, t2, t3, t4, t5, t6, t7, t8, t9), this); } /** * Subscribes to an Observable but ignore its emissions and notifications. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code subscribe} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @return a {@link Subscription} reference with which the {@link Observer} can stop receiving items before * the Observable has finished sending them * @throws OnErrorNotImplementedException * if the Observable tries to call {@code onError} * @see <a href="http://reactivex.io/documentation/operators/subscribe.html">ReactiveX operators documentation: Subscribe</a> */ public final Subscription subscribe() { return subscribe(new Subscriber<T>() { @Override public final void onCompleted() { // do nothing } @Override public final void onError(Throwable e) { throw new OnErrorNotImplementedException(e); } @Override public final void onNext(T args) { // do nothing } }); } /** * Subscribes to an Observable and provides a callback to handle the items it emits. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code subscribe} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param onNext * the {@code Action1<T>} you have designed to accept emissions from the Observable * @return a {@link Subscription} reference with which the {@link Observer} can stop receiving items before * the Observable has finished sending them * @throws IllegalArgumentException * if {@code onNext} is null * @throws OnErrorNotImplementedException * if the Observable calls {@code onError} * @see <a href="http://reactivex.io/documentation/operators/subscribe.html">ReactiveX operators documentation: Subscribe</a> */ public final Subscription subscribe(final Action1<? super T> onNext) { if (onNext == null) { throw new IllegalArgumentException("onNext can not be null"); } return subscribe(new Subscriber<T>() { @Override public final void onCompleted() { // do nothing } @Override public final void onError(Throwable e) { throw new OnErrorNotImplementedException(e); } @Override public final void onNext(T args) { onNext.call(args); } }); } /** * Subscribes to an Observable and provides callbacks to handle the items it emits and any error * notification it issues. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code subscribe} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param onNext * the {@code Action1<T>} you have designed to accept emissions from the Observable * @param onError * the {@code Action1<Throwable>} you have designed to accept any error notification from the * Observable * @return a {@link Subscription} reference with which the {@link Observer} can stop receiving items before * the Observable has finished sending them * @see <a href="http://reactivex.io/documentation/operators/subscribe.html">ReactiveX operators documentation: Subscribe</a> * @throws IllegalArgumentException * if {@code onNext} is null, or * if {@code onError} is null */ public final Subscription subscribe(final Action1<? super T> onNext, final Action1<Throwable> onError) { if (onNext == null) { throw new IllegalArgumentException("onNext can not be null"); } if (onError == null) { throw new IllegalArgumentException("onError can not be null"); } return subscribe(new Subscriber<T>() { @Override public final void onCompleted() { // do nothing } @Override public final void onError(Throwable e) { onError.call(e); } @Override public final void onNext(T args) { onNext.call(args); } }); } /** * Subscribes to an Observable and provides callbacks to handle the items it emits and any error or * completion notification it issues. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code subscribe} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param onNext * the {@code Action1<T>} you have designed to accept emissions from the Observable * @param onError * the {@code Action1<Throwable>} you have designed to accept any error notification from the * Observable * @param onComplete * the {@code Action0} you have designed to accept a completion notification from the * Observable * @return a {@link Subscription} reference with which the {@link Observer} can stop receiving items before * the Observable has finished sending them * @throws IllegalArgumentException * if {@code onNext} is null, or * if {@code onError} is null, or * if {@code onComplete} is null * @see <a href="http://reactivex.io/documentation/operators/subscribe.html">ReactiveX operators documentation: Subscribe</a> */ public final Subscription subscribe(final Action1<? super T> onNext, final Action1<Throwable> onError, final Action0 onComplete) { if (onNext == null) { throw new IllegalArgumentException("onNext can not be null"); } if (onError == null) { throw new IllegalArgumentException("onError can not be null"); } if (onComplete == null) { throw new IllegalArgumentException("onComplete can not be null"); } return subscribe(new Subscriber<T>() { @Override public final void onCompleted() { onComplete.call(); } @Override public final void onError(Throwable e) { onError.call(e); } @Override public final void onNext(T args) { onNext.call(args); } }); } /** * Subscribes to an Observable and provides an Observer that implements functions to handle the items the * Observable emits and any error or completion notification it issues. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code subscribe} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param observer * the Observer that will handle emissions and notifications from the Observable * @return a {@link Subscription} reference with which the {@link Observer} can stop receiving items before * the Observable has completed * @see <a href="http://reactivex.io/documentation/operators/subscribe.html">ReactiveX operators documentation: Subscribe</a> */ public final Subscription subscribe(final Observer<? super T> observer) { if (observer instanceof Subscriber) { return subscribe((Subscriber<? super T>)observer); } return subscribe(new Subscriber<T>() { @Override public void onCompleted() { observer.onCompleted(); } @Override public void onError(Throwable e) { observer.onError(e); } @Override public void onNext(T t) { observer.onNext(t); } }); } /** * Subscribes to an Observable and invokes {@link OnSubscribe} function without any contract protection, * error handling, unsubscribe, or execution hooks. * <p> * Use this only for implementing an {@link Operator} that requires nested subscriptions. For other * purposes, use {@link #subscribe(Subscriber)} which ensures * <a href="http://reactivex.io/documentation/contract.html">the Observable contract</a> and other * functionality. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code unsafeSubscribe} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param subscriber * the Subscriber that will handle emissions and notifications from the Observable * @return a {@link Subscription} reference with which the {@link Subscriber} can stop receiving items * before the Observable has completed */ public final Subscription unsafeSubscribe(Subscriber<? super T> subscriber) { try { // new Subscriber so onStart it subscriber.onStart(); // allow the hook to intercept and/or decorate hook.onSubscribeStart(this, onSubscribe).call(subscriber); return hook.onSubscribeReturn(subscriber); } catch (Throwable e) { // special handling for certain Throwable/Error/Exception types Exceptions.throwIfFatal(e); // if an unhandled error occurs executing the onSubscribe we will propagate it try { subscriber.onError(hook.onSubscribeError(e)); } catch (OnErrorNotImplementedException e2) { // special handling when onError is not implemented ... we just rethrow throw e2; } catch (Throwable e2) { // if this happens it means the onError itself failed (perhaps an invalid function implementation) // so we are unable to propagate the error correctly and will just throw RuntimeException r = new RuntimeException("Error occurred attempting to subscribe [" + e.getMessage() + "] and then again while trying to pass to onError.", e2); // TODO could the hook be the cause of the error in the on error handling. hook.onSubscribeError(r); // TODO why aren't we throwing the hook's return value. throw r; } return Subscriptions.unsubscribed(); } } /** * Subscribes to an Observable and provides a Subscriber that implements functions to handle the items the * Observable emits and any error or completion notification it issues. * <p> * A typical implementation of {@code subscribe} does the following: * <ol> * <li>It stores a reference to the Subscriber in a collection object, such as a {@code List<T>} object.</li> * <li>It returns a reference to the {@link Subscription} interface. This enables Subscribers to * unsubscribe, that is, to stop receiving items and notifications before the Observable completes, which * also invokes the Subscriber's {@link Subscriber#onCompleted onCompleted} method.</li> * </ol><p> * An {@code Observable<T>} instance is responsible for accepting all subscriptions and notifying all * Subscribers. Unless the documentation for a particular {@code Observable<T>} implementation indicates * otherwise, Subscriber should make no assumptions about the order in which multiple Subscribers will * receive their notifications. * <p> * For more information see the * <a href="http://reactivex.io/documentation/observable.html">ReactiveX documentation</a>. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code subscribe} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param subscriber * the {@link Subscriber} that will handle emissions and notifications from the Observable * @return a {@link Subscription} reference with which Subscribers that are {@link Observer}s can * unsubscribe from the Observable * @throws IllegalStateException * if {@code subscribe} is unable to obtain an {@code OnSubscribe<>} function * @throws IllegalArgumentException * if the {@link Subscriber} provided as the argument to {@code subscribe} is {@code null} * @throws OnErrorNotImplementedException * if the {@link Subscriber}'s {@code onError} method is null * @throws RuntimeException * if the {@link Subscriber}'s {@code onError} method itself threw a {@code Throwable} * @see <a href="http://reactivex.io/documentation/operators/subscribe.html">ReactiveX operators documentation: Subscribe</a> */ public final Subscription subscribe(Subscriber<? super T> subscriber) { return Observable.subscribe(subscriber, this); } private static <T> Subscription subscribe(Subscriber<? super T> subscriber, Observable<T> observable) { // validate and proceed if (subscriber == null) { throw new IllegalArgumentException("observer can not be null"); } if (observable.onSubscribe == null) { throw new IllegalStateException("onSubscribe function can not be null."); /* * the subscribe function can also be overridden but generally that's not the appropriate approach * so I won't mention that in the exception */ } // new Subscriber so onStart it subscriber.onStart(); /* * See https://github.com/ReactiveX/RxJava/issues/216 for discussion on "Guideline 6.4: Protect calls * to user code from within an Observer" */ // if not already wrapped if (!(subscriber instanceof SafeSubscriber)) { // assign to `observer` so we return the protected version subscriber = new SafeSubscriber<T>(subscriber); } // The code below is exactly the same an unsafeSubscribe but not used because it would // add a significant depth to already huge call stacks. try { // allow the hook to intercept and/or decorate hook.onSubscribeStart(observable, observable.onSubscribe).call(subscriber); return hook.onSubscribeReturn(subscriber); } catch (Throwable e) { // special handling for certain Throwable/Error/Exception types Exceptions.throwIfFatal(e); // if an unhandled error occurs executing the onSubscribe we will propagate it try { subscriber.onError(hook.onSubscribeError(e)); } catch (OnErrorNotImplementedException e2) { // special handling when onError is not implemented ... we just rethrow throw e2; } catch (Throwable e2) { // if this happens it means the onError itself failed (perhaps an invalid function implementation) // so we are unable to propagate the error correctly and will just throw RuntimeException r = new RuntimeException("Error occurred attempting to subscribe [" + e.getMessage() + "] and then again while trying to pass to onError.", e2); // TODO could the hook be the cause of the error in the on error handling. hook.onSubscribeError(r); // TODO why aren't we throwing the hook's return value. throw r; } return Subscriptions.unsubscribed(); } } /** * Asynchronously subscribes Observers to this Observable on the specified {@link Scheduler}. * <p> * <img width="640" height="305" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/subscribeOn.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>you specify which {@link Scheduler} this operator will use</dd> * </dl> * * @param scheduler * the {@link Scheduler} to perform subscription actions on * @return the source Observable modified so that its subscriptions happen on the * specified {@link Scheduler} * @see <a href="http://reactivex.io/documentation/operators/subscribeon.html">ReactiveX operators documentation: SubscribeOn</a> * @see <a href="http://www.grahamlea.com/2014/07/rxjava-threading-examples/">RxJava Threading Examples</a> * @see #observeOn */ public final Observable<T> subscribeOn(Scheduler scheduler) { if (this instanceof ScalarSynchronousObservable) { return ((ScalarSynchronousObservable<T>)this).scalarScheduleOn(scheduler); } return nest().lift(new OperatorSubscribeOn<T>(scheduler)); } /** * Returns a new Observable by applying a function that you supply to each item emitted by the source * Observable that returns an Observable, and then emitting the items emitted by the most recently emitted * of these Observables. * <p> * <img width="640" height="350" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/switchMap.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code switchMap} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param func * a function that, when applied to an item emitted by the source Observable, returns an * Observable * @return an Observable that emits the items emitted by the Observable returned from applying {@code func} to the most recently emitted item emitted by the source Observable * @see <a href="http://reactivex.io/documentation/operators/flatmap.html">ReactiveX operators documentation: FlatMap</a> */ public final <R> Observable<R> switchMap(Func1<? super T, ? extends Observable<? extends R>> func) { return switchOnNext(map(func)); } /** * Returns an Observable that emits only the first {@code count} items emitted by the source Observable. If the source emits fewer than * {@code count} items then all of its items are emitted. * <p> * <img width="640" height="305" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/take.png" alt=""> * <p> * This method returns an Observable that will invoke a subscribing {@link Observer}'s * {@link Observer#onNext onNext} function a maximum of {@code count} times before invoking * {@link Observer#onCompleted onCompleted}. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>This version of {@code take} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param count * the maximum number of items to emit * @return an Observable that emits only the first {@code count} items emitted by the source Observable, or * all of the items from the source Observable if that Observable emits fewer than {@code count} items * @see <a href="http://reactivex.io/documentation/operators/take.html">ReactiveX operators documentation: Take</a> */ public final Observable<T> take(final int count) { return lift(new OperatorTake<T>(count)); } /** * Returns an Observable that emits those items emitted by source Observable before a specified time runs * out. * <p> * <img width="640" height="305" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/take.t.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>This version of {@code take} operates by default on the {@code computation} {@link Scheduler}.</dd> * </dl> * * @param time * the length of the time window * @param unit * the time unit of {@code time} * @return an Observable that emits those items emitted by the source Observable before the time runs out * @see <a href="http://reactivex.io/documentation/operators/take.html">ReactiveX operators documentation: Take</a> */ public final Observable<T> take(long time, TimeUnit unit) { return take(time, unit, Schedulers.computation()); } /** * Returns an Observable that emits those items emitted by source Observable before a specified time (on a * specified Scheduler) runs out. * <p> * <img width="640" height="305" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/take.ts.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>you specify which {@link Scheduler} this operator will use</dd> * </dl> * * @param time * the length of the time window * @param unit * the time unit of {@code time} * @param scheduler * the Scheduler used for time source * @return an Observable that emits those items emitted by the source Observable before the time runs out, * according to the specified Scheduler * @see <a href="http://reactivex.io/documentation/operators/take.html">ReactiveX operators documentation: Take</a> */ public final Observable<T> take(long time, TimeUnit unit, Scheduler scheduler) { return lift(new OperatorTakeTimed<T>(time, unit, scheduler)); } /** * Returns an Observable that emits only the very first item emitted by the source Observable that satisfies * a specified condition. * <p> * <img width="640" height="305" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/takeFirstN.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code takeFirst} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param predicate * the condition any item emitted by the source Observable has to satisfy * @return an Observable that emits only the very first item emitted by the source Observable that satisfies * the given condition, or that completes without emitting anything if the source Observable * completes without emitting a single condition-satisfying item * @see <a href="http://reactivex.io/documentation/operators/first.html">ReactiveX operators documentation: First</a> */ public final Observable<T> takeFirst(Func1<? super T, Boolean> predicate) { return filter(predicate).take(1); } /** * Returns an Observable that emits at most the last {@code count} items emitted by the source Observable. If the source emits fewer than * {@code count} items then all of its items are emitted. * <p> * <img width="640" height="310" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/takeLast.n.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>This version of {@code takeLast} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param count * the maximum number of items to emit from the end of the sequence of items emitted by the source * Observable * @return an Observable that emits at most the last {@code count} items emitted by the source Observable * @throws IndexOutOfBoundsException * if {@code count} is less than zero * @see <a href="http://reactivex.io/documentation/operators/takelast.html">ReactiveX operators documentation: TakeLast</a> */ public final Observable<T> takeLast(final int count) { if (count == 0) return ignoreElements(); else if (count == 1 ) return lift(OperatorTakeLastOne.<T>instance()); else return lift(new OperatorTakeLast<T>(count)); } /** * Returns an Observable that emits at most a specified number of items from the source Observable that were * emitted in a specified window of time before the Observable completed. * <p> * <img width="640" height="310" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/takeLast.tn.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>This version of {@code takeLast} operates by default on the {@code computation} {@link Scheduler}.</dd> * </dl> * * @param count * the maximum number of items to emit * @param time * the length of the time window * @param unit * the time unit of {@code time} * @return an Observable that emits at most {@code count} items from the source Observable that were emitted * in a specified window of time before the Observable completed * @see <a href="http://reactivex.io/documentation/operators/takelast.html">ReactiveX operators documentation: TakeLast</a> */ public final Observable<T> takeLast(int count, long time, TimeUnit unit) { return takeLast(count, time, unit, Schedulers.computation()); } /** * Returns an Observable that emits at most a specified number of items from the source Observable that were * emitted in a specified window of time before the Observable completed, where the timing information is * provided by a given Scheduler. * <p> * <img width="640" height="310" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/takeLast.tns.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>you specify which {@link Scheduler} this operator will use</dd> * </dl> * * @param count * the maximum number of items to emit * @param time * the length of the time window * @param unit * the time unit of {@code time} * @param scheduler * the {@link Scheduler} that provides the timestamps for the observed items * @return an Observable that emits at most {@code count} items from the source Observable that were emitted * in a specified window of time before the Observable completed, where the timing information is * provided by the given {@code scheduler} * @throws IndexOutOfBoundsException * if {@code count} is less than zero * @see <a href="http://reactivex.io/documentation/operators/takelast.html">ReactiveX operators documentation: TakeLast</a> */ public final Observable<T> takeLast(int count, long time, TimeUnit unit, Scheduler scheduler) { return lift(new OperatorTakeLastTimed<T>(count, time, unit, scheduler)); } /** * Returns an Observable that emits the items from the source Observable that were emitted in a specified * window of time before the Observable completed. * <p> * <img width="640" height="310" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/takeLast.t.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>This version of {@code takeLast} operates by default on the {@code computation} {@link Scheduler}.</dd> * </dl> * * @param time * the length of the time window * @param unit * the time unit of {@code time} * @return an Observable that emits the items from the source Observable that were emitted in the window of * time before the Observable completed specified by {@code time} * @see <a href="http://reactivex.io/documentation/operators/takelast.html">ReactiveX operators documentation: TakeLast</a> */ public final Observable<T> takeLast(long time, TimeUnit unit) { return takeLast(time, unit, Schedulers.computation()); } /** * Returns an Observable that emits the items from the source Observable that were emitted in a specified * window of time before the Observable completed, where the timing information is provided by a specified * Scheduler. * <p> * <img width="640" height="310" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/takeLast.ts.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>you specify which {@link Scheduler} this operator will use</dd> * </dl> * * @param time * the length of the time window * @param unit * the time unit of {@code time} * @param scheduler * the Scheduler that provides the timestamps for the Observed items * @return an Observable that emits the items from the source Observable that were emitted in the window of * time before the Observable completed specified by {@code time}, where the timing information is * provided by {@code scheduler} * @see <a href="http://reactivex.io/documentation/operators/takelast.html">ReactiveX operators documentation: TakeLast</a> */ public final Observable<T> takeLast(long time, TimeUnit unit, Scheduler scheduler) { return lift(new OperatorTakeLastTimed<T>(time, unit, scheduler)); } /** * Returns an Observable that emits a single List containing at most the last {@code count} elements emitted by the * source Observable. If the source emits fewer than {@code count} items then the emitted List will contain all of the source emissions. * <p> * <img width="640" height="310" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/takeLastBuffer.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>This version of {@code takeLastBuffer} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param count * the maximum number of items to emit in the list * @return an Observable that emits a single list containing at most the last {@code count} elements emitted by the * source Observable * @see <a href="http://reactivex.io/documentation/operators/takelast.html">ReactiveX operators documentation: TakeLast</a> */ public final Observable<List<T>> takeLastBuffer(int count) { return takeLast(count).toList(); } /** * Returns an Observable that emits a single List containing at most {@code count} items from the source * Observable that were emitted during a specified window of time before the source Observable completed. * <p> * <img width="640" height="310" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/takeLastBuffer.tn.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>This version of {@code takeLastBuffer} operates by default on the {@code computation} {@link Scheduler}.</dd> * </dl> * * @param count * the maximum number of items to emit * @param time * the length of the time window * @param unit * the time unit of {@code time} * @return an Observable that emits a single List containing at most {@code count} items emitted by the * source Observable during the time window defined by {@code time} before the source Observable * completed * @see <a href="http://reactivex.io/documentation/operators/takelast.html">ReactiveX operators documentation: TakeLast</a> */ public final Observable<List<T>> takeLastBuffer(int count, long time, TimeUnit unit) { return takeLast(count, time, unit).toList(); } /** * Returns an Observable that emits a single List containing at most {@code count} items from the source * Observable that were emitted during a specified window of time (on a specified Scheduler) before the * source Observable completed. * <p> * <img width="640" height="310" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/takeLastBuffer.tns.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>you specify which {@link Scheduler} this operator will use</dd> * </dl> * * @param count * the maximum number of items to emit * @param time * the length of the time window * @param unit * the time unit of {@code time} * @param scheduler * the Scheduler that provides the timestamps for the observed items * @return an Observable that emits a single List containing at most {@code count} items emitted by the * source Observable during the time window defined by {@code time} before the source Observable * completed * @see <a href="http://reactivex.io/documentation/operators/takelast.html">ReactiveX operators documentation: TakeLast</a> */ public final Observable<List<T>> takeLastBuffer(int count, long time, TimeUnit unit, Scheduler scheduler) { return takeLast(count, time, unit, scheduler).toList(); } /** * Returns an Observable that emits a single List containing those items from the source Observable that * were emitted during a specified window of time before the source Observable completed. * <p> * <img width="640" height="310" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/takeLastBuffer.t.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>This version of {@code takeLastBuffer} operates by default on the {@code computation} {@link Scheduler}.</dd> * </dl> * * @param time * the length of the time window * @param unit * the time unit of {@code time} * @return an Observable that emits a single List containing the items emitted by the source Observable * during the time window defined by {@code time} before the source Observable completed * @see <a href="http://reactivex.io/documentation/operators/takelast.html">ReactiveX operators documentation: TakeLast</a> */ public final Observable<List<T>> takeLastBuffer(long time, TimeUnit unit) { return takeLast(time, unit).toList(); } /** * Returns an Observable that emits a single List containing those items from the source Observable that * were emitted during a specified window of time before the source Observable completed, where the timing * information is provided by the given Scheduler. * <p> * <img width="640" height="310" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/takeLastBuffer.ts.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>you specify which {@link Scheduler} this operator will use</dd> * </dl> * * @param time * the length of the time window * @param unit * the time unit of {@code time} * @param scheduler * the Scheduler that provides the timestamps for the observed items * @return an Observable that emits a single List containing the items emitted by the source Observable * during the time window defined by {@code time} before the source Observable completed, where the * timing information is provided by {@code scheduler} * @see <a href="http://reactivex.io/documentation/operators/takelast.html">ReactiveX operators documentation: TakeLast</a> */ public final Observable<List<T>> takeLastBuffer(long time, TimeUnit unit, Scheduler scheduler) { return takeLast(time, unit, scheduler).toList(); } /** * Returns an Observable that emits the items emitted by the source Observable until a second Observable * emits an item. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/takeUntil.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code takeUntil} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param other * the Observable whose first emitted item will cause {@code takeUntil} to stop emitting items * from the source Observable * @param <E> * the type of items emitted by {@code other} * @return an Observable that emits the items emitted by the source Observable until such time as {@code other} emits its first item * @see <a href="http://reactivex.io/documentation/operators/takeuntil.html">ReactiveX operators documentation: TakeUntil</a> */ public final <E> Observable<T> takeUntil(Observable<? extends E> other) { return lift(new OperatorTakeUntil<T, E>(other)); } /** * Returns an Observable that emits items emitted by the source Observable so long as each item satisfied a * specified condition, and then completes as soon as this condition is not satisfied. * <p> * <img width="640" height="305" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/takeWhile.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code takeWhile} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param predicate * a function that evaluates an item emitted by the source Observable and returns a Boolean * @return an Observable that emits the items from the source Observable so long as each item satisfies the * condition defined by {@code predicate}, then completes * @see <a href="http://reactivex.io/documentation/operators/takewhile.html">ReactiveX operators documentation: TakeWhile</a> * @see Observable#takeUntil(Func1) */ public final Observable<T> takeWhile(final Func1<? super T, Boolean> predicate) { return lift(new OperatorTakeWhile<T>(predicate)); } /** * Returns an Observable that emits items emitted by the source Observable, checks the specified predicate * for each item, and then completes if the condition is satisfied. * <p> * <img width="640" height="305" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/takeUntil.p.png" alt=""> * <p> * The difference between this operator and {@link #takeWhile(Func1)} is that here, the condition is * evaluated <em>after</em> the item is emitted. * * @warn "Scheduler" and "Backpressure Support" sections missing from javadocs * @param stopPredicate * a function that evaluates an item emitted by the source Observable and returns a Boolean * @return an Observable that first emits items emitted by the source Observable, checks the specified * condition after each item, and then completes if the condition is satisfied. * @see <a href="http://reactivex.io/documentation/operators/takeuntil.html">ReactiveX operators documentation: TakeUntil</a> * @see Observable#takeWhile(Func1) * @since (if this graduates from Experimental/Beta to supported, replace this parenthetical with the release number) */ @Experimental public final Observable<T> takeUntil(final Func1<? super T, Boolean> stopPredicate) { return lift(new OperatorTakeUntilPredicate<T>(stopPredicate)); } /** * Returns an Observable that emits only the first item emitted by the source Observable during sequential * time windows of a specified duration. * <p> * This differs from {@link #throttleLast} in that this only tracks passage of time whereas * {@link #throttleLast} ticks at scheduled intervals. * <p> * <img width="640" height="305" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/throttleFirst.png" alt=""> * <dl> * <dt><b>Backpressure Support:</b></dt> * <dd>This operator does not support backpressure as it uses time to control data flow.</dd> * <dt><b>Scheduler:</b></dt> * <dd>{@code throttleFirst} operates by default on the {@code computation} {@link Scheduler}.</dd> * </dl> * * @param windowDuration * time to wait before emitting another item after emitting the last item * @param unit * the unit of time of {@code windowDuration} * @return an Observable that performs the throttle operation * @see <a href="http://reactivex.io/documentation/operators/sample.html">ReactiveX operators documentation: Sample</a> * @see <a href="https://github.com/ReactiveX/RxJava/wiki/Backpressure">RxJava wiki: Backpressure</a> */ public final Observable<T> throttleFirst(long windowDuration, TimeUnit unit) { return throttleFirst(windowDuration, unit, Schedulers.computation()); } /** * Returns an Observable that emits only the first item emitted by the source Observable during sequential * time windows of a specified duration, where the windows are managed by a specified Scheduler. * <p> * This differs from {@link #throttleLast} in that this only tracks passage of time whereas * {@link #throttleLast} ticks at scheduled intervals. * <p> * <img width="640" height="305" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/throttleFirst.s.png" alt=""> * <dl> * <dt><b>Backpressure Support:</b></dt> * <dd>This operator does not support backpressure as it uses time to control data flow.</dd> * <dt><b>Scheduler:</b></dt> * <dd>you specify which {@link Scheduler} this operator will use</dd> * </dl> * * @param skipDuration * time to wait before emitting another item after emitting the last item * @param unit * the unit of time of {@code skipDuration} * @param scheduler * the {@link Scheduler} to use internally to manage the timers that handle timeout for each * event * @return an Observable that performs the throttle operation * @see <a href="http://reactivex.io/documentation/operators/sample.html">ReactiveX operators documentation: Sample</a> * @see <a href="https://github.com/ReactiveX/RxJava/wiki/Backpressure">RxJava wiki: Backpressure</a> */ public final Observable<T> throttleFirst(long skipDuration, TimeUnit unit, Scheduler scheduler) { return lift(new OperatorThrottleFirst<T>(skipDuration, unit, scheduler)); } /** * Returns an Observable that emits only the last item emitted by the source Observable during sequential * time windows of a specified duration. * <p> * This differs from {@link #throttleFirst} in that this ticks along at a scheduled interval whereas * {@link #throttleFirst} does not tick, it just tracks passage of time. * <p> * <img width="640" height="305" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/throttleLast.png" alt=""> * <dl> * <dt><b>Backpressure Support:</b></dt> * <dd>This operator does not support backpressure as it uses time to control data flow.</dd> * <dt><b>Scheduler:</b></dt> * <dd>{@code throttleLast} operates by default on the {@code computation} {@link Scheduler}.</dd> * </dl> * * @param intervalDuration * duration of windows within which the last item emitted by the source Observable will be * emitted * @param unit * the unit of time of {@code intervalDuration} * @return an Observable that performs the throttle operation * @see <a href="http://reactivex.io/documentation/operators/sample.html">ReactiveX operators documentation: Sample</a> * @see <a href="https://github.com/ReactiveX/RxJava/wiki/Backpressure">RxJava wiki: Backpressure</a> * @see #sample(long, TimeUnit) */ public final Observable<T> throttleLast(long intervalDuration, TimeUnit unit) { return sample(intervalDuration, unit); } /** * Returns an Observable that emits only the last item emitted by the source Observable during sequential * time windows of a specified duration, where the duration is governed by a specified Scheduler. * <p> * This differs from {@link #throttleFirst} in that this ticks along at a scheduled interval whereas * {@link #throttleFirst} does not tick, it just tracks passage of time. * <p> * <img width="640" height="305" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/throttleLast.s.png" alt=""> * <dl> * <dt><b>Backpressure Support:</b></dt> * <dd>This operator does not support backpressure as it uses time to control data flow.</dd> * <dt><b>Scheduler:</b></dt> * <dd>you specify which {@link Scheduler} this operator will use</dd> * </dl> * * @param intervalDuration * duration of windows within which the last item emitted by the source Observable will be * emitted * @param unit * the unit of time of {@code intervalDuration} * @param scheduler * the {@link Scheduler} to use internally to manage the timers that handle timeout for each * event * @return an Observable that performs the throttle operation * @see <a href="http://reactivex.io/documentation/operators/sample.html">ReactiveX operators documentation: Sample</a> * @see <a href="https://github.com/ReactiveX/RxJava/wiki/Backpressure">RxJava wiki: Backpressure</a> * @see #sample(long, TimeUnit, Scheduler) */ public final Observable<T> throttleLast(long intervalDuration, TimeUnit unit, Scheduler scheduler) { return sample(intervalDuration, unit, scheduler); } /** * Returns an Observable that only emits those items emitted by the source Observable that are not followed * by another emitted item within a specified time window. * <p> * <em>Note:</em> If the source Observable keeps emitting items more frequently than the length of the time * window then no items will be emitted by the resulting Observable. * <p> * <img width="640" height="305" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/throttleWithTimeout.png" alt=""> * <p> * Information on debounce vs throttle: * <p> * <ul> * <li><a href="http://drupalmotion.com/article/debounce-and-throttle-visual-explanation">Debounce and Throttle: visual explanation</a></li> * <li><a href="http://unscriptable.com/2009/03/20/debouncing-javascript-methods/">Debouncing: javascript methods</a></li> * <li><a href="http://www.illyriad.co.uk/blog/index.php/2011/09/javascript-dont-spam-your-server-debounce-and-throttle/">Javascript - don't spam your server: debounce and throttle</a></li> * </ul> * <dl> * <dt><b>Backpressure Support:</b></dt> * <dd>This operator does not support backpressure as it uses time to control data flow.</dd> * <dt><b>Scheduler:</b></dt> * <dd>{@code throttleWithTimeout} operates by default on the {@code computation} {@link Scheduler}.</dd> * </dl> * * @param timeout * the length of the window of time that must pass after the emission of an item from the source * Observable in which that Observable emits no items in order for the item to be emitted by the * resulting Observable * @param unit * the {@link TimeUnit} of {@code timeout} * @return an Observable that filters out items that are too quickly followed by newer items * @see <a href="http://reactivex.io/documentation/operators/debounce.html">ReactiveX operators documentation: Debounce</a> * @see <a href="https://github.com/ReactiveX/RxJava/wiki/Backpressure">RxJava wiki: Backpressure</a> * @see #debounce(long, TimeUnit) */ public final Observable<T> throttleWithTimeout(long timeout, TimeUnit unit) { return debounce(timeout, unit); } /** * Returns an Observable that only emits those items emitted by the source Observable that are not followed * by another emitted item within a specified time window, where the time window is governed by a specified * Scheduler. * <p> * <em>Note:</em> If the source Observable keeps emitting items more frequently than the length of the time * window then no items will be emitted by the resulting Observable. * <p> * <img width="640" height="305" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/throttleWithTimeout.s.png" alt=""> * <p> * Information on debounce vs throttle: * <p> * <ul> * <li><a href="http://drupalmotion.com/article/debounce-and-throttle-visual-explanation">Debounce and Throttle: visual explanation</a></li> * <li><a href="http://unscriptable.com/2009/03/20/debouncing-javascript-methods/">Debouncing: javascript methods</a></li> * <li><a href="http://www.illyriad.co.uk/blog/index.php/2011/09/javascript-dont-spam-your-server-debounce-and-throttle/">Javascript - don't spam your server: debounce and throttle</a></li> * </ul> * <dl> * <dt><b>Backpressure Support:</b></dt> * <dd>This operator does not support backpressure as it uses time to control data flow.</dd> * <dt><b>Scheduler:</b></dt> * <dd>you specify which {@link Scheduler} this operator will use</dd> * </dl> * * @param timeout * the length of the window of time that must pass after the emission of an item from the source * Observable in which that Observable emits no items in order for the item to be emitted by the * resulting Observable * @param unit * the {@link TimeUnit} of {@code timeout} * @param scheduler * the {@link Scheduler} to use internally to manage the timers that handle the timeout for each * item * @return an Observable that filters out items that are too quickly followed by newer items * @see <a href="http://reactivex.io/documentation/operators/debounce.html">ReactiveX operators documentation: Debounce</a> * @see <a href="https://github.com/ReactiveX/RxJava/wiki/Backpressure">RxJava wiki: Backpressure</a> * @see #debounce(long, TimeUnit, Scheduler) */ public final Observable<T> throttleWithTimeout(long timeout, TimeUnit unit, Scheduler scheduler) { return debounce(timeout, unit, scheduler); } /** * Returns an Observable that emits records of the time interval between consecutive items emitted by the * source Observable. * <p> * <img width="640" height="310" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/timeInterval.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code timeInterval} operates by default on the {@code immediate} {@link Scheduler}.</dd> * </dl> * * @return an Observable that emits time interval information items * @see <a href="http://reactivex.io/documentation/operators/timeinterval.html">ReactiveX operators documentation: TimeInterval</a> */ public final Observable<TimeInterval<T>> timeInterval() { return timeInterval(Schedulers.immediate()); } /** * Returns an Observable that emits records of the time interval between consecutive items emitted by the * source Observable, where this interval is computed on a specified Scheduler. * <p> * <img width="640" height="315" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/timeInterval.s.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>you specify which {@link Scheduler} this operator will use</dd> * </dl> * * @param scheduler * the {@link Scheduler} used to compute time intervals * @return an Observable that emits time interval information items * @see <a href="http://reactivex.io/documentation/operators/timeinterval.html">ReactiveX operators documentation: TimeInterval</a> */ public final Observable<TimeInterval<T>> timeInterval(Scheduler scheduler) { return lift(new OperatorTimeInterval<T>(scheduler)); } /** * Returns an Observable that mirrors the source Observable, but notifies observers of a * {@code TimeoutException} if either the first item emitted by the source Observable or any subsequent item * doesn't arrive within time windows defined by other Observables. * <p> * <img width="640" height="400" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/timeout5.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>This version of {@code timeout} operates by default on the {@code immediate} {@link Scheduler}.</dd> * </dl> * * @param <U> * the first timeout value type (ignored) * @param <V> * the subsequent timeout value type (ignored) * @param firstTimeoutSelector * a function that returns an Observable that determines the timeout window for the first source * item * @param timeoutSelector * a function that returns an Observable for each item emitted by the source Observable and that * determines the timeout window in which the subsequent source item must arrive in order to * continue the sequence * @return an Observable that mirrors the source Observable, but notifies observers of a * {@code TimeoutException} if either the first item or any subsequent item doesn't arrive within * the time windows specified by the timeout selectors * @see <a href="http://reactivex.io/documentation/operators/timeout.html">ReactiveX operators documentation: Timeout</a> */ public final <U, V> Observable<T> timeout(Func0<? extends Observable<U>> firstTimeoutSelector, Func1<? super T, ? extends Observable<V>> timeoutSelector) { return timeout(firstTimeoutSelector, timeoutSelector, null); } /** * Returns an Observable that mirrors the source Observable, but switches to a fallback Observable if either * the first item emitted by the source Observable or any subsequent item doesn't arrive within time windows * defined by other Observables. * <p> * <img width="640" height="400" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/timeout6.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>This version of {@code timeout} operates by default on the {@code immediate} {@link Scheduler}.</dd> * </dl> * * @param <U> * the first timeout value type (ignored) * @param <V> * the subsequent timeout value type (ignored) * @param firstTimeoutSelector * a function that returns an Observable which determines the timeout window for the first source * item * @param timeoutSelector * a function that returns an Observable for each item emitted by the source Observable and that * determines the timeout window in which the subsequent source item must arrive in order to * continue the sequence * @param other * the fallback Observable to switch to if the source Observable times out * @return an Observable that mirrors the source Observable, but switches to the {@code other} Observable if * either the first item emitted by the source Observable or any subsequent item doesn't arrive * within time windows defined by the timeout selectors * @throws NullPointerException * if {@code timeoutSelector} is null * @see <a href="http://reactivex.io/documentation/operators/timeout.html">ReactiveX operators documentation: Timeout</a> */ public final <U, V> Observable<T> timeout(Func0<? extends Observable<U>> firstTimeoutSelector, Func1<? super T, ? extends Observable<V>> timeoutSelector, Observable<? extends T> other) { if (timeoutSelector == null) { throw new NullPointerException("timeoutSelector is null"); } return lift(new OperatorTimeoutWithSelector<T, U, V>(firstTimeoutSelector, timeoutSelector, other)); } /** * Returns an Observable that mirrors the source Observable, but notifies observers of a * {@code TimeoutException} if an item emitted by the source Observable doesn't arrive within a window of * time after the emission of the previous item, where that period of time is measured by an Observable that * is a function of the previous item. * <p> * <img width="640" height="400" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/timeout3.png" alt=""> * <p> * Note: The arrival of the first source item is never timed out. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>This version of {@code timeout} operates by default on the {@code immediate} {@link Scheduler}.</dd> * </dl> * * @param <V> * the timeout value type (ignored) * @param timeoutSelector * a function that returns an observable for each item emitted by the source * Observable and that determines the timeout window for the subsequent item * @return an Observable that mirrors the source Observable, but notifies observers of a * {@code TimeoutException} if an item emitted by the source Observable takes longer to arrive than * the time window defined by the selector for the previously emitted item * @see <a href="http://reactivex.io/documentation/operators/timeout.html">ReactiveX operators documentation: Timeout</a> */ public final <V> Observable<T> timeout(Func1<? super T, ? extends Observable<V>> timeoutSelector) { return timeout(null, timeoutSelector, null); } /** * Returns an Observable that mirrors the source Observable, but that switches to a fallback Observable if * an item emitted by the source Observable doesn't arrive within a window of time after the emission of the * previous item, where that period of time is measured by an Observable that is a function of the previous * item. * <p> * <img width="640" height="400" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/timeout4.png" alt=""> * <p> * Note: The arrival of the first source item is never timed out. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>This version of {@code timeout} operates by default on the {@code immediate} {@link Scheduler}.</dd> * </dl> * * @param <V> * the timeout value type (ignored) * @param timeoutSelector * a function that returns an Observable, for each item emitted by the source Observable, that * determines the timeout window for the subsequent item * @param other * the fallback Observable to switch to if the source Observable times out * @return an Observable that mirrors the source Observable, but switches to mirroring a fallback Observable * if an item emitted by the source Observable takes longer to arrive than the time window defined * by the selector for the previously emitted item * @see <a href="http://reactivex.io/documentation/operators/timeout.html">ReactiveX operators documentation: Timeout</a> */ public final <V> Observable<T> timeout(Func1<? super T, ? extends Observable<V>> timeoutSelector, Observable<? extends T> other) { return timeout(null, timeoutSelector, other); } /** * Returns an Observable that mirrors the source Observable but applies a timeout policy for each emitted * item. If the next item isn't emitted within the specified timeout duration starting from its predecessor, * the resulting Observable terminates and notifies observers of a {@code TimeoutException}. * <p> * <img width="640" height="305" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/timeout.1.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>This version of {@code timeout} operates by default on the {@code computation} {@link Scheduler}.</dd> * </dl> * * @param timeout * maximum duration between emitted items before a timeout occurs * @param timeUnit * the unit of time that applies to the {@code timeout} argument. * @return the source Observable modified to notify observers of a {@code TimeoutException} in case of a * timeout * @see <a href="http://reactivex.io/documentation/operators/timeout.html">ReactiveX operators documentation: Timeout</a> */ public final Observable<T> timeout(long timeout, TimeUnit timeUnit) { return timeout(timeout, timeUnit, null, Schedulers.computation()); } /** * Returns an Observable that mirrors the source Observable but applies a timeout policy for each emitted * item. If the next item isn't emitted within the specified timeout duration starting from its predecessor, * the resulting Observable begins instead to mirror a fallback Observable. * <p> * <img width="640" height="305" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/timeout.2.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>This version of {@code timeout} operates by default on the {@code computation} {@link Scheduler}.</dd> * </dl> * * @param timeout * maximum duration between items before a timeout occurs * @param timeUnit * the unit of time that applies to the {@code timeout} argument * @param other * the fallback Observable to use in case of a timeout * @return the source Observable modified to switch to the fallback Observable in case of a timeout * @see <a href="http://reactivex.io/documentation/operators/timeout.html">ReactiveX operators documentation: Timeout</a> */ public final Observable<T> timeout(long timeout, TimeUnit timeUnit, Observable<? extends T> other) { return timeout(timeout, timeUnit, other, Schedulers.computation()); } /** * Returns an Observable that mirrors the source Observable but applies a timeout policy for each emitted * item using a specified Scheduler. If the next item isn't emitted within the specified timeout duration * starting from its predecessor, the resulting Observable begins instead to mirror a fallback Observable. * <p> * <img width="640" height="305" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/timeout.2s.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>you specify which {@link Scheduler} this operator will use</dd> * </dl> * * @param timeout * maximum duration between items before a timeout occurs * @param timeUnit * the unit of time that applies to the {@code timeout} argument * @param other * the Observable to use as the fallback in case of a timeout * @param scheduler * the {@link Scheduler} to run the timeout timers on * @return the source Observable modified so that it will switch to the fallback Observable in case of a * timeout * @see <a href="http://reactivex.io/documentation/operators/timeout.html">ReactiveX operators documentation: Timeout</a> */ public final Observable<T> timeout(long timeout, TimeUnit timeUnit, Observable<? extends T> other, Scheduler scheduler) { return lift(new OperatorTimeout<T>(timeout, timeUnit, other, scheduler)); } /** * Returns an Observable that mirrors the source Observable but applies a timeout policy for each emitted * item, where this policy is governed on a specified Scheduler. If the next item isn't emitted within the * specified timeout duration starting from its predecessor, the resulting Observable terminates and * notifies observers of a {@code TimeoutException}. * <p> * <img width="640" height="305" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/timeout.1s.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>you specify which {@link Scheduler} this operator will use</dd> * </dl> * * @param timeout * maximum duration between items before a timeout occurs * @param timeUnit * the unit of time that applies to the {@code timeout} argument * @param scheduler * the Scheduler to run the timeout timers on * @return the source Observable modified to notify observers of a {@code TimeoutException} in case of a * timeout * @see <a href="http://reactivex.io/documentation/operators/timeout.html">ReactiveX operators documentation: Timeout</a> */ public final Observable<T> timeout(long timeout, TimeUnit timeUnit, Scheduler scheduler) { return timeout(timeout, timeUnit, null, scheduler); } /** * Returns an Observable that emits each item emitted by the source Observable, wrapped in a * {@link Timestamped} object. * <p> * <img width="640" height="310" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/timestamp.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code timestamp} operates by default on the {@code immediate} {@link Scheduler}.</dd> * </dl> * * @return an Observable that emits timestamped items from the source Observable * @see <a href="http://reactivex.io/documentation/operators/timestamp.html">ReactiveX operators documentation: Timestamp</a> */ public final Observable<Timestamped<T>> timestamp() { return timestamp(Schedulers.immediate()); } /** * Returns an Observable that emits each item emitted by the source Observable, wrapped in a * {@link Timestamped} object whose timestamps are provided by a specified Scheduler. * <p> * <img width="640" height="310" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/timestamp.s.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>you specify which {@link Scheduler} this operator will use</dd> * </dl> * * @param scheduler * the {@link Scheduler} to use as a time source * @return an Observable that emits timestamped items from the source Observable with timestamps provided by * the {@code scheduler} * @see <a href="http://reactivex.io/documentation/operators/timestamp.html">ReactiveX operators documentation: Timestamp</a> */ public final Observable<Timestamped<T>> timestamp(Scheduler scheduler) { return lift(new OperatorTimestamp<T>(scheduler)); } /** * Converts an Observable into a {@link BlockingObservable} (an Observable with blocking operators). * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code toBlocking} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @return a {@code BlockingObservable} version of this Observable * @see <a href="http://reactivex.io/documentation/operators/to.html">ReactiveX operators documentation: To</a> */ public final BlockingObservable<T> toBlocking() { return BlockingObservable.from(this); } /** * Returns an Observable that emits a single item, a list composed of all the items emitted by the source * Observable. * <p> * <img width="640" height="305" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/toList.png" alt=""> * <p> * Normally, an Observable that returns multiple items will do so by invoking its {@link Observer}'s * {@link Observer#onNext onNext} method for each such item. You can change this behavior, instructing the * Observable to compose a list of all of these items and then to invoke the Observer's {@code onNext} * function once, passing it the entire list, by calling the Observable's {@code toList} method prior to * calling its {@link #subscribe} method. * <p> * Be careful not to use this operator on Observables that emit infinite or very large numbers of items, as * you do not have the option to unsubscribe. * <dl> * <dt><b>Backpressure Support:</b></dt> * <dd>The operator buffers everything from its upstream but it only emits the aggregated list when the downstream requests at least one item.</dd> * <dt><b>Scheduler:</b></dt> * <dd>{@code toList} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @return an Observable that emits a single item: a List containing all of the items emitted by the source * Observable * @see <a href="http://reactivex.io/documentation/operators/to.html">ReactiveX operators documentation: To</a> */ public final Observable<List<T>> toList() { return lift(OperatorToObservableList.<T>instance()); } /** * Returns an Observable that emits a single HashMap containing all items emitted by the source Observable, * mapped by the keys returned by a specified {@code keySelector} function. * <p> * <img width="640" height="305" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/toMap.png" alt=""> * <p> * If more than one source item maps to the same key, the HashMap will contain the latest of those items. * <dl> * <dt><b>Backpressure Support:</b></dt> * <dd>This operator does not support backpressure as by intent it is requesting and buffering everything.</dd> * <dt><b>Scheduler:</b></dt> * <dd>{@code toMap} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param keySelector * the function that extracts the key from a source item to be used in the HashMap * @return an Observable that emits a single item: a HashMap containing the mapped items from the source * Observable * @see <a href="http://reactivex.io/documentation/operators/to.html">ReactiveX operators documentation: To</a> */ public final <K> Observable<Map<K, T>> toMap(Func1<? super T, ? extends K> keySelector) { return lift(new OperatorToMap<T, K, T>(keySelector, UtilityFunctions.<T>identity())); } /** * Returns an Observable that emits a single HashMap containing values corresponding to items emitted by the * source Observable, mapped by the keys returned by a specified {@code keySelector} function. * <p> * <img width="640" height="305" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/toMap.png" alt=""> * <p> * If more than one source item maps to the same key, the HashMap will contain a single entry that * corresponds to the latest of those items. * <dl> * <dt><b>Backpressure Support:</b></dt> * <dd>This operator does not support backpressure as by intent it is requesting and buffering everything.</dd> * <dt><b>Scheduler:</b></dt> * <dd>{@code toMap} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param keySelector * the function that extracts the key from a source item to be used in the HashMap * @param valueSelector * the function that extracts the value from a source item to be used in the HashMap * @return an Observable that emits a single item: a HashMap containing the mapped items from the source * Observable * @see <a href="http://reactivex.io/documentation/operators/to.html">ReactiveX operators documentation: To</a> */ public final <K, V> Observable<Map<K, V>> toMap(Func1<? super T, ? extends K> keySelector, Func1<? super T, ? extends V> valueSelector) { return lift(new OperatorToMap<T, K, V>(keySelector, valueSelector)); } /** * Returns an Observable that emits a single Map, returned by a specified {@code mapFactory} function, that * contains keys and values extracted from the items emitted by the source Observable. * <p> * <img width="640" height="305" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/toMap.png" alt=""> * <dl> * <dt><b>Backpressure Support:</b></dt> * <dd>This operator does not support backpressure as by intent it is requesting and buffering everything.</dd> * <dt><b>Scheduler:</b></dt> * <dd>{@code toMap} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param keySelector * the function that extracts the key from a source item to be used in the Map * @param valueSelector * the function that extracts the value from the source items to be used as value in the Map * @param mapFactory * the function that returns a Map instance to be used * @return an Observable that emits a single item: a Map that contains the mapped items emitted by the * source Observable * @see <a href="http://reactivex.io/documentation/operators/to.html">ReactiveX operators documentation: To</a> */ public final <K, V> Observable<Map<K, V>> toMap(Func1<? super T, ? extends K> keySelector, Func1<? super T, ? extends V> valueSelector, Func0<? extends Map<K, V>> mapFactory) { return lift(new OperatorToMap<T, K, V>(keySelector, valueSelector, mapFactory)); } /** * Returns an Observable that emits a single HashMap that contains an ArrayList of items emitted by the * source Observable keyed by a specified {@code keySelector} function. * <p> * <img width="640" height="305" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/toMultiMap.png" alt=""> * <dl> * <dt><b>Backpressure Support:</b></dt> * <dd>This operator does not support backpressure as by intent it is requesting and buffering everything.</dd> * <dt><b>Scheduler:</b></dt> * <dd>{@code toMultiMap} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param keySelector * the function that extracts the key from the source items to be used as key in the HashMap * @return an Observable that emits a single item: a HashMap that contains an ArrayList of items mapped from * the source Observable * @see <a href="http://reactivex.io/documentation/operators/to.html">ReactiveX operators documentation: To</a> */ public final <K> Observable<Map<K, Collection<T>>> toMultimap(Func1<? super T, ? extends K> keySelector) { return lift(new OperatorToMultimap<T, K, T>(keySelector, UtilityFunctions.<T>identity())); } /** * Returns an Observable that emits a single HashMap that contains an ArrayList of values extracted by a * specified {@code valueSelector} function from items emitted by the source Observable, keyed by a * specified {@code keySelector} function. * <p> * <img width="640" height="305" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/toMultiMap.png" alt=""> * <dl> * <dt><b>Backpressure Support:</b></dt> * <dd>This operator does not support backpressure as by intent it is requesting and buffering everything.</dd> * <dt><b>Scheduler:</b></dt> * <dd>{@code toMultiMap} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param keySelector * the function that extracts a key from the source items to be used as key in the HashMap * @param valueSelector * the function that extracts a value from the source items to be used as value in the HashMap * @return an Observable that emits a single item: a HashMap that contains an ArrayList of items mapped from * the source Observable * @see <a href="http://reactivex.io/documentation/operators/to.html">ReactiveX operators documentation: To</a> */ public final <K, V> Observable<Map<K, Collection<V>>> toMultimap(Func1<? super T, ? extends K> keySelector, Func1<? super T, ? extends V> valueSelector) { return lift(new OperatorToMultimap<T, K, V>(keySelector, valueSelector)); } /** * Returns an Observable that emits a single Map, returned by a specified {@code mapFactory} function, that * contains an ArrayList of values, extracted by a specified {@code valueSelector} function from items * emitted by the source Observable and keyed by the {@code keySelector} function. * <p> * <img width="640" height="305" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/toMultiMap.png" alt=""> * <dl> * <dt><b>Backpressure Support:</b></dt> * <dd>This operator does not support backpressure as by intent it is requesting and buffering everything.</dd> * <dt><b>Scheduler:</b></dt> * <dd>{@code toMultiMap} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param keySelector * the function that extracts a key from the source items to be used as the key in the Map * @param valueSelector * the function that extracts a value from the source items to be used as the value in the Map * @param mapFactory * the function that returns a Map instance to be used * @return an Observable that emits a single item: a Map that contains a list items mapped from the source * Observable * @see <a href="http://reactivex.io/documentation/operators/to.html">ReactiveX operators documentation: To</a> */ public final <K, V> Observable<Map<K, Collection<V>>> toMultimap(Func1<? super T, ? extends K> keySelector, Func1<? super T, ? extends V> valueSelector, Func0<? extends Map<K, Collection<V>>> mapFactory) { return lift(new OperatorToMultimap<T, K, V>(keySelector, valueSelector, mapFactory)); } /** * Returns an Observable that emits a single Map, returned by a specified {@code mapFactory} function, that * contains a custom collection of values, extracted by a specified {@code valueSelector} function from * items emitted by the source Observable, and keyed by the {@code keySelector} function. * <p> * <img width="640" height="305" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/toMultiMap.png" alt=""> * <dl> * <dt><b>Backpressure Support:</b></dt> * <dd>This operator does not support backpressure as by intent it is requesting and buffering everything.</dd> * <dt><b>Scheduler:</b></dt> * <dd>{@code toMultiMap} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param keySelector * the function that extracts a key from the source items to be used as the key in the Map * @param valueSelector * the function that extracts a value from the source items to be used as the value in the Map * @param mapFactory * the function that returns a Map instance to be used * @param collectionFactory * the function that returns a Collection instance for a particular key to be used in the Map * @return an Observable that emits a single item: a Map that contains the collection of mapped items from * the source Observable * @see <a href="http://reactivex.io/documentation/operators/to.html">ReactiveX operators documentation: To</a> */ public final <K, V> Observable<Map<K, Collection<V>>> toMultimap(Func1<? super T, ? extends K> keySelector, Func1<? super T, ? extends V> valueSelector, Func0<? extends Map<K, Collection<V>>> mapFactory, Func1<? super K, ? extends Collection<V>> collectionFactory) { return lift(new OperatorToMultimap<T, K, V>(keySelector, valueSelector, mapFactory, collectionFactory)); } /** * Returns an Observable that emits a list that contains the items emitted by the source Observable, in a * sorted order. Each item emitted by the Observable must implement {@link Comparable} with respect to all * other items in the sequence. * <p> * <img width="640" height="310" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/toSortedList.png" alt=""> * <dl> * <dt><b>Backpressure Support:</b></dt> * <dd>The operator buffers everything from its upstream but it only emits the sorted list when the downstream requests at least one item.</dd> * <dt><b>Scheduler:</b></dt> * <dd>{@code toSortedList} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @throws ClassCastException * if any item emitted by the Observable does not implement {@link Comparable} with respect to * all other items emitted by the Observable * @return an Observable that emits a list that contains the items emitted by the source Observable in * sorted order * @see <a href="http://reactivex.io/documentation/operators/to.html">ReactiveX operators documentation: To</a> */ public final Observable<List<T>> toSortedList() { return lift(new OperatorToObservableSortedList<T>(10)); } /** * Returns an Observable that emits a list that contains the items emitted by the source Observable, in a * sorted order based on a specified comparison function. * <p> * <img width="640" height="310" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/toSortedList.f.png" alt=""> * <dl> * <dt><b>Backpressure Support:</b></dt> * <dd>The operator buffers everything from its upstream but it only emits the sorted list when the downstream requests at least one item.</dd> * <dt><b>Scheduler:</b></dt> * <dd>{@code toSortedList} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param sortFunction * a function that compares two items emitted by the source Observable and returns an Integer * that indicates their sort order * @return an Observable that emits a list that contains the items emitted by the source Observable in * sorted order * @see <a href="http://reactivex.io/documentation/operators/to.html">ReactiveX operators documentation: To</a> */ public final Observable<List<T>> toSortedList(Func2<? super T, ? super T, Integer> sortFunction) { return lift(new OperatorToObservableSortedList<T>(sortFunction, 10)); } /** * Returns an Observable that emits a list that contains the items emitted by the source Observable, in a * sorted order. Each item emitted by the Observable must implement {@link Comparable} with respect to all * other items in the sequence. * <p> * <img width="640" height="310" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/toSortedList.png" alt=""> * <dl> * <dt><b>Backpressure Support:</b></dt> * <dd>The operator buffers everything from its upstream but it only emits the sorted list when the downstream requests at least one item.</dd> * <dt><b>Scheduler:</b></dt> * <dd>{@code toSortedList} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @throws ClassCastException * if any item emitted by the Observable does not implement {@link Comparable} with respect to * all other items emitted by the Observable * @param initialCapacity * the initial capacity of the ArrayList used to accumulate items before sorting * @return an Observable that emits a list that contains the items emitted by the source Observable in * sorted order * @see <a href="http://reactivex.io/documentation/operators/to.html">ReactiveX operators documentation: To</a> * @since (if this graduates from Experimental/Beta to supported, replace this parenthetical with the release number) */ @Experimental public final Observable<List<T>> toSortedList(int initialCapacity) { return lift(new OperatorToObservableSortedList<T>(initialCapacity)); } /** * Returns an Observable that emits a list that contains the items emitted by the source Observable, in a * sorted order based on a specified comparison function. * <p> * <img width="640" height="310" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/toSortedList.f.png" alt=""> * <dl> * <dt><b>Backpressure Support:</b></dt> * <dd>The operator buffers everything from its upstream but it only emits the sorted list when the downstream requests at least one item.</dd> * <dt><b>Scheduler:</b></dt> * <dd>{@code toSortedList} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param sortFunction * a function that compares two items emitted by the source Observable and returns an Integer * that indicates their sort order * @param initialCapacity * the initial capacity of the ArrayList used to accumulate items before sorting * @return an Observable that emits a list that contains the items emitted by the source Observable in * sorted order * @see <a href="http://reactivex.io/documentation/operators/to.html">ReactiveX operators documentation: To</a> * @since (if this graduates from Experimental/Beta to supported, replace this parenthetical with the release number) */ @Experimental public final Observable<List<T>> toSortedList(Func2<? super T, ? super T, Integer> sortFunction, int initialCapacity) { return lift(new OperatorToObservableSortedList<T>(sortFunction, initialCapacity)); } /** * Modifies the source Observable so that subscribers will unsubscribe from it on a specified * {@link Scheduler}. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>you specify which {@link Scheduler} this operator will use</dd> * </dl> * * @param scheduler * the {@link Scheduler} to perform unsubscription actions on * @return the source Observable modified so that its unsubscriptions happen on the specified * {@link Scheduler} * @see <a href="http://reactivex.io/documentation/operators/subscribeon.html">ReactiveX operators documentation: SubscribeOn</a> */ public final Observable<T> unsubscribeOn(Scheduler scheduler) { return lift(new OperatorUnsubscribeOn<T>(scheduler)); } /** * Merges the specified Observable into this Observable sequence by using the {@code resultSelector} * function only when the source Observable (this instance) emits an item. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/withLatestFrom.png" alt=""> * * @warn "Backpressure Support" section missing from javadoc * @warn "Scheduler" section missing from javadoc * @param other * the other Observable * @param resultSelector * the function to call when this Observable emits an item and the other Observable has already * emitted an item, to generate the item to be emitted by the resulting Observable * @return an Observable that merges the specified Observable into this Observable by using the * {@code resultSelector} function only when the source Observable sequence (this instance) emits an * item * @Experimental The behavior of this can change at any time. * @since (if this graduates from Experimental/Beta to supported, replace this parenthetical with the release number) * @see <a href="http://reactivex.io/documentation/operators/combinelatest.html">ReactiveX operators documentation: CombineLatest</a> */ @Experimental public final <U, R> Observable<R> withLatestFrom(Observable<? extends U> other, Func2<? super T, ? super U, ? extends R> resultSelector) { return lift(new OperatorWithLatestFrom<T, U, R>(other, resultSelector)); } /** * Returns an Observable that emits windows of items it collects from the source Observable. The resulting * Observable emits connected, non-overlapping windows. It emits the current window and opens a new one * whenever the Observable produced by the specified {@code closingSelector} emits an item. * <p> * <img width="640" height="460" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/window1.png" alt=""> * <dl> * <dt><b>Backpressure Support:</b></dt> * <dd>This operator does not support backpressure as it uses the {@code closingSelector} to control data * flow.</dd> * <dt><b>Scheduler:</b></dt> * <dd>This version of {@code window} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param closingSelector * a {@link Func0} that returns an {@code Observable} that governs the boundary between windows. * When this {@code Observable} emits an item, {@code window} emits the current window and begins * a new one. * @return an Observable that emits connected, non-overlapping windows of items from the source Observable * whenever {@code closingSelector} emits an item * @see <a href="http://reactivex.io/documentation/operators/window.html">ReactiveX operators documentation: Window</a> */ public final <TClosing> Observable<Observable<T>> window(Func0<? extends Observable<? extends TClosing>> closingSelector) { return lift(new OperatorWindowWithObservableFactory<T, TClosing>(closingSelector)); } /** * Returns an Observable that emits windows of items it collects from the source Observable. The resulting * Observable emits connected, non-overlapping windows, each containing {@code count} items. When the source * Observable completes or encounters an error, the resulting Observable emits the current window and * propagates the notification from the source Observable. * <p> * <img width="640" height="400" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/window3.png" alt=""> * <dl> * <dt><b>Backpressure Support:</b></dt> * <dd>The operator honors backpressure on its outer subscriber, ignores backpressure in its inner Observables * but each of them will emit at most {@code count} elements.</dd> * <dt><b>Scheduler:</b></dt> * <dd>This version of {@code window} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param count * the maximum size of each window before it should be emitted * @return an Observable that emits connected, non-overlapping windows, each containing at most * {@code count} items from the source Observable * @see <a href="http://reactivex.io/documentation/operators/window.html">ReactiveX operators documentation: Window</a> */ public final Observable<Observable<T>> window(int count) { return window(count, count); } /** * Returns an Observable that emits windows of items it collects from the source Observable. The resulting * Observable emits windows every {@code skip} items, each containing no more than {@code count} items. When * the source Observable completes or encounters an error, the resulting Observable emits the current window * and propagates the notification from the source Observable. * <p> * <img width="640" height="365" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/window4.png" alt=""> * <dl> * <dt><b>Backpressure Support:</b></dt> * <dd>The operator honors backpressure on its outer subscriber, ignores backpressure in its inner Observables * but each of them will emit at most {@code count} elements.</dd> * <dt><b>Scheduler:</b></dt> * <dd>This version of {@code window} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param count * the maximum size of each window before it should be emitted * @param skip * how many items need to be skipped before starting a new window. Note that if {@code skip} and * {@code count} are equal this is the same operation as {@link #window(int)}. * @return an Observable that emits windows every {@code skip} items containing at most {@code count} items * from the source Observable * @see <a href="http://reactivex.io/documentation/operators/window.html">ReactiveX operators documentation: Window</a> */ public final Observable<Observable<T>> window(int count, int skip) { return lift(new OperatorWindowWithSize<T>(count, skip)); } /** * Returns an Observable that emits windows of items it collects from the source Observable. The resulting * Observable starts a new window periodically, as determined by the {@code timeshift} argument. It emits * each window after a fixed timespan, specified by the {@code timespan} argument. When the source * Observable completes or Observable completes or encounters an error, the resulting Observable emits the * current window and propagates the notification from the source Observable. * <p> * <img width="640" height="335" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/window7.png" alt=""> * <dl> * <dt><b>Backpressure Support:</b></dt> * <dd>This operator does not support backpressure as it uses time to control data flow.</dd> * <dt><b>Scheduler:</b></dt> * <dd>This version of {@code window} operates by default on the {@code computation} {@link Scheduler}.</dd> * </dl> * * @param timespan * the period of time each window collects items before it should be emitted * @param timeshift * the period of time after which a new window will be created * @param unit * the unit of time that applies to the {@code timespan} and {@code timeshift} arguments * @return an Observable that emits new windows periodically as a fixed timespan elapses * @see <a href="http://reactivex.io/documentation/operators/window.html">ReactiveX operators documentation: Window</a> */ public final Observable<Observable<T>> window(long timespan, long timeshift, TimeUnit unit) { return window(timespan, timeshift, unit, Integer.MAX_VALUE, Schedulers.computation()); } /** * Returns an Observable that emits windows of items it collects from the source Observable. The resulting * Observable starts a new window periodically, as determined by the {@code timeshift} argument. It emits * each window after a fixed timespan, specified by the {@code timespan} argument. When the source * Observable completes or Observable completes or encounters an error, the resulting Observable emits the * current window and propagates the notification from the source Observable. * <p> * <img width="640" height="335" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/window7.s.png" alt=""> * <dl> * <dt><b>Backpressure Support:</b></dt> * <dd>This operator does not support backpressure as it uses time to control data flow.</dd> * <dt><b>Scheduler:</b></dt> * <dd>you specify which {@link Scheduler} this operator will use</dd> * </dl> * * @param timespan * the period of time each window collects items before it should be emitted * @param timeshift * the period of time after which a new window will be created * @param unit * the unit of time that applies to the {@code timespan} and {@code timeshift} arguments * @param scheduler * the {@link Scheduler} to use when determining the end and start of a window * @return an Observable that emits new windows periodically as a fixed timespan elapses * @see <a href="http://reactivex.io/documentation/operators/window.html">ReactiveX operators documentation: Window</a> */ public final Observable<Observable<T>> window(long timespan, long timeshift, TimeUnit unit, Scheduler scheduler) { return window(timespan, timeshift, unit, Integer.MAX_VALUE, scheduler); } /** * Returns an Observable that emits windows of items it collects from the source Observable. The resulting * Observable starts a new window periodically, as determined by the {@code timeshift} argument or a maximum * size as specified by the {@code count} argument (whichever is reached first). It emits * each window after a fixed timespan, specified by the {@code timespan} argument. When the source * Observable completes or Observable completes or encounters an error, the resulting Observable emits the * current window and propagates the notification from the source Observable. * <p> * <img width="640" height="335" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/window7.s.png" alt=""> * <dl> * <dt><b>Backpressure Support:</b></dt> * <dd>This operator does not support backpressure as it uses time to control data flow.</dd> * <dt><b>Scheduler:</b></dt> * <dd>you specify which {@link Scheduler} this operator will use</dd> * </dl> * * @param timespan * the period of time each window collects items before it should be emitted * @param timeshift * the period of time after which a new window will be created * @param unit * the unit of time that applies to the {@code timespan} and {@code timeshift} arguments * @param count * the maximum size of each window before it should be emitted * @param scheduler * the {@link Scheduler} to use when determining the end and start of a window * @return an Observable that emits new windows periodically as a fixed timespan elapses * @see <a href="http://reactivex.io/documentation/operators/window.html">ReactiveX operators documentation: Window</a> */ public final Observable<Observable<T>> window(long timespan, long timeshift, TimeUnit unit, int count, Scheduler scheduler) { return lift(new OperatorWindowWithTime<T>(timespan, timeshift, unit, count, scheduler)); } /** * Returns an Observable that emits windows of items it collects from the source Observable. The resulting * Observable emits connected, non-overlapping windows, each of a fixed duration specified by the * {@code timespan} argument. When the source Observable completes or encounters an error, the resulting * Observable emits the current window and propagates the notification from the source Observable. * <p> * <img width="640" height="375" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/window5.png" alt=""> * <dl> * <dt><b>Backpressure Support:</b></dt> * <dd>This operator does not support backpressure as it uses time to control data flow.</dd> * <dt><b>Scheduler:</b></dt> * <dd>This version of {@code window} operates by default on the {@code computation} {@link Scheduler}.</dd> * </dl> * * @param timespan * the period of time each window collects items before it should be emitted and replaced with a * new window * @param unit * the unit of time that applies to the {@code timespan} argument * @return an Observable that emits connected, non-overlapping windows represending items emitted by the * source Observable during fixed, consecutive durations * @see <a href="http://reactivex.io/documentation/operators/window.html">ReactiveX operators documentation: Window</a> */ public final Observable<Observable<T>> window(long timespan, TimeUnit unit) { return window(timespan, timespan, unit, Schedulers.computation()); } /** * Returns an Observable that emits windows of items it collects from the source Observable. The resulting * Observable emits connected, non-overlapping windows, each of a fixed duration as specified by the * {@code timespan} argument or a maximum size as specified by the {@code count} argument (whichever is * reached first). When the source Observable completes or encounters an error, the resulting Observable * emits the current window and propagates the notification from the source Observable. * <p> * <img width="640" height="370" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/window6.png" alt=""> * <dl> * <dt><b>Backpressure Support:</b></dt> * <dd>This operator does not support backpressure as it uses time to control data flow.</dd> * <dt><b>Scheduler:</b></dt> * <dd>This version of {@code window} operates by default on the {@code computation} {@link Scheduler}.</dd> * </dl> * * @param timespan * the period of time each window collects items before it should be emitted and replaced with a * new window * @param unit * the unit of time that applies to the {@code timespan} argument * @param count * the maximum size of each window before it should be emitted * @return an Observable that emits connected, non-overlapping windows of items from the source Observable * that were emitted during a fixed duration of time or when the window has reached maximum capacity * (whichever occurs first) * @see <a href="http://reactivex.io/documentation/operators/window.html">ReactiveX operators documentation: Window</a> */ public final Observable<Observable<T>> window(long timespan, TimeUnit unit, int count) { return window(timespan, unit, count, Schedulers.computation()); } /** * Returns an Observable that emits windows of items it collects from the source Observable. The resulting * Observable emits connected, non-overlapping windows, 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 source Observable completes or encounters an error, the resulting Observable emits the * current window and propagates the notification from the source Observable. * <p> * <img width="640" height="370" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/window6.s.png" alt=""> * <dl> * <dt><b>Backpressure Support:</b></dt> * <dd>This operator does not support backpressure as it uses time to control data flow.</dd> * <dt><b>Scheduler:</b></dt> * <dd>you specify which {@link Scheduler} this operator will use</dd> * </dl> * * @param timespan * the period of time each window collects items before it should be emitted and replaced with a * new window * @param unit * the unit of time which applies to the {@code timespan} argument * @param count * the maximum size of each window before it should be emitted * @param scheduler * the {@link Scheduler} to use when determining the end and start of a window * @return an Observable that emits connected, non-overlapping windows of items from the source Observable * that were emitted during a fixed duration of time or when the window has reached maximum capacity * (whichever occurs first) * @see <a href="http://reactivex.io/documentation/operators/window.html">ReactiveX operators documentation: Window</a> */ public final Observable<Observable<T>> window(long timespan, TimeUnit unit, int count, Scheduler scheduler) { return window(timespan, timespan, unit, count, scheduler); } /** * Returns an Observable that emits windows of items it collects from the source Observable. The resulting * Observable emits connected, non-overlapping windows, each of a fixed duration as specified by the * {@code timespan} argument. When the source Observable completes or encounters an error, the resulting * Observable emits the current window and propagates the notification from the source Observable. * <p> * <img width="640" height="375" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/window5.s.png" alt=""> * <dl> * <dt><b>Backpressure Support:</b></dt> * <dd>This operator does not support backpressure as it uses time to control data flow.</dd> * <dt><b>Scheduler:</b></dt> * <dd>you specify which {@link Scheduler} this operator will use</dd> * </dl> * * @param timespan * the period of time each window collects items before it should be emitted and replaced with a * new window * @param unit * the unit of time which applies to the {@code timespan} argument * @param scheduler * the {@link Scheduler} to use when determining the end and start of a window * @return an Observable that emits connected, non-overlapping windows containing items emitted by the * source Observable within a fixed duration * @see <a href="http://reactivex.io/documentation/operators/window.html">ReactiveX operators documentation: Window</a> */ public final Observable<Observable<T>> window(long timespan, TimeUnit unit, Scheduler scheduler) { return window(timespan, unit, Integer.MAX_VALUE, scheduler); } /** * Returns an Observable that emits windows of items it collects from the source Observable. The resulting * Observable emits windows that contain those items emitted by the source Observable between the time when * the {@code windowOpenings} Observable emits an item and when the Observable returned by * {@code closingSelector} emits an item. * <p> * <img width="640" height="550" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/window2.png" alt=""> * <dl> * <dt><b>Backpressure Support:</b></dt> * <dd>This operator does not support backpressure as it uses Observables to control data flow.</dd> * <dt><b>Scheduler:</b></dt> * <dd>This version of {@code window} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param windowOpenings * an Observable that, when it emits an item, causes another window to be created * @param closingSelector * a {@link Func1} that produces an Observable for every window created. When this Observable * emits an item, the associated window is closed and emitted * @return an Observable that emits windows of items emitted by the source Observable that are governed by * the specified window-governing Observables * @see <a href="http://reactivex.io/documentation/operators/window.html">ReactiveX operators documentation: Window</a> */ public final <TOpening, TClosing> Observable<Observable<T>> window(Observable<? extends TOpening> windowOpenings, Func1<? super TOpening, ? extends Observable<? extends TClosing>> closingSelector) { return lift(new OperatorWindowWithStartEndObservable<T, TOpening, TClosing>(windowOpenings, closingSelector)); } /** * Returns an Observable that emits non-overlapping windows of items it collects from the source Observable * where the boundary of each window is determined by the items emitted from a specified boundary-governing * Observable. * <p> * <img width="640" height="475" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/window8.png" alt=""> * <dl> * <dt><b>Backpressure Support:</b></dt> * <dd>This operator does not support backpressure as it uses a {@code boundary} Observable to control data * flow.</dd> * <dt><b>Scheduler:</b></dt> * <dd>This version of {@code window} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param <U> * the window element type (ignored) * @param boundary * an Observable whose emitted items close and open windows * @return an Observable that emits non-overlapping windows of items it collects from the source Observable * where the boundary of each window is determined by the items emitted from the {@code boundary} * Observable * @see <a href="http://reactivex.io/documentation/operators/window.html">ReactiveX operators documentation: Window</a> */ public final <U> Observable<Observable<T>> window(Observable<U> boundary) { return lift(new OperatorWindowWithObservable<T, U>(boundary)); } /** * Returns an Observable that emits items that are the result of applying a specified function to pairs of * values, one each from the source Observable and a specified Iterable sequence. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/zip.i.png" alt=""> * <p> * Note that the {@code other} Iterable is evaluated as items are observed from the source Observable; it is * not pre-consumed. This allows you to zip infinite streams on either side. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code zipWith} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param <T2> * the type of items in the {@code other} Iterable * @param <R> * the type of items emitted by the resulting Observable * @param other * the Iterable sequence * @param zipFunction * a function that combines the pairs of items from the Observable and the Iterable to generate * the items to be emitted by the resulting Observable * @return an Observable that pairs up values from the source Observable and the {@code other} Iterable * sequence and emits the results of {@code zipFunction} applied to these pairs * @see <a href="http://reactivex.io/documentation/operators/zip.html">ReactiveX operators documentation: Zip</a> */ public final <T2, R> Observable<R> zipWith(Iterable<? extends T2> other, Func2<? super T, ? super T2, ? extends R> zipFunction) { return lift(new OperatorZipIterable<T, T2, R>(other, zipFunction)); } /** * Returns an Observable that emits items that are the result of applying a specified function to pairs of * values, one each from the source Observable and another specified Observable. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/zip.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code zipWith} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param <T2> * the type of items emitted by the {@code other} Observable * @param <R> * the type of items emitted by the resulting Observable * @param other * the other Observable * @param zipFunction * a function that combines the pairs of items from the two Observables to generate the items to * be emitted by the resulting Observable * @return an Observable that pairs up values from the source Observable and the {@code other} Observable * and emits the results of {@code zipFunction} applied to these pairs * @see <a href="http://reactivex.io/documentation/operators/zip.html">ReactiveX operators documentation: Zip</a> */ public final <T2, R> Observable<R> zipWith(Observable<? extends T2> other, Func2<? super T, ? super T2, ? extends R> zipFunction) { return zip(this, other, zipFunction); } /** * An Observable that never sends any information to an {@link Observer}. * This Observable is useful primarily for testing purposes. * * @param <T> * the type of item (not) emitted by the Observable */ private static class NeverObservable<T> extends Observable<T> { private static class Holder { static final NeverObservable<?> INSTANCE = new NeverObservable<Object>(); } /** * Returns a singleton instance of NeverObservble (cast to the generic type). * * @return */ @SuppressWarnings("unchecked") static <T> NeverObservable<T> instance() { return (NeverObservable<T>) Holder.INSTANCE; } NeverObservable() { super(new OnSubscribe<T>() { @Override public void call(Subscriber<? super T> observer) { // do nothing } }); } } /** * An Observable that invokes {@link Observer#onError onError} when the {@link Observer} subscribes to it. * * @param <T> * the type of item (ostensibly) emitted by the Observable */ private static class ThrowObservable<T> extends Observable<T> { public ThrowObservable(final Throwable exception) { super(new OnSubscribe<T>() { /** * Accepts an {@link Observer} and calls its {@link Observer#onError onError} method. * * @param observer * an {@link Observer} of this Observable */ @Override public void call(Subscriber<? super T> observer) { observer.onError(exception); } }); } } }
apache-2.0
ArnoHeid/PubApp
poi/src/main/java/de/hsmainz/pubapp/poi/model/googleapi/GoogleOpeningHours.java
360
package de.hsmainz.pubapp.poi.model.googleapi; /** * Represents a places information whether its open or not returned by Google * Places API * * @author caro * */ public class GoogleOpeningHours { private Boolean openNow; public Boolean getOpenNow() { return openNow; } public void setOpenNow(Boolean openNow) { this.openNow = openNow; } }
apache-2.0
qynnine/ode-qyn
jbi/src/main/java/org/apache/ode/jbi/OdeServiceUnit.java
6386
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.ode.jbi; import java.io.File; import java.io.FilenameFilter; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import java.util.ArrayList; import java.util.Collection; import java.util.List; import javax.jbi.management.DeploymentException; import javax.xml.namespace.QName; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * Representation of a JBI service unit. A JBI service unit may actually consist * of multiple processes. */ class OdeServiceUnit { private static final Log __log = LogFactory.getLog(OdeServiceUnit.class); private static final Messages __msgs = Messages.getMessages(Messages.class); /** The ever-present context. */ private OdeContext _ode; /** Our own directory managed by JBI */ private File _serviceUnitRootPath; /** Our JBI indentifier. */ private String _serviceUnitID; private Collection<QName> _registered = new ArrayList<QName>(); private static final String LIB_DIR = "lib"; /** Ctor. */ OdeServiceUnit(OdeContext ode, String serviceUnitID, String serviceUnitRootPath) { _ode = ode; _serviceUnitID = serviceUnitID; _serviceUnitRootPath = new File(serviceUnitRootPath); } public void deploy() throws DeploymentException { ClassLoader cl = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader(getConfigurationClassLoader()); // JBI ServiceUnits don't use autoincrement version, // because in ServiceMix redeploying component yields to redeploying dependent // ServiceUnits, and we don't want to create new processes versions // on such redeployments _ode._store.deploy(_serviceUnitRootPath, false); } catch (Exception ex) { String errmsg = __msgs.msgOdeProcessDeploymentFailed(_serviceUnitRootPath, _serviceUnitID); __log.error(errmsg, ex); throw new DeploymentException(errmsg, ex); } finally { Thread.currentThread().setContextClassLoader(cl); } } public void undeploy() throws Exception { try { Collection<QName> undeployed = _ode._store.undeploy(_serviceUnitRootPath); for (QName pqname : undeployed) { _ode._server.unregister(pqname); } } catch (Exception ex) { String errmsg = __msgs.msgOdeProcessUndeploymentFailed(null); __log.error(errmsg, ex); throw new DeploymentException(errmsg, ex); } } public void init() throws Exception { // TODO Auto-generated method stub } public void shutdown() throws Exception { // TODO Auto-generated method stub } public void start() throws Exception { List<QName> pids = _ode._store.listProcesses(_serviceUnitRootPath.getName()); if (pids == null) { __log.error(_serviceUnitRootPath.getName() + " not found in process store. "); throw new IllegalStateException("Process store and JBI out of synch."); } Exception e = null; for (QName pid : pids) { try { _ode._server.register(_ode._store.getProcessConfiguration(pid)); _registered.add(pid); } catch (Exception ex) { e = ex; __log.error("Unable to load " + pid, ex); break; } } if (_registered.size() != pids.size()) { for (QName pid : new ArrayList<QName>(_registered)) try { _ode._server.unregister(pid); _registered.remove(pid); } catch (Exception ex) { __log.error("Unable to unload " + pid, ex); } } if (e != null) throw e; } public void stop() throws Exception { for (QName pid : new ArrayList<QName>(_registered)) { try { _ode._server.unregister(pid); _registered.remove(pid); } catch (Exception ex) { __log.error("Unable to unload " + pid, ex); } } } public ClassLoader getConfigurationClassLoader() throws DeploymentException { return new URLClassLoader(getDefaultLocations(), getClass().getClassLoader()); } protected URL[] getDefaultLocations() throws DeploymentException { try { File[] jars = new File(_serviceUnitRootPath, LIB_DIR).listFiles(new FilenameFilter() { public boolean accept(File dir, String name) { name = name.toLowerCase(); return name.endsWith(".jar") || name.endsWith(".zip"); } }); URL[] urls = new URL[jars != null ? jars.length + 1 : 1]; urls[0] = _serviceUnitRootPath.toURI().toURL(); if (jars != null) { for (int i = 0; i < jars.length; i++) { urls[i + 1] = jars[i].toURI().toURL(); } } if (__log.isDebugEnabled()) { for (URL u : urls) { __log.debug("in classpath for "+_serviceUnitID+" using url: "+u); } } return urls; } catch (MalformedURLException e) { throw new DeploymentException("Unable to get default classpath locations", e); } } }
apache-2.0
chaoli314/otbn
tests/io/HuginNetFormatTest.java
2390
package io; import bayesian_network.BayesianNetwork; import bayesian_network.Node; import org.junit.After; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertEquals; /** * Created by chaoli on 10/22/16. */ public class HuginNetFormatTest { BayesianNetwork bn_; String file_name_; @Before public void setUp() throws Exception { bn_ = new BayesianNetwork(); } @After public void tearDown() throws Exception { bn_ = null; file_name_ = null; } @Test public void read() throws Exception { file_name_ = "bnr/bnlearn/asia.net"; bn_ = HuginNetFormat.read(file_name_); /// parse nodes assertEquals(8, bn_.getNumberOfNodes()); int broncIndex = bn_.getNodeIndex("bronc"); assertEquals(4, broncIndex); Node broncNode = bn_.getNodeByIndex(4); assertEquals("yes", broncNode.getStateLabel(0)); assertEquals(1, broncNode.getStateIndex("no")); assertEquals(2, broncNode.getCard()); /// parse CPTs // potential ( asia ){data = ( 0.01 0.99 );} assertEquals(0, bn_.getNodeByName("asia").getParents().size()); assertEquals(2, bn_.getNodeByName("asia").getTable().nrStates()); assertEquals(0.01, bn_.getNodeByName("asia").getTable().get(0), 0.01); assertEquals(0.99, bn_.getNodeByName("asia").getTable().get(1), 0.01); // potential ( either | lung tub ){data = (((1.0 0.0)(1.0 0.0))((1.0 0.0)(0.0 1.0))) ;} assertEquals(2, bn_.getNodeByName("either").getParents().size()); assertEquals(8, bn_.getNodeByName("either").getTable().nrStates()); assertEquals(1.0, bn_.getNodeByName("either").getTable().get(0), 0.01); assertEquals(0.0, bn_.getNodeByName("either").getTable().get(1), 0.01); assertEquals(1.0, bn_.getNodeByName("either").getTable().get(2), 0.01); assertEquals(0.0, bn_.getNodeByName("either").getTable().get(3), 0.01); assertEquals(1.0, bn_.getNodeByName("either").getTable().get(4), 0.01); assertEquals(0.0, bn_.getNodeByName("either").getTable().get(5), 0.01); assertEquals(0.0, bn_.getNodeByName("either").getTable().get(6), 0.01); assertEquals(1.0, bn_.getNodeByName("either").getTable().get(7), 0.01); } @Test public void saveAsNet() throws Exception { } }
apache-2.0
ben-manes/caffeine
caffeine/src/test/java/com/github/benmanes/caffeine/cache/FrequencySketchTest.java
4833
/* * Copyright 2015 Ben Manes. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.benmanes.caffeine.cache; import static com.google.common.truth.Truth.assertThat; import java.util.HashSet; import java.util.concurrent.ThreadLocalRandom; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; /** * @author ben.manes@gmail.com (Ben Manes) */ public final class FrequencySketchTest { final Integer item = ThreadLocalRandom.current().nextInt(); @Test public void construct() { var sketch = new FrequencySketch<Integer>(); assertThat(sketch.table).isNull(); } @Test(dataProvider = "sketch", expectedExceptions = IllegalArgumentException.class) public void ensureCapacity_negative(FrequencySketch<Integer> sketch) { sketch.ensureCapacity(-1); } @Test(dataProvider = "sketch") public void ensureCapacity_smaller(FrequencySketch<Integer> sketch) { int size = sketch.table.length; sketch.ensureCapacity(size / 2); assertThat(sketch.table).hasLength(size); assertThat(sketch.tableMask).isEqualTo(size - 1); assertThat(sketch.sampleSize).isEqualTo(10 * size); } @Test(dataProvider = "sketch") public void ensureCapacity_larger(FrequencySketch<Integer> sketch) { int size = sketch.table.length; sketch.ensureCapacity(2 * size); assertThat(sketch.table).hasLength(2 * size); assertThat(sketch.tableMask).isEqualTo(2 * size - 1); assertThat(sketch.sampleSize).isEqualTo(10 * 2 * size); } @Test(dataProvider = "sketch") public void increment_once(FrequencySketch<Integer> sketch) { sketch.increment(item); assertThat(sketch.frequency(item)).isEqualTo(1); } @Test(dataProvider = "sketch") public void increment_max(FrequencySketch<Integer> sketch) { for (int i = 0; i < 20; i++) { sketch.increment(item); } assertThat(sketch.frequency(item)).isEqualTo(15); } @Test(dataProvider = "sketch") public void increment_distinct(FrequencySketch<Integer> sketch) { sketch.increment(item); sketch.increment(item + 1); assertThat(sketch.frequency(item)).isEqualTo(1); assertThat(sketch.frequency(item + 1)).isEqualTo(1); assertThat(sketch.frequency(item + 2)).isEqualTo(0); } @Test(dataProvider = "sketch") public void indexOf_aroundZero(FrequencySketch<Integer> sketch) { var indexes = new HashSet<Integer>(16); int[] hashes = { -1, 0, 1 }; for (int hash : hashes) { for (int i = 0; i < 4; i++) { indexes.add(sketch.indexOf(hash, i)); } } assertThat(indexes).hasSize(4 * hashes.length); } @Test public void reset() { boolean reset = false; var sketch = new FrequencySketch<Integer>(); sketch.ensureCapacity(64); for (int i = 1; i < 20 * sketch.table.length; i++) { sketch.increment(i); if (sketch.size != i) { reset = true; break; } } assertThat(reset).isTrue(); assertThat(sketch.size).isAtMost(sketch.sampleSize / 2); } @Test public void heavyHitters() { FrequencySketch<Double> sketch = makeSketch(512); for (int i = 100; i < 100_000; i++) { sketch.increment((double) i); } for (int i = 0; i < 10; i += 2) { for (int j = 0; j < i; j++) { sketch.increment((double) i); } } // A perfect popularity count yields an array [0, 0, 2, 0, 4, 0, 6, 0, 8, 0] int[] popularity = new int[10]; for (int i = 0; i < 10; i++) { popularity[i] = sketch.frequency((double) i); } for (int i = 0; i < popularity.length; i++) { if ((i == 0) || (i == 1) || (i == 3) || (i == 5) || (i == 7) || (i == 9)) { assertThat(popularity[i]).isAtMost(popularity[2]); } else if (i == 2) { assertThat(popularity[2]).isAtMost(popularity[4]); } else if (i == 4) { assertThat(popularity[4]).isAtMost(popularity[6]); } else if (i == 6) { assertThat(popularity[6]).isAtMost(popularity[8]); } } } @DataProvider(name = "sketch") public Object[][] providesSketch() { return new Object[][] {{ makeSketch(512) }}; } private static <E> FrequencySketch<E> makeSketch(long maximumSize) { var sketch = new FrequencySketch<E>(); sketch.ensureCapacity(maximumSize); return sketch; } }
apache-2.0
open-telemetry/opentelemetry-java
sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/aggregator/DoubleHistogramAggregator.java
5649
/* * Copyright The OpenTelemetry Authors * SPDX-License-Identifier: Apache-2.0 */ package io.opentelemetry.sdk.metrics.internal.aggregator; import io.opentelemetry.api.common.Attributes; import io.opentelemetry.api.internal.GuardedBy; import io.opentelemetry.sdk.common.InstrumentationLibraryInfo; import io.opentelemetry.sdk.metrics.data.AggregationTemporality; import io.opentelemetry.sdk.metrics.data.ExemplarData; import io.opentelemetry.sdk.metrics.data.MetricData; import io.opentelemetry.sdk.metrics.exemplar.ExemplarReservoir; import io.opentelemetry.sdk.metrics.internal.data.ImmutableHistogramData; import io.opentelemetry.sdk.metrics.internal.descriptor.MetricDescriptor; import io.opentelemetry.sdk.resources.Resource; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.concurrent.locks.ReentrantLock; import java.util.function.Supplier; /** * Aggregator that generates histograms. * * <p>This class is internal and is hence not for public use. Its APIs are unstable and can change * at any time. */ public final class DoubleHistogramAggregator implements Aggregator<HistogramAccumulation> { private final double[] boundaries; // a cache for converting to MetricData private final List<Double> boundaryList; private final Supplier<ExemplarReservoir> reservoirSupplier; /** * Constructs a histogram aggregator. * * @param boundaries Bucket boundaries, in-order. * @param reservoirSupplier Supplier of exemplar reservoirs per-stream. */ public DoubleHistogramAggregator( double[] boundaries, Supplier<ExemplarReservoir> reservoirSupplier) { this.boundaries = boundaries; List<Double> boundaryList = new ArrayList<>(this.boundaries.length); for (double v : this.boundaries) { boundaryList.add(v); } this.boundaryList = Collections.unmodifiableList(boundaryList); this.reservoirSupplier = reservoirSupplier; } @Override public AggregatorHandle<HistogramAccumulation> createHandle() { return new Handle(this.boundaries, reservoirSupplier.get()); } /** * Return the result of the merge of two histogram accumulations. As long as one Aggregator * instance produces all Accumulations with constant boundaries we don't need to worry about * merging accumulations with different boundaries. */ @Override public HistogramAccumulation merge( HistogramAccumulation previous, HistogramAccumulation current) { long[] previousCounts = previous.getCounts(); long[] mergedCounts = new long[previousCounts.length]; for (int i = 0; i < previousCounts.length; ++i) { mergedCounts[i] = previousCounts[i] + current.getCounts()[i]; } return HistogramAccumulation.create( previous.getSum() + current.getSum(), mergedCounts, current.getExemplars()); } @Override public HistogramAccumulation diff(HistogramAccumulation previous, HistogramAccumulation current) { long[] previousCounts = previous.getCounts(); long[] diffedCounts = new long[previousCounts.length]; for (int i = 0; i < previousCounts.length; ++i) { diffedCounts[i] = current.getCounts()[i] - previousCounts[i]; } return HistogramAccumulation.create( current.getSum() - previous.getSum(), diffedCounts, current.getExemplars()); } @Override public MetricData toMetricData( Resource resource, InstrumentationLibraryInfo instrumentationLibraryInfo, MetricDescriptor metricDescriptor, Map<Attributes, HistogramAccumulation> accumulationByLabels, AggregationTemporality temporality, long startEpochNanos, long lastCollectionEpoch, long epochNanos) { return MetricData.createDoubleHistogram( resource, instrumentationLibraryInfo, metricDescriptor.getName(), metricDescriptor.getDescription(), metricDescriptor.getUnit(), ImmutableHistogramData.create( temporality, MetricDataUtils.toDoubleHistogramPointList( accumulationByLabels, (temporality == AggregationTemporality.CUMULATIVE) ? startEpochNanos : lastCollectionEpoch, epochNanos, boundaryList))); } static final class Handle extends AggregatorHandle<HistogramAccumulation> { // read-only private final double[] boundaries; @GuardedBy("lock") private double sum; @GuardedBy("lock") private final long[] counts; private final ReentrantLock lock = new ReentrantLock(); Handle(double[] boundaries, ExemplarReservoir reservoir) { super(reservoir); this.boundaries = boundaries; this.counts = new long[this.boundaries.length + 1]; this.sum = 0; } @Override protected HistogramAccumulation doAccumulateThenReset(List<ExemplarData> exemplars) { lock.lock(); try { HistogramAccumulation acc = HistogramAccumulation.create(sum, Arrays.copyOf(counts, counts.length), exemplars); this.sum = 0; Arrays.fill(this.counts, 0); return acc; } finally { lock.unlock(); } } @Override protected void doRecordDouble(double value) { int bucketIndex = ExplicitBucketHistogramUtils.findBucketIndex(this.boundaries, value); lock.lock(); try { this.sum += value; this.counts[bucketIndex]++; } finally { lock.unlock(); } } @Override protected void doRecordLong(long value) { doRecordDouble((double) value); } } }
apache-2.0
sajithab/identity-inbound-auth-saml-cloud
components/org.wso2.carbon.identity.sso.saml.cloud/src/main/java/org/wso2/carbon/identity/sso/saml/cloud/configs/SalesForceConfigs.java
6752
/* * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.carbon.identity.sso.saml.cloud.configs; import org.wso2.carbon.identity.application.common.model.Property; import org.wso2.carbon.identity.application.mgt.AbstractInboundAuthenticatorConfig; import org.wso2.carbon.identity.base.IdentityConstants; import org.wso2.carbon.identity.base.IdentityException; import org.wso2.carbon.identity.core.util.IdentityUtil; import org.wso2.carbon.identity.sso.saml.cloud.SAMLSSOConstants; public class SalesForceConfigs extends AbstractInboundAuthenticatorConfig { //This is the key @Override public String getAuthKey() { return null; } @Override public String getConfigName() { return "salesforce"; } //this is the authType @Override public String getName() { return SAMLSSOConstants.SAMLFormFields.SAML_SSO; } @Override public String getFriendlyName() { return "Salesforce"; } @Override public Property[] getConfigurationProperties() { Property issuer = new Property(); issuer.setName(SAMLSSOConstants.SAMLFormFields.ISSUER); issuer.setDisplayName("Issuer"); issuer.setValue("https://saml.salesforce.com"); issuer.setDefaultValue("https://saml.salesforce.com"); Property appType = new Property(); appType.setName(IdentityConstants.ServerConfig.WELLKNOWN_APPLICATION_TYPE); appType.setType("hidden"); appType.setValue(getConfigName()); appType.setDisplayName("UI Config Type"); Property acsurls = new Property(); acsurls.setName(SAMLSSOConstants.SAMLFormFields.ACS_URLS); acsurls.setDisplayName("Assertion Consumer URLs"); acsurls.setDescription("The url where you should redirected after authenticated."); Property enableAtrProf = new Property(); enableAtrProf.setName(SAMLSSOConstants.SAMLFormFields.ENABLE_ATTR_PROF); enableAtrProf.setDisplayName("Enable Attribute Profile "); enableAtrProf.setValue("true"); enableAtrProf.setType("hidden"); Property enableDefaultAtrProf = new Property(); enableDefaultAtrProf.setName(SAMLSSOConstants.SAMLFormFields.ENABLE_DEFAULT_ATTR_PROF); enableDefaultAtrProf.setDisplayName("Include Attributes in the Response Always "); enableDefaultAtrProf.setValue("true"); enableDefaultAtrProf.setType("hidden"); Property metadata = new Property(); metadata.setName(SAMLSSOConstants.SAMLFormFields.METADATA); metadata.setDisplayName("Metadata File"); metadata.setType("hidden"); Property acsindex = new Property(); acsindex.setName(SAMLSSOConstants.SAMLFormFields.ACS_INDEX); acsindex.setType("hidden"); acsindex.setDisplayName("Assertion Consumer Service Index"); try { acsindex.setValue(Integer.toString(IdentityUtil.getRandomInteger())); } catch (IdentityException e) { //log.error("Error occurred when generating attribute consumer service index.", e); } Property defaultacs = new Property(); defaultacs.setName(SAMLSSOConstants.SAMLFormFields.DEFAULT_ACS); defaultacs.setDisplayName("Default Assertion Consumer URL"); Property nameid = new Property(); nameid.setName(SAMLSSOConstants.SAMLFormFields.NAME_ID_FORMAT); nameid.setType("hidden"); nameid.setDisplayName("NameID format "); Property certificate = new Property(); certificate.setName(SAMLSSOConstants.SAMLFormFields.PUB_CERT); certificate.setDisplayName("Certificate"); Property alias = new Property(); alias.setName(SAMLSSOConstants.SAMLFormFields.ALIAS); alias.setType("hidden"); alias.setDisplayName("Certificate Alias"); Property signAlgo = new Property(); signAlgo.setName(SAMLSSOConstants.SAMLFormFields.SIGN_ALGO); signAlgo.setType("hidden"); signAlgo.setDisplayName("Response Signing Algorithm "); signAlgo.setValue("http://www.w3.org/2000/09/xmldsig#rsa-sha1"); Property digestAlgo = new Property(); digestAlgo.setName(SAMLSSOConstants.SAMLFormFields.DIGEST_ALGO); digestAlgo.setType("hidden"); digestAlgo.setDisplayName("Response Digest Algorithm "); digestAlgo.setValue("http://www.w3.org/2000/09/xmldsig#sha1"); Property enableSign = new Property(); enableSign.setName(SAMLSSOConstants.SAMLFormFields.ENABLE_RESPONSE_SIGNING); enableSign.setType("hidden"); enableSign.setDisplayName("Enable Response Signing"); enableSign.setValue("true"); Property enableSigValidation = new Property(); enableSigValidation.setName(SAMLSSOConstants.SAMLFormFields.ENABLE_SIGNATURE_VALIDATION); enableSigValidation.setType("hidden"); enableSigValidation.setDisplayName("Enable Signature Validation in Authentication Requests and Logout " + "Requests"); enableSigValidation.setValue("false"); Property enableAssertionSigned = new Property(); enableAssertionSigned.setName(SAMLSSOConstants.SAMLFormFields.ENABLE_ASSERTION_SIGNING); enableAssertionSigned.setDisplayName("Enable Assertion Signing "); enableAssertionSigned.setValue("true"); enableAssertionSigned.setType("hidden"); Property enableEncAssert = new Property(); enableEncAssert.setName(SAMLSSOConstants.SAMLFormFields.ENABLE_ASSERTION_ENCRYPTION); enableEncAssert.setType("hidden"); enableEncAssert.setDisplayName("Enable Assertion Encryption "); enableEncAssert.setValue("false"); return new Property[]{issuer, appType, acsurls, enableAtrProf, enableDefaultAtrProf, acsindex, defaultacs, nameid, alias, signAlgo, digestAlgo, enableSign, enableSigValidation, enableEncAssert, enableAssertionSigned, certificate, metadata}; } @Override public String getRelyingPartyKey() { return SAMLSSOConstants.SAMLFormFields.ISSUER; } }
apache-2.0
pkarmstr/NYBC
solr-4.2.1/lucene/test-framework/src/java/org/apache/lucene/index/AssertingDirectoryReader.java
2744
package org.apache.lucene.index; /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.io.IOException; import java.util.List; /** * A {@link DirectoryReader} that wraps all its subreaders with * {@link AssertingAtomicReader} */ public class AssertingDirectoryReader extends DirectoryReader { protected DirectoryReader in; public AssertingDirectoryReader(DirectoryReader in) { super(in.directory(), wrap(in.getSequentialSubReaders())); this.in = in; } private static AtomicReader[] wrap(List<? extends AtomicReader> readers) { AtomicReader[] wrapped = new AtomicReader[readers.size()]; for (int i = 0; i < readers.size(); i++) { wrapped[i] = new AssertingAtomicReader(readers.get(i)); } return wrapped; } @Override protected DirectoryReader doOpenIfChanged() throws IOException { DirectoryReader d = in.doOpenIfChanged(); return d == null ? null : new AssertingDirectoryReader(d); } @Override protected DirectoryReader doOpenIfChanged(IndexCommit commit) throws IOException { DirectoryReader d = in.doOpenIfChanged(commit); return d == null ? null : new AssertingDirectoryReader(d); } @Override protected DirectoryReader doOpenIfChanged(IndexWriter writer, boolean applyAllDeletes) throws IOException { DirectoryReader d = in.doOpenIfChanged(writer, applyAllDeletes); return d == null ? null : new AssertingDirectoryReader(d); } @Override public long getVersion() { return in.getVersion(); } @Override public boolean isCurrent() throws IOException { return in.isCurrent(); } @Override public IndexCommit getIndexCommit() throws IOException { return in.getIndexCommit(); } @Override protected void doClose() throws IOException { in.doClose(); } @Override public Object getCoreCacheKey() { return in.getCoreCacheKey(); } @Override public Object getCombinedCoreAndDeletesKey() { return in.getCombinedCoreAndDeletesKey(); } }
apache-2.0
zhougz9527/coolweather
app/src/main/java/com/think/coolweather/MainActivity.java
726
package com.think.coolweather; import android.content.Intent; import android.content.SharedPreferences; import android.preference.PreferenceManager; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); if(prefs.getString("weather",null)!= null){ Intent intent = new Intent(this,WeatherActivity.class); startActivity(intent); finish(); } } }
apache-2.0
vimaier/conqat
org.conqat.engine.core/src/org/conqat/engine/core/conqatdoc/compare/SpecificationNameComparator.java
2062
/*-------------------------------------------------------------------------+ | | | Copyright 2005-2011 The ConQAT Project | | | | Licensed under the Apache License, Version 2.0 (the "License"); | | you may not use this file except in compliance with the License. | | You may obtain a copy of the License at | | | | http://www.apache.org/licenses/LICENSE-2.0 | | | | Unless required by applicable law or agreed to in writing, software | | distributed under the License is distributed on an "AS IS" BASIS, | | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | | See the License for the specific language governing permissions and | | limitations under the License. | +-------------------------------------------------------------------------*/ package org.conqat.engine.core.conqatdoc.compare; import java.util.Comparator; import org.conqat.engine.core.driver.specification.ISpecification; /** * Comparator for comparing specifications by their full name. * * @author Benjamin Hummel * @author Florian Deissenboeck * @author $Author: juergens $ * @version $Rev: 35194 $ * @ConQAT.Rating GREEN Hash: FAFC415993EACE3D68646B1C1010AD13 */ public class SpecificationNameComparator implements Comparator<ISpecification> { /** Instance of the comparator. */ public final static SpecificationNameComparator INSTANCE = new SpecificationNameComparator(); /** Compare specifications by name. */ @Override public int compare(ISpecification specification1, ISpecification specification2) { return specification1.getName().compareTo(specification2.getName()); } }
apache-2.0
kit-data-manager/base
DataOrganization/src/main/java/edu/kit/dama/mdm/dataorganization/impl/jpa/JPAImplUtil.java
3938
/** * Copyright (C) 2014 Karlsruhe Institute of Technology * * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package edu.kit.dama.mdm.dataorganization.impl.jpa; import edu.kit.dama.authorization.entities.IAuthorizationContext; import edu.kit.dama.authorization.exceptions.UnauthorizedAccessAttemptException; import edu.kit.dama.commons.types.DigitalObjectId; import edu.kit.dama.mdm.core.IMetaDataManager; import edu.kit.dama.mdm.core.MetaDataManagement; import edu.kit.dama.mdm.dataorganization.entity.core.ICollectionNode; import edu.kit.dama.mdm.dataorganization.entity.core.IDataOrganizationNode; import edu.kit.dama.mdm.dataorganization.entity.core.IFileNode; import edu.kit.dama.mdm.dataorganization.impl.jpa.persistence.PersistenceFacade; import edu.kit.dama.mdm.dataorganization.service.exception.DataOrganizationError; /** * Utility functions for the JPA implementation. * * @author pasic */ public final class JPAImplUtil { /** * Hidden constructor. */ private JPAImplUtil() { } /** * Converts some IDataOrganizationNode to JPA data organization node. * * @param pDataOrganizationNode the node to be converted. * * @return a corresponding JPA data organization node. */ public static DataOrganizationNode convertDataOrganizationNode(IDataOrganizationNode pDataOrganizationNode) { DataOrganizationNode newDon = null; if (null == pDataOrganizationNode) { return null; } if (pDataOrganizationNode instanceof DataOrganizationNode) { if (pDataOrganizationNode instanceof FileTree) { newDon = new CollectionNode((ICollectionNode) pDataOrganizationNode); } else { newDon = (DataOrganizationNode) pDataOrganizationNode; } } else if (pDataOrganizationNode instanceof ICollectionNode) { newDon = new CollectionNode((ICollectionNode) pDataOrganizationNode); } else if (pDataOrganizationNode instanceof IFileNode) { newDon = new FileNode((IFileNode) pDataOrganizationNode); } if (null == newDon) { throw new DataOrganizationError("node:IDataOrganizationNode should be either" + " instance of IFileNode or instance of ICollectionNode"); } return newDon; } public static int renameView(DigitalObjectId pObjectId, String pOldName, String pNewName, IAuthorizationContext pContext) throws UnauthorizedAccessAttemptException { String pu = PersistenceFacade.getInstance().getPersistenceUnitName(); IMetaDataManager mdm = MetaDataManagement.getMetaDataManagement().getMetaDataManager(pu); mdm.setAuthorizationContext(pContext); try { // int attribChanges = mdm.performUpdate("UPDATE Attribute a SET a.viewName=?1 WHERE a.annotatedNode.digitalObjectIDStr=?2 AND a.annotatedNode.viewName=?3", new Object[]{pNewName, pObjectId.getStringRepresentation(), pOldName}); // System.out.println("CHANGE " + attribChanges); return mdm.performUpdate("UPDATE DataOrganizationNode n SET n.viewName=?1 WHERE n.digitalObjectIDStr=?2 AND n.viewName=?3", new Object[]{pNewName, pObjectId.getStringRepresentation(), pOldName}); } finally { mdm.close(); } } }
apache-2.0
GoogleCloudPlatform/professional-services
tools/quota-monitoring-alerting/java/quota-notification/src/main/java/functions/eventpojos/PubSubMessage.java
1585
/* Copyright 2021 Google LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package functions.eventpojos; public class PubSubMessage { // Cloud Functions uses GSON to populate this object. // Field types/names are specified by Cloud Functions // Changing them may break your code! private String metric; private String limit; private String usage; private Float consumption; private String emailIds; public String getMetric() { return metric; } public void setMetric(String metric) { this.metric = metric; } public String getLimit() { return limit; } public void setLimit(String limit) { this.limit = limit; } public String getUsage() { return usage; } public void setUsage(String usage) { this.usage = usage; } public Float getConsumption() { return consumption; } public void setConsumption(Float consumption) { this.consumption = consumption; } public String getEmailIds() { return emailIds; } public void setEmailIds(String emailIds) { this.emailIds = emailIds; } }
apache-2.0
lesaint/experimenting-annotation-processing
experimenting-rounds/massive-count-of-annotated-classes/src/main/java/fr/javatronic/blog/massive/annotation1/sub1/Class_8757.java
151
package fr.javatronic.blog.massive.annotation1.sub1; import fr.javatronic.blog.processor.Annotation_001; @Annotation_001 public class Class_8757 { }
apache-2.0
jentfoo/aws-sdk-java
aws-java-sdk-mediaconvert/src/main/java/com/amazonaws/services/mediaconvert/model/ImageInserter.java
5930
/* * Copyright 2014-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.mediaconvert.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.protocol.StructuredPojo; import com.amazonaws.protocol.ProtocolMarshaller; /** * Enable the image inserter feature to include a graphic overlay on your video. Enable or disable this feature for each * input or output individually. This setting is disabled by default. * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/mediaconvert-2017-08-29/ImageInserter" target="_top">AWS API * Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class ImageInserter implements Serializable, Cloneable, StructuredPojo { /** Specify the images that you want to overlay on your video. The images must be PNG or TGA files. */ private java.util.List<InsertableImage> insertableImages; /** * Specify the images that you want to overlay on your video. The images must be PNG or TGA files. * * @return Specify the images that you want to overlay on your video. The images must be PNG or TGA files. */ public java.util.List<InsertableImage> getInsertableImages() { return insertableImages; } /** * Specify the images that you want to overlay on your video. The images must be PNG or TGA files. * * @param insertableImages * Specify the images that you want to overlay on your video. The images must be PNG or TGA files. */ public void setInsertableImages(java.util.Collection<InsertableImage> insertableImages) { if (insertableImages == null) { this.insertableImages = null; return; } this.insertableImages = new java.util.ArrayList<InsertableImage>(insertableImages); } /** * Specify the images that you want to overlay on your video. The images must be PNG or TGA files. * <p> * <b>NOTE:</b> This method appends the values to the existing list (if any). Use * {@link #setInsertableImages(java.util.Collection)} or {@link #withInsertableImages(java.util.Collection)} if you * want to override the existing values. * </p> * * @param insertableImages * Specify the images that you want to overlay on your video. The images must be PNG or TGA files. * @return Returns a reference to this object so that method calls can be chained together. */ public ImageInserter withInsertableImages(InsertableImage... insertableImages) { if (this.insertableImages == null) { setInsertableImages(new java.util.ArrayList<InsertableImage>(insertableImages.length)); } for (InsertableImage ele : insertableImages) { this.insertableImages.add(ele); } return this; } /** * Specify the images that you want to overlay on your video. The images must be PNG or TGA files. * * @param insertableImages * Specify the images that you want to overlay on your video. The images must be PNG or TGA files. * @return Returns a reference to this object so that method calls can be chained together. */ public ImageInserter withInsertableImages(java.util.Collection<InsertableImage> insertableImages) { setInsertableImages(insertableImages); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getInsertableImages() != null) sb.append("InsertableImages: ").append(getInsertableImages()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof ImageInserter == false) return false; ImageInserter other = (ImageInserter) obj; if (other.getInsertableImages() == null ^ this.getInsertableImages() == null) return false; if (other.getInsertableImages() != null && other.getInsertableImages().equals(this.getInsertableImages()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getInsertableImages() == null) ? 0 : getInsertableImages().hashCode()); return hashCode; } @Override public ImageInserter clone() { try { return (ImageInserter) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } @com.amazonaws.annotation.SdkInternalApi @Override public void marshall(ProtocolMarshaller protocolMarshaller) { com.amazonaws.services.mediaconvert.model.transform.ImageInserterMarshaller.getInstance().marshall(this, protocolMarshaller); } }
apache-2.0
Complexible/clearbit
test/src/com/complexible/clearbit/EnrichmentAPIV1Tests.java
308
package com.complexible.clearbit; /** * <p></p> * * @author Michael Grove * @since 0.2 * @version 0.2 */ public final class EnrichmentAPIV1Tests extends EnrichmentAPITests { /** * {@inheritDoc} */ @Override protected EnrichmentAPI createAPI() { return new EnrichmentAPIV1(getKey()); } }
apache-2.0
JohnStarich/mcStats
mcstats/GenericSkill.java
717
package mods.mcstats; /** * Abstract base skill class which * all skills are based on. * */ public abstract class GenericSkill { /** Skill level */ private int level; /** Total skill experience for current level */ private int experience; /** Total skill experience to gain new level */ private int xptonextlevel; /** * Returns skill level * @return */ public int getSkillLevel(){ return level; } /** * Returns skill experience * @return */ public int getExperience(){ return experience; } /** * Returns total experience to gain new level * @return */ public int getXPToNextLevel(){ return xptonextlevel; } /** * */ public abstract void gainExperience(); }
apache-2.0
UniTime/unitime
JavaSource/org/unitime/timetable/security/authority/OtherAuthority.java
1031
/* * Licensed to The Apereo Foundation under one or more contributor license * agreements. See the NOTICE file distributed with this work for * additional information regarding copyright ownership. * * The Apereo Foundation licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * limitations under the License. * */ package org.unitime.timetable.security.authority; import org.unitime.timetable.security.UserAuthority; /** * @author Tomas Muller */ public interface OtherAuthority { public boolean isMatch(UserAuthority authority); }
apache-2.0
tutufool/squbs
squbs-httpclient/src/test/java/org/squbs/httpclient/japi/TeamBeanWithCaseClassMember.java
2597
/* * Copyright 2015 PayPal * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.squbs.httpclient.japi; import org.squbs.httpclient.dummy.Employee; import java.util.ArrayList; import java.util.List; /** * Created by lma on 6/15/2015. */ public class TeamBeanWithCaseClassMember { private String description; private List<Employee> members; //must have a default one for unmarshalling public TeamBeanWithCaseClassMember() { } // public void setDescription(String desc) { // this.description = desc; // } // // public void setMembers(List<Employee> mbs) { // this.members = mbs; // } public String getDescription() { return this.description; } public List<Employee> getMembers() { return this.members; } public TeamBeanWithCaseClassMember addMember(Employee employee) { List<Employee> all = new ArrayList<Employee>(); all.addAll(members); all.add(employee); return new TeamBeanWithCaseClassMember(description, all); } public TeamBeanWithCaseClassMember(String description1, List<Employee> members1) { this.description = description1; this.members = members1; // nameMap = new HashMap<String, String>(); // for(int i = 0;i < members.size(); i++){ // EmployeeBean mem = members.get(i); // nameMap.put(mem.getFirstName(),mem.getLastName()); // } } public String toString() { StringBuilder sb = new StringBuilder(); sb.append("TeamBean[") .append("description=").append(description) .append(",members=").append(members) .append("]"); return sb.toString(); } public boolean equals(Object other) { if (!(other instanceof TeamBeanWithCaseClassMember)) return false; else { TeamBeanWithCaseClassMember otherTeam = (TeamBeanWithCaseClassMember) other; return otherTeam.description.equals(description) && otherTeam.members.equals(members); } } }
apache-2.0
willjgriff/android-skeleton
app/src/main/java/com/github/willjgriff/skeleton/ui/navigation/NavigationToolbarListener.java
314
package com.github.willjgriff.skeleton.ui.navigation; import android.support.annotation.StringRes; /** * Created by Will on 20/08/2016. */ public interface NavigationToolbarListener { void showNetworkLoadingView(); void hideNetworkLoadingView(); void setToolbarTitle(@StringRes int toolbarTitleRes); }
apache-2.0
org-metaeffekt/metaeffekt-core
plugins/ae-jira-maven-plugin/src/main/java/org/metaeffekt/core/maven/jira/util/JsonTransformer.java
5338
/* * Copyright 2009-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.metaeffekt.core.maven.jira.util; import org.codehaus.jackson.JsonGenerationException; import org.codehaus.jackson.JsonNode; import org.codehaus.jackson.JsonProcessingException; import org.codehaus.jackson.map.JsonMappingException; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.map.SerializationConfig.Feature; import org.codehaus.jackson.node.ArrayNode; import org.codehaus.jackson.node.ObjectNode; import org.codehaus.jackson.node.POJONode; import java.io.IOException; import java.util.*; /** * Transformer to convert between object trees and the string representation of JSON data. */ public class JsonTransformer { /** * Convert data tree recursively to a JSON string. * * @param data the data to be converted * @param indent if <code>true</code>, indent the output (typically with two spaces) * * @return JSON string representation of the given data tree */ public static String transform(Object data, boolean indent) { ObjectMapper mapper = new ObjectMapper(); if (indent) { mapper.configure(Feature.INDENT_OUTPUT, true); } try { return mapper.writeValueAsString(data); } catch (JsonGenerationException e) { throw new RuntimeException(e); } catch (JsonMappingException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } } /** * Convert a JSON string to a data tree structure. * <p> * Most of the effort goes into replacing the proprietary classes in the package * <code>org.codehaus.jackson</code> with plain standard Java classes like * <code>java.util.Map</code> and <code>java.util.List</code>. * * @param dataString the data string to be converted * * @return The JSON data as a hierarchical structure of maps, lists, string and number values */ public static Object transform(String dataString) { ObjectMapper mapper = new ObjectMapper(); JsonNode result = null; try { result = mapper.readTree(dataString); } catch (JsonProcessingException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } return transformNode(result); } private static Object transformNode(JsonNode node) { if (node.isArray()) { return transformArray((ArrayNode) node); } else if (node.isObject()) { return transformObject((ObjectNode) node); } else if (node.isPojo()) { return transformPojo((POJONode) node); } else if (node.isInt()) { return node.getIntValue(); } else if (node.isBigInteger()) { return node.getBigIntegerValue(); } else if (node.isLong()) { return node.getLongValue(); } else if (node.isDouble() || node.isFloatingPointNumber()) { return node.getDoubleValue(); } else if (node.isBoolean()) { return node.getBooleanValue(); } else if (node.isTextual()) { return node.getTextValue(); } else if (node.isNull()) { return null; } else { return node.getValueAsText(); } } private static Map<String, Object> transformPojo(POJONode pojoNode) { Map<String, Object> result = new HashMap<String, Object>(); Iterator<String> fieldNames = pojoNode.getFieldNames(); while (fieldNames.hasNext()) { String key = fieldNames.next(); JsonNode node = pojoNode.get(key); result.put(key, transformNode(node)); } return result; } private static Map<String, Object> transformObject(ObjectNode objectNode) { Map<String, Object> result = new HashMap<String, Object>(); Iterator<String> fieldNames = objectNode.getFieldNames(); while (fieldNames.hasNext()) { String key = fieldNames.next(); JsonNode node = objectNode.get(key); result.put(key, transformNode(node)); } return result; } private static List<Object> transformArray(ArrayNode arrayNode) { List<Object> result = new ArrayList<Object>(); Iterator<JsonNode> nodes = arrayNode.getElements(); while (nodes.hasNext()) { JsonNode node = nodes.next(); result.add(transformNode(node)); } return result; } }
apache-2.0
DmitryBSS/java_test
addressbook-web-tests/src/test/java/ru/stqa/pft/addressbook/tests/DetailInformationContactTests.java
1979
package ru.stqa.pft.addressbook.tests; import org.testng.annotations.Test; import ru.stqa.pft.addressbook.model.ContactData; import ru.stqa.pft.addressbook.model.Contacts; import java.util.Arrays; import java.util.Iterator; import java.util.stream.Collectors; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; /** * Created by popdv on 14.08.2016. */ public class DetailInformationContactTests extends TestBase { @Test public void testDetailInformationContact() { app.goTo().homePage(); Contacts contacts = app.contract().all(); Iterator<ContactData> iterator = contacts.iterator(); ContactData contact = null; while (iterator.hasNext()) { contact = iterator.next(); if (contact.getId() == 217) { break; } } ContactData contactInfoFromDetailForm = app.contract().infoFromDetailForm(contact); ContactData contactInfoFromEditForm = app.contract().infoFromEditForm(contact); String mergeInfoFromEditForm = mergeInfoFromEditForm(contactInfoFromEditForm); assertThat(contactInfoFromDetailForm.getDetailsInfo(), equalTo(mergeInfoFromEditForm)); } private String mergeInfoFromEditForm(ContactData contact) { if (!(contact.getTelHome().equals(""))) { contact.withTelHome("H: " + contact.getTelHome()); } if (!(contact.getTelMobile().equals(""))) { contact.withTelMobile("M: " + contact.getTelMobile()); } if (!(contact.getTelWork().equals(""))) { contact.withTelWork("W: " + contact.getTelWork()); } return Arrays.asList(contact.getFirstName() + " " + contact.getLastName(), contact.getAddress() + "\n", contact.getTelHome(), contact.getTelMobile(), contact.getTelWork()) .stream().filter((s) -> !s.equals("")) .collect(Collectors.joining("\n")); } }
apache-2.0
kanrourou/software-testing
Debugging/Bug 6/ExcelParserTest.java
15125
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.tika.parser.microsoft; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.io.InputStream; import java.util.Locale; import org.apache.tika.detect.DefaultDetector; import org.apache.tika.detect.Detector; import org.apache.tika.metadata.Metadata; import org.apache.tika.metadata.OfficeOpenXMLExtended; import org.apache.tika.metadata.TikaCoreProperties; import org.apache.tika.mime.MediaType; import org.apache.tika.parser.AutoDetectParser; import org.apache.tika.parser.ParseContext; import org.apache.tika.parser.microsoft.ooxml.OOXMLParser; import org.apache.tika.sax.BodyContentHandler; import org.junit.Test; import org.xml.sax.ContentHandler; public class ExcelParserTest { @Test public void test_Russian_Excel_Parser() throws Exception { InputStream input = ExcelParserTest.class.getResourceAsStream( "/test-documents/ะกั‡ะตั‚ โ„–3144 ะพั‚ 31.10.12 (35 320ั€.).xls"); try { Metadata metadata = new Metadata(); ContentHandler handler = new BodyContentHandler(); ParseContext context = new ParseContext(); context.set(Locale.class, Locale.US); new OfficeParser().parse(input, handler, metadata, context); String content = handler.toString(); assertTrue( ! content.isEmpty()); } finally { input.close(); } } @Test public void testExcelParser() throws Exception { InputStream input = ExcelParserTest.class.getResourceAsStream( "/test-documents/testEXCEL.xls"); try { Metadata metadata = new Metadata(); ContentHandler handler = new BodyContentHandler(); ParseContext context = new ParseContext(); context.set(Locale.class, Locale.US); new OfficeParser().parse(input, handler, metadata, context); assertEquals( "application/vnd.ms-excel", metadata.get(Metadata.CONTENT_TYPE)); assertEquals("Simple Excel document", metadata.get(TikaCoreProperties.TITLE)); assertEquals("Keith Bennett", metadata.get(TikaCoreProperties.CREATOR)); assertEquals("Keith Bennett", metadata.get(Metadata.AUTHOR)); // Mon Oct 01 17:13:56 BST 2007 assertEquals("2007-10-01T16:13:56Z", metadata.get(TikaCoreProperties.CREATED)); assertEquals("2007-10-01T16:13:56Z", metadata.get(Metadata.CREATION_DATE)); // Mon Oct 01 17:31:43 BST 2007 assertEquals("2007-10-01T16:31:43Z", metadata.get(TikaCoreProperties.MODIFIED)); assertEquals("2007-10-01T16:31:43Z", metadata.get(Metadata.DATE)); String content = handler.toString(); assertTrue(content.contains("Sample Excel Worksheet")); assertTrue(content.contains("Numbers and their Squares")); assertTrue(content.contains("\t\tNumber\tSquare")); assertTrue(content.contains("9")); assertFalse(content.contains("9.0")); assertTrue(content.contains("196")); assertFalse(content.contains("196.0")); } finally { input.close(); } } @Test public void testExcelParserFormatting() throws Exception { InputStream input = ExcelParserTest.class.getResourceAsStream( "/test-documents/testEXCEL-formats.xls"); try { Metadata metadata = new Metadata(); ParseContext context = new ParseContext(); context.set(Locale.class, Locale.US); ContentHandler handler = new BodyContentHandler(); new OfficeParser().parse(input, handler, metadata, context); assertEquals( "application/vnd.ms-excel", metadata.get(Metadata.CONTENT_TYPE)); String content = handler.toString(); // Number #,##0.00 assertTrue(content.contains("1,599.99")); assertTrue(content.contains("-1,599.99")); // Currency $#,##0.00;[Red]($#,##0.00) assertTrue(content.contains("$1,599.99")); assertTrue(content.contains("($1,599.99)")); // Scientific 0.00E+00 // poi <=3.8beta1 returns 1.98E08, newer versions return 1.98+E08 assertTrue(content.contains("1.98E08") || content.contains("1.98E+08")); assertTrue(content.contains("-1.98E08") || content.contains("-1.98E+08")); // Percentage. assertTrue(content.contains("2.50%")); // Excel rounds up to 3%, but that requires Java 1.6 or later if(System.getProperty("java.version").startsWith("1.5")) { assertTrue(content.contains("2%")); } else { assertTrue(content.contains("3%")); } // Time Format: h:mm assertTrue(content.contains("6:15")); assertTrue(content.contains("18:15")); // Date Format: d-mmm-yy assertTrue(content.contains("17-May-07")); // Date Format: m/d/yy assertTrue(content.contains("10/3/09")); // Date/Time Format: m/d/yy h:mm assertTrue(content.contains("1/19/08 4:35")); // Below assertions represent outstanding formatting issues to be addressed // they are included to allow the issues to be progressed with the Apache POI // team - See TIKA-103. /************************************************************************* // Custom Number (0 "dollars and" .00 "cents") assertTrue(content.contains("19 dollars and .99 cents")); // Custom Number ("At" h:mm AM/PM "on" dddd mmmm d"," yyyy) assertTrue(content.contains("At 4:20 AM on Thursday May 17, 2007")); // Fraction (2.5): # ?/? (TODO Coming in POI 3.8 beta 6) assertTrue(content.contains("2 1 / 2")); **************************************************************************/ } finally { input.close(); } } /** * TIKA-214 - Ensure we extract labels etc from Charts */ @Test public void testExcelParserCharts() throws Exception { InputStream input = ExcelParserTest.class.getResourceAsStream( "/test-documents/testEXCEL-charts.xls"); try { Metadata metadata = new Metadata(); ParseContext context = new ParseContext(); context.set(Locale.class, Locale.US); ContentHandler handler = new BodyContentHandler(); new OfficeParser().parse(input, handler, metadata, context); assertEquals( "application/vnd.ms-excel", metadata.get(Metadata.CONTENT_TYPE)); String content = handler.toString(); // The first sheet has a pie chart assertTrue(content.contains("charttabyodawg")); assertTrue(content.contains("WhamPuff")); // The second sheet has a bar chart and some text assertTrue(content.contains("Sheet1")); assertTrue(content.contains("Test Excel Spreasheet")); assertTrue(content.contains("foo")); assertTrue(content.contains("bar")); assertTrue(content.contains("fizzlepuff")); assertTrue(content.contains("whyaxis")); assertTrue(content.contains("eksaxis")); // The third sheet has some text assertTrue(content.contains("Sheet2")); assertTrue(content.contains("dingdong")); } finally { input.close(); } } @Test public void testJXL() throws Exception { InputStream input = ExcelParserTest.class.getResourceAsStream( "/test-documents/jxl.xls"); try { Metadata metadata = new Metadata(); ContentHandler handler = new BodyContentHandler(-1); ParseContext context = new ParseContext(); context.set(Locale.class, Locale.US); new OfficeParser().parse(input, handler, metadata, context); assertEquals( "application/vnd.ms-excel", metadata.get(Metadata.CONTENT_TYPE)); String content = handler.toString(); assertTrue(content.contains("Number Formats")); } finally { input.close(); } } @Test public void testWorksSpreadsheet70() throws Exception { InputStream input = ExcelParserTest.class.getResourceAsStream( "/test-documents/testWORKSSpreadsheet7.0.xlr"); try { Metadata metadata = new Metadata(); ContentHandler handler = new BodyContentHandler(-1); ParseContext context = new ParseContext(); context.set(Locale.class, Locale.US); new OfficeParser().parse(input, handler, metadata, context); String content = handler.toString(); assertTrue(content.contains("Microsoft Works")); } finally { input.close(); } } /** * We don't currently support the .xlsb file format * (an OOXML container with binary blobs), but we * shouldn't break on these files either (TIKA-826) */ @Test public void testExcelXLSB() throws Exception { Detector detector = new DefaultDetector(); AutoDetectParser parser = new AutoDetectParser(); InputStream input = ExcelParserTest.class.getResourceAsStream( "/test-documents/testEXCEL.xlsb"); Metadata m = new Metadata(); m.add(Metadata.RESOURCE_NAME_KEY, "excel.xlsb"); // Should be detected correctly MediaType type = null; try { type = detector.detect(input, m); assertEquals("application/vnd.ms-excel.sheet.binary.macroenabled.12", type.toString()); } finally { input.close(); } // OfficeParser won't handle it assertEquals(false, (new OfficeParser()).getSupportedTypes(new ParseContext()).contains(type)); // OOXMLParser won't handle it assertEquals(false, (new OOXMLParser()).getSupportedTypes(new ParseContext()).contains(type)); // AutoDetectParser doesn't break on it input = ExcelParserTest.class.getResourceAsStream("/test-documents/testEXCEL.xlsb"); try { ContentHandler handler = new BodyContentHandler(-1); ParseContext context = new ParseContext(); context.set(Locale.class, Locale.US); parser.parse(input, handler, m, context); String content = handler.toString(); assertEquals("", content); } finally { input.close(); } } /** * We don't currently support the old Excel 95 .xls file format, * but we shouldn't break on these files either (TIKA-976) */ @Test public void testExcel95() throws Exception { Detector detector = new DefaultDetector(); AutoDetectParser parser = new AutoDetectParser(); InputStream input = ExcelParserTest.class.getResourceAsStream( "/test-documents/testEXCEL_95.xls"); Metadata m = new Metadata(); m.add(Metadata.RESOURCE_NAME_KEY, "excel_95.xls"); // Should be detected correctly MediaType type = null; try { type = detector.detect(input, m); assertEquals("application/vnd.ms-excel", type.toString()); } finally { input.close(); } // OfficeParser will claim to handle it assertEquals(true, (new OfficeParser()).getSupportedTypes(new ParseContext()).contains(type)); // OOXMLParser won't handle it assertEquals(false, (new OOXMLParser()).getSupportedTypes(new ParseContext()).contains(type)); // AutoDetectParser doesn't break on it input = ExcelParserTest.class.getResourceAsStream("/test-documents/testEXCEL_95.xls"); try { ContentHandler handler = new BodyContentHandler(-1); ParseContext context = new ParseContext(); context.set(Locale.class, Locale.US); parser.parse(input, handler, m, context); String content = handler.toString(); assertEquals("", content); } finally { input.close(); } } /** * Ensures that custom OLE2 (HPSF) properties are extracted */ @Test public void testCustomProperties() throws Exception { InputStream input = ExcelParserTest.class.getResourceAsStream( "/test-documents/testEXCEL_custom_props.xls"); Metadata metadata = new Metadata(); try { ContentHandler handler = new BodyContentHandler(-1); ParseContext context = new ParseContext(); context.set(Locale.class, Locale.US); new OfficeParser().parse(input, handler, metadata, context); } finally { input.close(); } assertEquals("application/vnd.ms-excel", metadata.get(Metadata.CONTENT_TYPE)); assertEquals("", metadata.get(TikaCoreProperties.CREATOR)); assertEquals("", metadata.get(TikaCoreProperties.MODIFIER)); assertEquals("2011-08-22T13:45:54Z", metadata.get(TikaCoreProperties.MODIFIED)); assertEquals("2006-09-12T15:06:44Z", metadata.get(TikaCoreProperties.CREATED)); assertEquals("Microsoft Excel", metadata.get(OfficeOpenXMLExtended.APPLICATION)); assertEquals("true", metadata.get("custom:myCustomBoolean")); assertEquals("3", metadata.get("custom:myCustomNumber")); assertEquals("MyStringValue", metadata.get("custom:MyCustomString")); assertEquals("2010-12-30T22:00:00Z", metadata.get("custom:MyCustomDate")); assertEquals("2010-12-29T22:00:00Z", metadata.get("custom:myCustomSecondDate")); } }
apache-2.0
JNDX25219/ZhiHuiDianTi
app/src/main/java/com/example/administrator/zhihuidianti/data/bean/JianYiBiao.java
2420
package com.example.administrator.zhihuidianti.data.bean; import com.j256.ormlite.field.DatabaseField; import com.j256.ormlite.table.DatabaseTable; /** * Created by FengChaoQun * on 2016/2/25 */ @DatabaseTable(tableName = "ๅปบ่ฎฎ่กจ") public class JianYiBiao extends Base{ @DatabaseField private String ๅปบ่ฎฎๅ†…ๅฎน; @DatabaseField private String ๅปบ่ฎฎ็”จๆˆท; @DatabaseField private String ๅปบ่ฎฎๆ—ฅๆœŸ; @DatabaseField private String ๅปบ่ฎฎ็”จๆˆทid; @DatabaseField private String ๅปบ่ฎฎ็”จๆˆท็ฑปๅˆซ; @DatabaseField private String ๅ›žๅคๅ†…ๅฎน; @DatabaseField private String ๅ›žๅค็”จๆˆท; @DatabaseField private String ๅ›žๅคๆ—ฅๆœŸ; @DatabaseField private String ๅ›žๅค็”จๆˆทid; public String getๅปบ่ฎฎๅ†…ๅฎน() { return ๅปบ่ฎฎๅ†…ๅฎน; } public void setๅปบ่ฎฎๅ†…ๅฎน(String ๅปบ่ฎฎๅ†…ๅฎน) { this.ๅปบ่ฎฎๅ†…ๅฎน = ๅปบ่ฎฎๅ†…ๅฎน; } public String getๅปบ่ฎฎ็”จๆˆท() { return ๅปบ่ฎฎ็”จๆˆท; } public void setๅปบ่ฎฎ็”จๆˆท(String ๅปบ่ฎฎ็”จๆˆท) { this.ๅปบ่ฎฎ็”จๆˆท = ๅปบ่ฎฎ็”จๆˆท; } public String getๅปบ่ฎฎๆ—ฅๆœŸ() { return ๅปบ่ฎฎๆ—ฅๆœŸ; } public void setๅปบ่ฎฎๆ—ฅๆœŸ(String ๅปบ่ฎฎๆ—ฅๆœŸ) { this.ๅปบ่ฎฎๆ—ฅๆœŸ = ๅปบ่ฎฎๆ—ฅๆœŸ; } public String getๅปบ่ฎฎ็”จๆˆทid() { return ๅปบ่ฎฎ็”จๆˆทid; } public void setๅปบ่ฎฎ็”จๆˆทid(String ๅปบ่ฎฎ็”จๆˆทid) { this.ๅปบ่ฎฎ็”จๆˆทid = ๅปบ่ฎฎ็”จๆˆทid; } public String getๅปบ่ฎฎ็”จๆˆท็ฑปๅˆซ() { return ๅปบ่ฎฎ็”จๆˆท็ฑปๅˆซ; } public void setๅปบ่ฎฎ็”จๆˆท็ฑปๅˆซ(String ๅปบ่ฎฎ็”จๆˆท็ฑปๅˆซ) { this.ๅปบ่ฎฎ็”จๆˆท็ฑปๅˆซ = ๅปบ่ฎฎ็”จๆˆท็ฑปๅˆซ; } public String getๅ›žๅคๅ†…ๅฎน() { return ๅ›žๅคๅ†…ๅฎน; } public void setๅ›žๅคๅ†…ๅฎน(String ๅ›žๅคๅ†…ๅฎน) { this.ๅ›žๅคๅ†…ๅฎน = ๅ›žๅคๅ†…ๅฎน; } public String getๅ›žๅค็”จๆˆท() { return ๅ›žๅค็”จๆˆท; } public void setๅ›žๅค็”จๆˆท(String ๅ›žๅค็”จๆˆท) { this.ๅ›žๅค็”จๆˆท = ๅ›žๅค็”จๆˆท; } public String getๅ›žๅคๆ—ฅๆœŸ() { return ๅ›žๅคๆ—ฅๆœŸ; } public void setๅ›žๅคๆ—ฅๆœŸ(String ๅ›žๅคๆ—ฅๆœŸ) { this.ๅ›žๅคๆ—ฅๆœŸ = ๅ›žๅคๆ—ฅๆœŸ; } public String getๅ›žๅค็”จๆˆทid() { return ๅ›žๅค็”จๆˆทid; } public void setๅ›žๅค็”จๆˆทid(String ๅ›žๅค็”จๆˆทid) { this.ๅ›žๅค็”จๆˆทid = ๅ›žๅค็”จๆˆทid; } }
apache-2.0
ParaskP7/sample-code-posts
app/src/main/java/io/petros/posts/app/graph/components/package-info.java
259
/** * This package-info.java file handles package-level annotations. Mind that package level annotations don't affect nested packages. */ @PackageNonnull package io.petros.posts.app.graph.components; import io.petros.posts.util.annotations.PackageNonnull;
apache-2.0
lei-xia/helix
helix-core/src/main/java/org/apache/helix/tools/commandtools/ZkGrep.java
19106
package org.apache.helix.tools.commandtools; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import java.io.BufferedReader; import java.io.File; import java.io.FileFilter; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.Date; import java.util.List; import java.util.zip.GZIPInputStream; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.GnuParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Option; import org.apache.commons.cli.OptionBuilder; import org.apache.commons.cli.OptionGroup; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.apache.commons.io.FileUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * utility for grep zk transaction/snapshot logs * - to grep a pattern by t1 use: * zkgrep --zkCfg zkCfg --by t1 --pattern patterns... * - to grep a pattern between t1 and t2 use: * zkgrep --zkCfg zkCfg --between t1 t2 --pattern patterns... * for example, to find fail-over latency between t1 and t2, use: * 1) zkgrep --zkCfg zkCfg --by t1 --pattern "/{cluster}/LIVEINSTNCES/" | grep {fail-node} * 2) zkgrep --zkCfg zkCfg --between t1 t2 --pattern "closeSession" | grep {fail-node session-id} * 3) zkgrep --zkCfg zkCfg --between t1 t2 --pattern "/{cluster}" | grep "CURRENTSTATES" | * grep "setData" | tail -1 * fail-over latency = timestamp difference between 2) and 3) */ public class ZkGrep { private static Logger LOG = LoggerFactory.getLogger(ZkGrep.class); private static final String zkCfg = "zkCfg"; private static final String pattern = "pattern"; private static final String by = "by"; private static final String between = "between"; public static final String log = "log"; public static final String snapshot = "snapshot"; private static final String gzSuffix = ".gz"; @SuppressWarnings("static-access") private static Options constructCommandLineOptions() { Option zkCfgOption = OptionBuilder.hasArgs(1).isRequired(false).withLongOpt(zkCfg).withArgName("zoo.cfg") .withDescription("provide zoo.cfg").create(); Option patternOption = OptionBuilder.hasArgs().isRequired(true).withLongOpt(pattern) .withArgName("grep-patterns...").withDescription("provide patterns (required)") .create(); Option betweenOption = OptionBuilder.hasArgs(2).isRequired(false).withLongOpt(between) .withArgName("t1 t2 (timestamp in ms or yyMMdd_hhmmss_SSS)") .withDescription("grep between t1 and t2").create(); Option byOption = OptionBuilder.hasArgs(1).isRequired(false).withLongOpt(by) .withArgName("t (timestamp in ms or yyMMdd_hhmmss_SSS)").withDescription("grep by t") .create(); OptionGroup group = new OptionGroup(); group.setRequired(true); group.addOption(betweenOption); group.addOption(byOption); Options options = new Options(); options.addOption(zkCfgOption); options.addOption(patternOption); options.addOptionGroup(group); return options; } /** * get zk transaction log dir and zk snapshot log dir * @param zkCfgFile * @return String[0]: zk-transaction-log-dir, String[1]: zk-snapshot-dir */ static String[] getZkDataDirs(String zkCfgFile) { String[] zkDirs = new String[2]; FileInputStream fis = null; BufferedReader br = null; try { fis = new FileInputStream(zkCfgFile); br = new BufferedReader(new InputStreamReader(fis)); String line; while ((line = br.readLine()) != null) { String key = "dataDir="; if (line.startsWith(key)) { zkDirs[1] = zkDirs[0] = line.substring(key.length()) + "/version-2"; } key = "dataLogDir="; if (line.startsWith(key)) { zkDirs[0] = line.substring(key.length()) + "/version-2"; } } } catch (Exception e) { LOG.error("exception in read file: " + zkCfgFile, e); } finally { try { if (br != null) { br.close(); } if (fis != null) { fis.close(); } } catch (Exception e) { LOG.error("exception in closing file: " + zkCfgFile, e); } } return zkDirs; } // debug static void printFiles(File[] files) { System.out.println("START print"); for (int i = 0; i < files.length; i++) { File file = files[i]; System.out.println(file.getName() + ", " + file.lastModified()); } System.out.println("END print"); } /** * get files under dir in order of last modified time * @param dir * @param pattern * @return */ static File[] getSortedFiles(String dirPath, final String pattern) { File dir = new File(dirPath); File[] files = dir.listFiles(new FileFilter() { @Override public boolean accept(File file) { return file.isFile() && (file.getName().indexOf(pattern) != -1); } }); Arrays.sort(files, new Comparator<File>() { @Override public int compare(File o1, File o2) { int sign = (int) Math.signum(o1.lastModified() - o2.lastModified()); return sign; } }); return files; } /** * get value for an attribute in a parsed zk log; e.g. * "time:1384984016778 session:0x14257d1d17e0004 cxid:0x5 zxid:0x46899 type:error err:-101" * given "time" return "1384984016778" * @param line * @param attribute * @return value */ static String getAttributeValue(String line, String attribute) { if (line == null) { return null; } if (!attribute.endsWith(":")) { attribute = attribute + ":"; } String[] parts = line.split("\\s"); if (parts != null && parts.length > 0) { for (int i = 0; i < parts.length; i++) { if (parts[i].startsWith(attribute)) { String val = parts[i].substring(attribute.length()); return val; } } } return null; } static long getTimestamp(String line) { String timestamp = getAttributeValue(line, "time"); return Long.parseLong(timestamp); } /** * parse a time string either in timestamp form or "yyMMdd_hhmmss_SSS" form * @param time * @return timestamp or -1 on error */ static long parseTimeString(String time) { try { return Long.parseLong(time); } catch (NumberFormatException e) { try { SimpleDateFormat formatter = new SimpleDateFormat("yyMMdd_hhmmss_SSS"); Date date = formatter.parse(time); return date.getTime(); } catch (java.text.ParseException ex) { LOG.error("fail to parse time string: " + time, e); } } return -1; } public static void grepZkLog(File zkLog, long start, long end, String... patterns) { FileInputStream fis = null; BufferedReader br = null; try { fis = new FileInputStream(zkLog); br = new BufferedReader(new InputStreamReader(fis)); String line; while ((line = br.readLine()) != null) { try { long timestamp = getTimestamp(line); if (timestamp > end) { break; } if (timestamp < start) { continue; } boolean match = true; for (String pattern : patterns) { if (line.indexOf(pattern) == -1) { match = false; break; } } if (match) { System.out.println(line); } } catch (NumberFormatException e) { // ignore } } } catch (Exception e) { LOG.error("exception in grep zk-log: " + zkLog, e); } finally { try { if (br != null) { br.close(); } if (fis != null) { fis.close(); } } catch (Exception e) { LOG.error("exception in closing zk-log: " + zkLog, e); } } } public static void grepZkLogDir(List<File> parsedZkLogs, long start, long end, String... patterns) { for (File file : parsedZkLogs) { grepZkLog(file, start, end, patterns); } } public static void grepZkSnapshot(File zkSnapshot, String... patterns) { FileInputStream fis = null; BufferedReader br = null; try { fis = new FileInputStream(zkSnapshot); br = new BufferedReader(new InputStreamReader(fis)); String line; while ((line = br.readLine()) != null) { try { boolean match = true; for (String pattern : patterns) { if (line.indexOf(pattern) == -1) { match = false; break; } } if (match) { System.out.println(line); } } catch (NumberFormatException e) { // ignore } } } catch (Exception e) { LOG.error("exception in grep zk-snapshot: " + zkSnapshot, e); } finally { try { if (br != null) { br.close(); } if (fis != null) { fis.close(); } } catch (Exception e) { LOG.error("exception in closing zk-snapshot: " + zkSnapshot, e); } } } /** * guess zoo.cfg dir * @return absolute path to zoo.cfg */ static String guessZkCfgDir() { // TODO impl this return null; } public static void printUsage(Options cliOptions) { HelpFormatter helpFormatter = new HelpFormatter(); helpFormatter.setWidth(1000); helpFormatter.printHelp("java " + ZkGrep.class.getName(), cliOptions); } /** * parse zk-transaction-logs between start and end, if not already parsed * @param zkLogDir * @param start * @param end * @return list of parsed zklogs between start and end, in order of last modified timestamp */ static List<File> parseZkLogs(String zkLogDir, long start, long end) { File zkParsedDir = new File(String.format("%s/zklog-parsed", System.getProperty("user.home"))); File[] zkLogs = getSortedFiles(zkLogDir, log); // printFiles(zkDataFiles); List<File> parsedZkLogs = new ArrayList<File>(); boolean stop = false; for (File zkLog : zkLogs) { if (stop) { break; } if (zkLog.lastModified() < start) { continue; } if (zkLog.lastModified() > end) { stop = true; } try { File parsedZkLog = new File(zkParsedDir, stripGzSuffix(zkLog.getName()) + ".parsed"); if (!parsedZkLog.exists() || parsedZkLog.lastModified() <= zkLog.lastModified()) { if (zkLog.getName().endsWith(gzSuffix)) { // copy and gunzip it FileUtils.copyFileToDirectory(zkLog, zkParsedDir); File zkLogGz = new File(zkParsedDir, zkLog.getName()); File tmpZkLog = gunzip(zkLogGz); // parse gunzip file ZKLogFormatter .main(new String[] { log, tmpZkLog.getAbsolutePath(), parsedZkLog.getAbsolutePath() }); // delete it zkLogGz.delete(); tmpZkLog.delete(); } else { // parse it directly ZKLogFormatter.main(new String[] { log, zkLog.getAbsolutePath(), parsedZkLog.getAbsolutePath() }); } } parsedZkLogs.add(parsedZkLog); } catch (Exception e) { LOG.error("fail to parse zkLog: " + zkLog, e); } } return parsedZkLogs; } /** * Strip off a .gz suffix if any * @param filename * @return */ static String stripGzSuffix(String filename) { if (filename.endsWith(gzSuffix)) { return filename.substring(0, filename.length() - gzSuffix.length()); } return filename; } /** * Gunzip a file * @param zipFile * @return */ static File gunzip(File zipFile) { File outputFile = new File(stripGzSuffix(zipFile.getAbsolutePath())); byte[] buffer = new byte[1024]; try { GZIPInputStream gzis = new GZIPInputStream(new FileInputStream(zipFile)); FileOutputStream out = new FileOutputStream(outputFile); int len; while ((len = gzis.read(buffer)) > 0) { out.write(buffer, 0, len); } gzis.close(); out.close(); return outputFile; } catch (IOException e) { LOG.error("fail to gunzip file: " + zipFile, e); } return null; } /** * parse the last zk-snapshots by by-time, if not already parsed * @param zkSnapshotDir * @param byTime * @return File array which the first element is the last zk-snapshot by by-time and the second * element is its parsed file */ static File[] parseZkSnapshot(String zkSnapshotDir, long byTime) { File[] retFiles = new File[2]; File zkParsedDir = new File(String.format("%s/zklog-parsed", System.getProperty("user.home"))); File[] zkSnapshots = getSortedFiles(zkSnapshotDir, snapshot); // printFiles(zkDataFiles); File lastZkSnapshot = null; for (int i = 0; i < zkSnapshots.length; i++) { File zkSnapshot = zkSnapshots[i]; if (zkSnapshot.lastModified() >= byTime) { break; } lastZkSnapshot = zkSnapshot; retFiles[0] = lastZkSnapshot; } try { File parsedZkSnapshot = new File(zkParsedDir, stripGzSuffix(lastZkSnapshot.getName()) + ".parsed"); if (!parsedZkSnapshot.exists() || parsedZkSnapshot.lastModified() <= lastZkSnapshot.lastModified()) { if (lastZkSnapshot.getName().endsWith(gzSuffix)) { // copy and gunzip it FileUtils.copyFileToDirectory(lastZkSnapshot, zkParsedDir); File lastZkSnapshotGz = new File(zkParsedDir, lastZkSnapshot.getName()); File tmpLastZkSnapshot = gunzip(lastZkSnapshotGz); // parse gunzip file ZKLogFormatter.main(new String[] { snapshot, tmpLastZkSnapshot.getAbsolutePath(), parsedZkSnapshot.getAbsolutePath() }); // delete it lastZkSnapshotGz.delete(); tmpLastZkSnapshot.delete(); } else { // parse it directly ZKLogFormatter.main(new String[] { snapshot, lastZkSnapshot.getAbsolutePath(), parsedZkSnapshot.getAbsolutePath() }); } } retFiles[1] = parsedZkSnapshot; return retFiles; } catch (Exception e) { LOG.error("fail to parse zkSnapshot: " + lastZkSnapshot, e); } return null; } public static void processCommandLineArgs(String[] cliArgs) { CommandLineParser cliParser = new GnuParser(); Options cliOptions = constructCommandLineOptions(); CommandLine cmd = null; try { cmd = cliParser.parse(cliOptions, cliArgs); } catch (ParseException pe) { System.err.println("CommandLineClient: failed to parse command-line options: " + pe); printUsage(cliOptions); System.exit(1); } String zkCfgDirValue = null; String zkCfgFile = null; if (cmd.hasOption(zkCfg)) { zkCfgDirValue = cmd.getOptionValue(zkCfg); } if (zkCfgDirValue == null) { zkCfgDirValue = guessZkCfgDir(); } if (zkCfgDirValue == null) { LOG.error("couldn't figure out path to zkCfg file"); System.exit(1); } // get zoo.cfg path from cfg-dir zkCfgFile = zkCfgDirValue; if (!zkCfgFile.endsWith(".cfg")) { // append with default zoo.cfg zkCfgFile = zkCfgFile + "/zoo.cfg"; } if (!new File(zkCfgFile).exists()) { LOG.error("zoo.cfg file doen't exist: " + zkCfgFile); System.exit(1); } String[] patterns = cmd.getOptionValues(pattern); String[] zkDataDirs = getZkDataDirs(zkCfgFile); // parse zk data files if (zkDataDirs == null || zkDataDirs[0] == null || zkDataDirs[1] == null) { LOG.error("invalid zkCfgDir: " + zkCfgDirValue); System.exit(1); } File zkParsedDir = new File(String.format("%s/zklog-parsed", System.getProperty("user.home"))); if (!zkParsedDir.exists()) { LOG.info("creating zklog-parsed dir: " + zkParsedDir.getAbsolutePath()); zkParsedDir.mkdirs(); } if (cmd.hasOption(between)) { String[] timeStrings = cmd.getOptionValues(between); long startTime = parseTimeString(timeStrings[0]); if (startTime == -1) { LOG.error("invalid start time string: " + timeStrings[0] + ", should be either timestamp or yyMMdd_hhmmss_SSS"); System.exit(1); } long endTime = parseTimeString(timeStrings[1]); if (endTime == -1) { LOG.error("invalid end time string: " + timeStrings[1] + ", should be either timestamp or yyMMdd_hhmmss_SSS"); System.exit(1); } if (startTime > endTime) { LOG.warn("empty window: " + startTime + " - " + endTime); System.exit(1); } // zkDataDirs[0] is the transaction log dir List<File> parsedZkLogs = parseZkLogs(zkDataDirs[0], startTime, endTime); grepZkLogDir(parsedZkLogs, startTime, endTime, patterns); } else if (cmd.hasOption(by)) { String timeString = cmd.getOptionValue(by); long byTime = parseTimeString(timeString); if (byTime == -1) { LOG.error("invalid by time string: " + timeString + ", should be either timestamp or yyMMdd_hhmmss_SSS"); System.exit(1); } // zkDataDirs[1] is the snapshot dir File[] lastZkSnapshot = parseZkSnapshot(zkDataDirs[1], byTime); // lastZkSnapshot[1] is the parsed last snapshot by byTime grepZkSnapshot(lastZkSnapshot[1], patterns); // need to grep transaction logs between last-modified-time of snapshot and byTime also // lastZkSnapshot[0] is the last snapshot by byTime long startTime = lastZkSnapshot[0].lastModified(); // zkDataDirs[0] is the transaction log dir List<File> parsedZkLogs = parseZkLogs(zkDataDirs[0], startTime, byTime); grepZkLogDir(parsedZkLogs, startTime, byTime, patterns); } } public static void main(String[] args) { processCommandLineArgs(args); } }
apache-2.0
RWTH-i5-IDSG/jamocha
src/main/java/org/jamocha/function/fwa/FunctionWithArgumentsComposite.java
1266
/* * Copyright 2002-2016 The Jamocha Team * * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.jamocha.org/ * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for * the specific language governing permissions and limitations under the License. */ package org.jamocha.function.fwa; import org.jamocha.function.Function; /** * Instantiation of {@link GenericWithArgumentsComposite} holding a Function. * * @author Fabian Ohler <fabian.ohler1@rwth-aachen.de> */ public class FunctionWithArgumentsComposite<L extends ExchangeableLeaf<L>> extends GenericWithArgumentsComposite<Object, Function<?>, L> { @SafeVarargs public FunctionWithArgumentsComposite(final Function<?> function, final FunctionWithArguments<L>... args) { super(function, args); } @Override public <T extends FunctionWithArgumentsVisitor<L>> T accept(final T visitor) { visitor.visit(this); return visitor; } }
apache-2.0
manovotn/core
environments/se/tests/src/test/java/org/jboss/weld/environment/se/test/discovery/isolation/Rorschach.java
906
/* * JBoss, Home of Professional Open Source * Copyright 2017, Red Hat, Inc., and individual contributors * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.weld.environment.se.test.discovery.isolation; @FooBinding public class Rorschach { void ping() { } }
apache-2.0
free46000/MultiItem
demo/src/main/java/com/freelib/multiitem/demo/LoadMoreActivity.java
3087
package com.freelib.multiitem.demo; import android.content.Context; import android.os.Handler; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import com.freelib.multiitem.adapter.BaseItemAdapter; import com.freelib.multiitem.demo.bean.TextBean; import com.freelib.multiitem.demo.viewholder.LoadMoreHolderManager; import com.freelib.multiitem.demo.viewholder.TextViewManager; import org.androidannotations.annotations.AfterViews; import org.androidannotations.annotations.EActivity; import org.androidannotations.annotations.ViewById; @EActivity(R.layout.layout_recycler_refresh) public class LoadMoreActivity extends AppCompatActivity { @ViewById(R.id.recyclerView) protected RecyclerView recyclerView; @ViewById(R.id.swipeRefreshLayout) protected SwipeRefreshLayout swipeRefreshLayout; private BaseItemAdapter adapter; private int currPage = 1; private int pageSize = 20; private int failTimes; public static void startActivity(Context context) { LoadMoreActivity_.intent(context).start(); } @AfterViews protected void initViews() { setTitle(R.string.load_more_title); recyclerView.setLayoutManager(new LinearLayoutManager(this)); //ๅˆๅง‹ๅŒ–adapter adapter = new BaseItemAdapter(); //ไธบXXBeanๆ•ฐๆฎๆบๆณจๅ†ŒXXManager็ฎก็†็ฑป adapter.register(TextBean.class, new TextViewManager()); adapter.addHeadItem(new TextBean("ๆˆ‘ๆ˜ฏHead View")); adapter.addFootItem(new TextBean("ๆˆ‘ๆ˜ฏFoot View")); recyclerView.setAdapter(adapter); //ๅผ€ๅฏๅŠ ่ฝฝๆ›ดๅคš่ง†ๅ›พ adapter.enableLoadMore(new LoadMoreHolderManager(this::loadData)); //ไธ‹ๆ‹‰ๅˆทๆ–ฐ่ง†ๅ›พ๏ผŒๆญคๅค„้‡‡็”จSwipeRefreshLayout swipeRefreshLayout.setOnRefreshListener(() -> refresh()); refresh(); } private void refresh() { swipeRefreshLayout.setRefreshing(true); currPage = 1; adapter.clearData(); adapter.notifyDataSetChanged(); loadData(); } /** * ๆจกๆ‹ŸๅŠ ่ฝฝๆ•ฐๆฎ * ๆ•ฐๆฎๅŠ ่ฝฝๆ—ถ้—ดๆจกๆ‹Ÿๅปถๆ—ถ1็ง’ * ๅ‰ไธคๆฌกๆˆๅŠŸ * ็ฌฌไธ‰ๆฌกๅŠ ่ฝฝๅคฑ่ดฅ * ็ฌฌๅ››ๆฌกๅŠ ่ฝฝๆˆๅŠŸ๏ผŒๅนถๅŠ ่ฝฝๆ•ฐๆฎๅฎŒๆˆ */ private void loadData() { new Handler().postDelayed(() -> { if (currPage < 3) { fillData(); adapter.setLoadCompleted(false); currPage++; } else if (currPage == 3 && failTimes == 0) { adapter.setLoadFailed(); failTimes++; } else { fillData(); adapter.setLoadCompleted(true); } swipeRefreshLayout.setRefreshing(false); }, 1000); } private void fillData() { for (int i = pageSize * (currPage - 1); i < pageSize * currPage; i++) { adapter.addDataItem(new TextBean("ๆ•ฐๆฎ" + i)); } } }
apache-2.0
taktos/dbflute-jodatime-example
src/main/java/com/example/dbflute/jodatime/bsbhv/BsMemberLoginBhv.java
65399
package com.example.dbflute.jodatime.bsbhv; import java.util.List; import org.seasar.dbflute.*; import org.seasar.dbflute.bhv.*; import org.seasar.dbflute.cbean.*; import org.seasar.dbflute.dbmeta.DBMeta; import org.seasar.dbflute.outsidesql.executor.*; import com.example.dbflute.jodatime.exbhv.*; import com.example.dbflute.jodatime.exentity.*; import com.example.dbflute.jodatime.bsentity.dbmeta.*; import com.example.dbflute.jodatime.cbean.*; /** * The behavior of MEMBER_LOGIN as TABLE. <br /> * <pre> * [primary key] * MEMBER_LOGIN_ID * * [column] * MEMBER_LOGIN_ID, MEMBER_ID, LOGIN_DATETIME, MOBILE_LOGIN_FLG, LOGIN_MEMBER_STATUS_CODE * * [sequence] * * * [identity] * MEMBER_LOGIN_ID * * [version-no] * * * [foreign table] * MEMBER, MEMBER_STATUS * * [referrer table] * * * [foreign property] * member, memberStatus * * [referrer property] * * </pre> * @author DBFlute(AutoGenerator) */ public abstract class BsMemberLoginBhv extends AbstractBehaviorWritable { // =================================================================================== // Definition // ========== /*df:beginQueryPath*/ /*df:endQueryPath*/ // =================================================================================== // Table name // ========== /** @return The name on database of table. (NotNull) */ public String getTableDbName() { return "MEMBER_LOGIN"; } // =================================================================================== // DBMeta // ====== /** @return The instance of DBMeta. (NotNull) */ public DBMeta getDBMeta() { return MemberLoginDbm.getInstance(); } /** @return The instance of DBMeta as my table type. (NotNull) */ public MemberLoginDbm getMyDBMeta() { return MemberLoginDbm.getInstance(); } // =================================================================================== // New Instance // ============ /** {@inheritDoc} */ public Entity newEntity() { return newMyEntity(); } /** {@inheritDoc} */ public ConditionBean newConditionBean() { return newMyConditionBean(); } /** @return The instance of new entity as my table type. (NotNull) */ public MemberLogin newMyEntity() { return new MemberLogin(); } /** @return The instance of new condition-bean as my table type. (NotNull) */ public MemberLoginCB newMyConditionBean() { return new MemberLoginCB(); } // =================================================================================== // Count Select // ============ /** * Select the count of uniquely-selected records by the condition-bean. {IgnorePagingCondition, IgnoreSpecifyColumn}<br /> * SpecifyColumn is ignored but you can use it only to remove text type column for union's distinct. * <pre> * MemberLoginCB cb = new MemberLoginCB(); * cb.query().setFoo...(value); * int count = memberLoginBhv.<span style="color: #FD4747">selectCount</span>(cb); * </pre> * @param cb The condition-bean of MemberLogin. (NotNull) * @return The count for the condition. (NotMinus) */ public int selectCount(MemberLoginCB cb) { return doSelectCountUniquely(cb); } protected int doSelectCountUniquely(MemberLoginCB cb) { // called by selectCount(cb) assertCBStateValid(cb); return delegateSelectCountUniquely(cb); } protected int doSelectCountPlainly(MemberLoginCB cb) { // called by selectPage(cb) assertCBStateValid(cb); return delegateSelectCountPlainly(cb); } @Override protected int doReadCount(ConditionBean cb) { return selectCount(downcast(cb)); } // =================================================================================== // Entity Select // ============= /** * Select the entity by the condition-bean. * <pre> * MemberLoginCB cb = new MemberLoginCB(); * cb.query().setFoo...(value); * MemberLogin memberLogin = memberLoginBhv.<span style="color: #FD4747">selectEntity</span>(cb); * if (memberLogin != null) { * ... = memberLogin.get...(); * } else { * ... * } * </pre> * @param cb The condition-bean of MemberLogin. (NotNull) * @return The entity selected by the condition. (NullAllowed: if no data, it returns null) * @exception org.seasar.dbflute.exception.EntityDuplicatedException When the entity has been duplicated. * @exception org.seasar.dbflute.exception.SelectEntityConditionNotFoundException When the condition for selecting an entity is not found. */ public MemberLogin selectEntity(MemberLoginCB cb) { return doSelectEntity(cb, MemberLogin.class); } protected <ENTITY extends MemberLogin> ENTITY doSelectEntity(final MemberLoginCB cb, Class<ENTITY> entityType) { assertCBStateValid(cb); return helpSelectEntityInternally(cb, entityType, new InternalSelectEntityCallback<ENTITY, MemberLoginCB>() { public List<ENTITY> callbackSelectList(MemberLoginCB cb, Class<ENTITY> entityType) { return doSelectList(cb, entityType); } }); } @Override protected Entity doReadEntity(ConditionBean cb) { return selectEntity(downcast(cb)); } /** * Select the entity by the condition-bean with deleted check. * <pre> * MemberLoginCB cb = new MemberLoginCB(); * cb.query().setFoo...(value); * MemberLogin memberLogin = memberLoginBhv.<span style="color: #FD4747">selectEntityWithDeletedCheck</span>(cb); * ... = memberLogin.get...(); <span style="color: #3F7E5E">// the entity always be not null</span> * </pre> * @param cb The condition-bean of MemberLogin. (NotNull) * @return The entity selected by the condition. (NotNull: if no data, throws exception) * @exception org.seasar.dbflute.exception.EntityAlreadyDeletedException When the entity has already been deleted. (not found) * @exception org.seasar.dbflute.exception.EntityDuplicatedException When the entity has been duplicated. * @exception org.seasar.dbflute.exception.SelectEntityConditionNotFoundException When the condition for selecting an entity is not found. */ public MemberLogin selectEntityWithDeletedCheck(MemberLoginCB cb) { return doSelectEntityWithDeletedCheck(cb, MemberLogin.class); } protected <ENTITY extends MemberLogin> ENTITY doSelectEntityWithDeletedCheck(final MemberLoginCB cb, Class<ENTITY> entityType) { assertCBStateValid(cb); return helpSelectEntityWithDeletedCheckInternally(cb, entityType, new InternalSelectEntityWithDeletedCheckCallback<ENTITY, MemberLoginCB>() { public List<ENTITY> callbackSelectList(MemberLoginCB cb, Class<ENTITY> entityType) { return doSelectList(cb, entityType); } }); } @Override protected Entity doReadEntityWithDeletedCheck(ConditionBean cb) { return selectEntityWithDeletedCheck(downcast(cb)); } /** * Select the entity by the primary-key value. * @param memberLoginId The one of primary key. (NotNull) * @return The entity selected by the PK. (NullAllowed: if no data, it returns null) * @exception org.seasar.dbflute.exception.EntityDuplicatedException When the entity has been duplicated. * @exception org.seasar.dbflute.exception.SelectEntityConditionNotFoundException When the condition for selecting an entity is not found. */ public MemberLogin selectByPKValue(Long memberLoginId) { return doSelectByPKValue(memberLoginId, MemberLogin.class); } protected <ENTITY extends MemberLogin> ENTITY doSelectByPKValue(Long memberLoginId, Class<ENTITY> entityType) { return doSelectEntity(buildPKCB(memberLoginId), entityType); } /** * Select the entity by the primary-key value with deleted check. * @param memberLoginId The one of primary key. (NotNull) * @return The entity selected by the PK. (NotNull: if no data, throws exception) * @exception org.seasar.dbflute.exception.EntityAlreadyDeletedException When the entity has already been deleted. (not found) * @exception org.seasar.dbflute.exception.EntityDuplicatedException When the entity has been duplicated. * @exception org.seasar.dbflute.exception.SelectEntityConditionNotFoundException When the condition for selecting an entity is not found. */ public MemberLogin selectByPKValueWithDeletedCheck(Long memberLoginId) { return doSelectByPKValueWithDeletedCheck(memberLoginId, MemberLogin.class); } protected <ENTITY extends MemberLogin> ENTITY doSelectByPKValueWithDeletedCheck(Long memberLoginId, Class<ENTITY> entityType) { return doSelectEntityWithDeletedCheck(buildPKCB(memberLoginId), entityType); } private MemberLoginCB buildPKCB(Long memberLoginId) { assertObjectNotNull("memberLoginId", memberLoginId); MemberLoginCB cb = newMyConditionBean(); cb.query().setMemberLoginId_Equal(memberLoginId); return cb; } // =================================================================================== // List Select // =========== /** * Select the list as result bean. * <pre> * MemberLoginCB cb = new MemberLoginCB(); * cb.query().setFoo...(value); * cb.query().addOrderBy_Bar...(); * ListResultBean&lt;MemberLogin&gt; memberLoginList = memberLoginBhv.<span style="color: #FD4747">selectList</span>(cb); * for (MemberLogin memberLogin : memberLoginList) { * ... = memberLogin.get...(); * } * </pre> * @param cb The condition-bean of MemberLogin. (NotNull) * @return The result bean of selected list. (NotNull: if no data, returns empty list) * @exception org.seasar.dbflute.exception.DangerousResultSizeException When the result size is over the specified safety size. */ public ListResultBean<MemberLogin> selectList(MemberLoginCB cb) { return doSelectList(cb, MemberLogin.class); } protected <ENTITY extends MemberLogin> ListResultBean<ENTITY> doSelectList(MemberLoginCB cb, Class<ENTITY> entityType) { assertCBStateValid(cb); assertObjectNotNull("entityType", entityType); assertSpecifyDerivedReferrerEntityProperty(cb, entityType); return helpSelectListInternally(cb, entityType, new InternalSelectListCallback<ENTITY, MemberLoginCB>() { public List<ENTITY> callbackSelectList(MemberLoginCB cb, Class<ENTITY> entityType) { return delegateSelectList(cb, entityType); } }); } @Override protected ListResultBean<? extends Entity> doReadList(ConditionBean cb) { return selectList(downcast(cb)); } // =================================================================================== // Page Select // =========== /** * Select the page as result bean. <br /> * (both count-select and paging-select are executed) * <pre> * MemberLoginCB cb = new MemberLoginCB(); * cb.query().setFoo...(value); * cb.query().addOrderBy_Bar...(); * cb.<span style="color: #FD4747">paging</span>(20, 3); <span style="color: #3F7E5E">// 20 records per a page and current page number is 3</span> * PagingResultBean&lt;MemberLogin&gt; page = memberLoginBhv.<span style="color: #FD4747">selectPage</span>(cb); * int allRecordCount = page.getAllRecordCount(); * int allPageCount = page.getAllPageCount(); * boolean isExistPrePage = page.isExistPrePage(); * boolean isExistNextPage = page.isExistNextPage(); * ... * for (MemberLogin memberLogin : page) { * ... = memberLogin.get...(); * } * </pre> * @param cb The condition-bean of MemberLogin. (NotNull) * @return The result bean of selected page. (NotNull: if no data, returns bean as empty list) * @exception org.seasar.dbflute.exception.DangerousResultSizeException When the result size is over the specified safety size. */ public PagingResultBean<MemberLogin> selectPage(MemberLoginCB cb) { return doSelectPage(cb, MemberLogin.class); } protected <ENTITY extends MemberLogin> PagingResultBean<ENTITY> doSelectPage(MemberLoginCB cb, Class<ENTITY> entityType) { assertCBStateValid(cb); assertObjectNotNull("entityType", entityType); return helpSelectPageInternally(cb, entityType, new InternalSelectPageCallback<ENTITY, MemberLoginCB>() { public int callbackSelectCount(MemberLoginCB cb) { return doSelectCountPlainly(cb); } public List<ENTITY> callbackSelectList(MemberLoginCB cb, Class<ENTITY> entityType) { return doSelectList(cb, entityType); } }); } @Override protected PagingResultBean<? extends Entity> doReadPage(ConditionBean cb) { return selectPage(downcast(cb)); } // =================================================================================== // Cursor Select // ============= /** * Select the cursor by the condition-bean. * <pre> * MemberLoginCB cb = new MemberLoginCB(); * cb.query().setFoo...(value); * memberLoginBhv.<span style="color: #FD4747">selectCursor</span>(cb, new EntityRowHandler&lt;MemberLogin&gt;() { * public void handle(MemberLogin entity) { * ... = entity.getFoo...(); * } * }); * </pre> * @param cb The condition-bean of MemberLogin. (NotNull) * @param entityRowHandler The handler of entity row of MemberLogin. (NotNull) */ public void selectCursor(MemberLoginCB cb, EntityRowHandler<MemberLogin> entityRowHandler) { doSelectCursor(cb, entityRowHandler, MemberLogin.class); } protected <ENTITY extends MemberLogin> void doSelectCursor(MemberLoginCB cb, EntityRowHandler<ENTITY> entityRowHandler, Class<ENTITY> entityType) { assertCBStateValid(cb); assertObjectNotNull("entityRowHandler<MemberLogin>", entityRowHandler); assertObjectNotNull("entityType", entityType); assertSpecifyDerivedReferrerEntityProperty(cb, entityType); helpSelectCursorInternally(cb, entityRowHandler, entityType, new InternalSelectCursorCallback<ENTITY, MemberLoginCB>() { public void callbackSelectCursor(MemberLoginCB cb, EntityRowHandler<ENTITY> entityRowHandler, Class<ENTITY> entityType) { delegateSelectCursor(cb, entityRowHandler, entityType); } public List<ENTITY> callbackSelectList(MemberLoginCB cb, Class<ENTITY> entityType) { return doSelectList(cb, entityType); } }); } // =================================================================================== // Scalar Select // ============= /** * Select the scalar value derived by a function from uniquely-selected records. <br /> * You should call a function method after this method called like as follows: * <pre> * memberLoginBhv.<span style="color: #FD4747">scalarSelect</span>(Date.class).max(new ScalarQuery() { * public void query(MemberLoginCB cb) { * cb.specify().<span style="color: #FD4747">columnFooDatetime()</span>; <span style="color: #3F7E5E">// required for a function</span> * cb.query().setBarName_PrefixSearch("S"); * } * }); * </pre> * @param <RESULT> The type of result. * @param resultType The type of result. (NotNull) * @return The scalar value derived by a function. (NullAllowed) */ public <RESULT> SLFunction<MemberLoginCB, RESULT> scalarSelect(Class<RESULT> resultType) { return doScalarSelect(resultType, newMyConditionBean()); } protected <RESULT, CB extends MemberLoginCB> SLFunction<CB, RESULT> doScalarSelect(Class<RESULT> resultType, CB cb) { assertObjectNotNull("resultType", resultType); assertCBStateValid(cb); cb.xsetupForScalarSelect(); cb.getSqlClause().disableSelectIndex(); // for when you use union return new SLFunction<CB, RESULT>(cb, resultType); } // =================================================================================== // Sequence // ======== @Override protected Number doReadNextVal() { String msg = "This table is NOT related to sequence: " + getTableDbName(); throw new UnsupportedOperationException(msg); } // =================================================================================== // Pull out Relation // ================= /** * Pull out the list of foreign table 'Member'. * @param memberLoginList The list of memberLogin. (NotNull, EmptyAllowed) * @return The list of foreign table. (NotNull, EmptyAllowed, NotNullElement) */ public List<Member> pulloutMember(List<MemberLogin> memberLoginList) { return helpPulloutInternally(memberLoginList, new InternalPulloutCallback<MemberLogin, Member>() { public Member getFr(MemberLogin e) { return e.getMember(); } public boolean hasRf() { return true; } public void setRfLs(Member e, List<MemberLogin> ls) { e.setMemberLoginList(ls); } }); } /** * Pull out the list of foreign table 'MemberStatus'. * @param memberLoginList The list of memberLogin. (NotNull, EmptyAllowed) * @return The list of foreign table. (NotNull, EmptyAllowed, NotNullElement) */ public List<MemberStatus> pulloutMemberStatus(List<MemberLogin> memberLoginList) { return helpPulloutInternally(memberLoginList, new InternalPulloutCallback<MemberLogin, MemberStatus>() { public MemberStatus getFr(MemberLogin e) { return e.getMemberStatus(); } public boolean hasRf() { return true; } public void setRfLs(MemberStatus e, List<MemberLogin> ls) { e.setMemberLoginList(ls); } }); } // =================================================================================== // Extract Column // ============== /** * Extract the value list of (single) primary key memberLoginId. * @param memberLoginList The list of memberLogin. (NotNull, EmptyAllowed) * @return The list of the column value. (NotNull, EmptyAllowed, NotNullElement) */ public List<Long> extractMemberLoginIdList(List<MemberLogin> memberLoginList) { return helpExtractListInternally(memberLoginList, new InternalExtractCallback<MemberLogin, Long>() { public Long getCV(MemberLogin e) { return e.getMemberLoginId(); } }); } // =================================================================================== // Entity Update // ============= /** * Insert the entity modified-only. (DefaultConstraintsEnabled) * <pre> * MemberLogin memberLogin = new MemberLogin(); * <span style="color: #3F7E5E">// if auto-increment, you don't need to set the PK value</span> * memberLogin.setFoo...(value); * memberLogin.setBar...(value); * <span style="color: #3F7E5E">// you don't need to set values of common columns</span> * <span style="color: #3F7E5E">//memberLogin.setRegisterUser(value);</span> * <span style="color: #3F7E5E">//memberLogin.set...;</span> * memberLoginBhv.<span style="color: #FD4747">insert</span>(memberLogin); * ... = memberLogin.getPK...(); <span style="color: #3F7E5E">// if auto-increment, you can get the value after</span> * </pre> * <p>While, when the entity is created by select, all columns are registered.</p> * @param memberLogin The entity of insert target. (NotNull, PrimaryKeyNullAllowed: when auto-increment) * @exception org.seasar.dbflute.exception.EntityAlreadyExistsException When the entity already exists. (unique constraint violation) */ public void insert(MemberLogin memberLogin) { doInsert(memberLogin, null); } protected void doInsert(MemberLogin memberLogin, InsertOption<MemberLoginCB> option) { assertObjectNotNull("memberLogin", memberLogin); prepareInsertOption(option); delegateInsert(memberLogin, option); } protected void prepareInsertOption(InsertOption<MemberLoginCB> option) { if (option == null) { return; } assertInsertOptionStatus(option); if (option.hasSpecifiedInsertColumn()) { option.resolveInsertColumnSpecification(createCBForSpecifiedUpdate()); } } @Override protected void doCreate(Entity entity, InsertOption<? extends ConditionBean> option) { if (option == null) { insert(downcast(entity)); } else { varyingInsert(downcast(entity), downcast(option)); } } /** * Update the entity modified-only. (ZeroUpdateException, NonExclusiveControl) * <pre> * MemberLogin memberLogin = new MemberLogin(); * memberLogin.setPK...(value); <span style="color: #3F7E5E">// required</span> * memberLogin.setFoo...(value); <span style="color: #3F7E5E">// you should set only modified columns</span> * <span style="color: #3F7E5E">// you don't need to set values of common columns</span> * <span style="color: #3F7E5E">//memberLogin.setRegisterUser(value);</span> * <span style="color: #3F7E5E">//memberLogin.set...;</span> * <span style="color: #3F7E5E">// if exclusive control, the value of exclusive control column is required</span> * memberLogin.<span style="color: #FD4747">setVersionNo</span>(value); * try { * memberLoginBhv.<span style="color: #FD4747">update</span>(memberLogin); * } catch (EntityAlreadyUpdatedException e) { <span style="color: #3F7E5E">// if concurrent update</span> * ... * } * </pre> * @param memberLogin The entity of update target. (NotNull, PrimaryKeyNotNull, ConcurrencyColumnRequired) * @exception org.seasar.dbflute.exception.EntityAlreadyDeletedException When the entity has already been deleted. (not found) * @exception org.seasar.dbflute.exception.EntityDuplicatedException When the entity has been duplicated. * @exception org.seasar.dbflute.exception.EntityAlreadyExistsException When the entity already exists. (unique constraint violation) */ public void update(final MemberLogin memberLogin) { doUpdate(memberLogin, null); } protected void doUpdate(MemberLogin memberLogin, final UpdateOption<MemberLoginCB> option) { assertObjectNotNull("memberLogin", memberLogin); prepareUpdateOption(option); helpUpdateInternally(memberLogin, new InternalUpdateCallback<MemberLogin>() { public int callbackDelegateUpdate(MemberLogin entity) { return delegateUpdate(entity, option); } }); } protected void prepareUpdateOption(UpdateOption<MemberLoginCB> option) { if (option == null) { return; } assertUpdateOptionStatus(option); if (option.hasSelfSpecification()) { option.resolveSelfSpecification(createCBForVaryingUpdate()); } if (option.hasSpecifiedUpdateColumn()) { option.resolveUpdateColumnSpecification(createCBForSpecifiedUpdate()); } } protected MemberLoginCB createCBForVaryingUpdate() { MemberLoginCB cb = newMyConditionBean(); cb.xsetupForVaryingUpdate(); return cb; } protected MemberLoginCB createCBForSpecifiedUpdate() { MemberLoginCB cb = newMyConditionBean(); cb.xsetupForSpecifiedUpdate(); return cb; } @Override protected void doModify(Entity entity, UpdateOption<? extends ConditionBean> option) { if (option == null) { update(downcast(entity)); } else { varyingUpdate(downcast(entity), downcast(option)); } } @Override protected void doModifyNonstrict(Entity entity, UpdateOption<? extends ConditionBean> option) { doModify(entity, option); } /** * Insert or update the entity modified-only. (DefaultConstraintsEnabled, NonExclusiveControl) <br /> * if (the entity has no PK) { insert() } else { update(), but no data, insert() } <br /> * <p><span style="color: #FD4747; font-size: 120%">Attention, you cannot update by unique keys instead of PK.</span></p> * @param memberLogin The entity of insert or update target. (NotNull) * @exception org.seasar.dbflute.exception.EntityAlreadyDeletedException When the entity has already been deleted. (not found) * @exception org.seasar.dbflute.exception.EntityDuplicatedException When the entity has been duplicated. * @exception org.seasar.dbflute.exception.EntityAlreadyExistsException When the entity already exists. (unique constraint violation) */ public void insertOrUpdate(MemberLogin memberLogin) { doInesrtOrUpdate(memberLogin, null, null); } protected void doInesrtOrUpdate(MemberLogin memberLogin, final InsertOption<MemberLoginCB> insertOption, final UpdateOption<MemberLoginCB> updateOption) { helpInsertOrUpdateInternally(memberLogin, new InternalInsertOrUpdateCallback<MemberLogin, MemberLoginCB>() { public void callbackInsert(MemberLogin entity) { doInsert(entity, insertOption); } public void callbackUpdate(MemberLogin entity) { doUpdate(entity, updateOption); } public MemberLoginCB callbackNewMyConditionBean() { return newMyConditionBean(); } public int callbackSelectCount(MemberLoginCB cb) { return selectCount(cb); } }); } @Override protected void doCreateOrModify(Entity entity, InsertOption<? extends ConditionBean> insertOption, UpdateOption<? extends ConditionBean> updateOption) { if (insertOption == null && updateOption == null) { insertOrUpdate(downcast(entity)); } else { insertOption = insertOption == null ? new InsertOption<MemberLoginCB>() : insertOption; updateOption = updateOption == null ? new UpdateOption<MemberLoginCB>() : updateOption; varyingInsertOrUpdate(downcast(entity), downcast(insertOption), downcast(updateOption)); } } @Override protected void doCreateOrModifyNonstrict(Entity entity, InsertOption<? extends ConditionBean> insertOption, UpdateOption<? extends ConditionBean> updateOption) { doCreateOrModify(entity, insertOption, updateOption); } /** * Delete the entity. (ZeroUpdateException, NonExclusiveControl) * <pre> * MemberLogin memberLogin = new MemberLogin(); * memberLogin.setPK...(value); <span style="color: #3F7E5E">// required</span> * <span style="color: #3F7E5E">// if exclusive control, the value of exclusive control column is required</span> * memberLogin.<span style="color: #FD4747">setVersionNo</span>(value); * try { * memberLoginBhv.<span style="color: #FD4747">delete</span>(memberLogin); * } catch (EntityAlreadyUpdatedException e) { <span style="color: #3F7E5E">// if concurrent update</span> * ... * } * </pre> * @param memberLogin The entity of delete target. (NotNull, PrimaryKeyNotNull, ConcurrencyColumnRequired) * @exception org.seasar.dbflute.exception.EntityAlreadyDeletedException When the entity has already been deleted. (not found) * @exception org.seasar.dbflute.exception.EntityDuplicatedException When the entity has been duplicated. */ public void delete(MemberLogin memberLogin) { doDelete(memberLogin, null); } protected void doDelete(MemberLogin memberLogin, final DeleteOption<MemberLoginCB> option) { assertObjectNotNull("memberLogin", memberLogin); prepareDeleteOption(option); helpDeleteInternally(memberLogin, new InternalDeleteCallback<MemberLogin>() { public int callbackDelegateDelete(MemberLogin entity) { return delegateDelete(entity, option); } }); } protected void prepareDeleteOption(DeleteOption<MemberLoginCB> option) { if (option == null) { return; } assertDeleteOptionStatus(option); } @Override protected void doRemove(Entity entity, DeleteOption<? extends ConditionBean> option) { if (option == null) { delete(downcast(entity)); } else { varyingDelete(downcast(entity), downcast(option)); } } @Override protected void doRemoveNonstrict(Entity entity, DeleteOption<? extends ConditionBean> option) { doRemove(entity, option); } // =================================================================================== // Batch Update // ============ /** * Batch-insert the entity list modified-only of same-set columns. (DefaultConstraintsEnabled) <br /> * This method uses executeBatch() of java.sql.PreparedStatement. <br /> * <p><span style="color: #FD4747; font-size: 120%">The columns of least common multiple are registered like this:</span></p> * <pre> * for (... : ...) { * MemberLogin memberLogin = new MemberLogin(); * memberLogin.setFooName("foo"); * if (...) { * memberLogin.setFooPrice(123); * } * <span style="color: #3F7E5E">// FOO_NAME and FOO_PRICE (and record meta columns) are registered</span> * <span style="color: #3F7E5E">// FOO_PRICE not-called in any entities are registered as null without default value</span> * <span style="color: #3F7E5E">// columns not-called in all entities are registered as null or default value</span> * memberLoginList.add(memberLogin); * } * memberLoginBhv.<span style="color: #FD4747">batchInsert</span>(memberLoginList); * </pre> * <p>While, when the entities are created by select, all columns are registered.</p> * <p>And if the table has an identity, entities after the process don't have incremented values. * (When you use the (normal) insert(), you can get the incremented value from your entity)</p> * @param memberLoginList The list of the entity. (NotNull, EmptyAllowed, PrimaryKeyNullAllowed: when auto-increment) * @return The array of inserted count. (NotNull, EmptyAllowed) */ public int[] batchInsert(List<MemberLogin> memberLoginList) { InsertOption<MemberLoginCB> option = createInsertUpdateOption(); return doBatchInsert(memberLoginList, option); } protected int[] doBatchInsert(List<MemberLogin> memberLoginList, InsertOption<MemberLoginCB> option) { assertObjectNotNull("memberLoginList", memberLoginList); prepareBatchInsertOption(memberLoginList, option); return delegateBatchInsert(memberLoginList, option); } protected void prepareBatchInsertOption(List<MemberLogin> memberLoginList, InsertOption<MemberLoginCB> option) { option.xallowInsertColumnModifiedPropertiesFragmented(); option.xacceptInsertColumnModifiedPropertiesIfNeeds(memberLoginList); prepareInsertOption(option); } @Override protected int[] doLumpCreate(List<Entity> ls, InsertOption<? extends ConditionBean> option) { if (option == null) { return batchInsert(downcast(ls)); } else { return varyingBatchInsert(downcast(ls), downcast(option)); } } /** * Batch-update the entity list modified-only of same-set columns. (NonExclusiveControl) <br /> * This method uses executeBatch() of java.sql.PreparedStatement. <br /> * <span style="color: #FD4747; font-size: 120%">You should specify same-set columns to all entities like this:</span> * <pre> * for (... : ...) { * MemberLogin memberLogin = new MemberLogin(); * memberLogin.setFooName("foo"); * if (...) { * memberLogin.setFooPrice(123); * } else { * memberLogin.setFooPrice(null); <span style="color: #3F7E5E">// updated as null</span> * <span style="color: #3F7E5E">//memberLogin.setFooDate(...); // *not allowed, fragmented</span> * } * <span style="color: #3F7E5E">// FOO_NAME and FOO_PRICE (and record meta columns) are updated</span> * <span style="color: #3F7E5E">// (others are not updated: their values are kept)</span> * memberLoginList.add(memberLogin); * } * memberLoginBhv.<span style="color: #FD4747">batchUpdate</span>(memberLoginList); * </pre> * @param memberLoginList The list of the entity. (NotNull, EmptyAllowed, PrimaryKeyNotNull) * @return The array of updated count. (NotNull, EmptyAllowed) * @exception org.seasar.dbflute.exception.EntityAlreadyDeletedException When the entity has already been deleted. (not found) */ public int[] batchUpdate(List<MemberLogin> memberLoginList) { UpdateOption<MemberLoginCB> option = createPlainUpdateOption(); return doBatchUpdate(memberLoginList, option); } protected int[] doBatchUpdate(List<MemberLogin> memberLoginList, UpdateOption<MemberLoginCB> option) { assertObjectNotNull("memberLoginList", memberLoginList); prepareBatchUpdateOption(memberLoginList, option); return delegateBatchUpdate(memberLoginList, option); } protected void prepareBatchUpdateOption(List<MemberLogin> memberLoginList, UpdateOption<MemberLoginCB> option) { option.xacceptUpdateColumnModifiedPropertiesIfNeeds(memberLoginList); prepareUpdateOption(option); } @Override protected int[] doLumpModify(List<Entity> ls, UpdateOption<? extends ConditionBean> option) { if (option == null) { return batchUpdate(downcast(ls)); } else { return varyingBatchUpdate(downcast(ls), downcast(option)); } } /** * Batch-update the entity list specified-only. (NonExclusiveControl) <br /> * This method uses executeBatch() of java.sql.PreparedStatement. * <pre> * <span style="color: #3F7E5E">// e.g. update two columns only</span> * memberLoginBhv.<span style="color: #FD4747">batchUpdate</span>(memberLoginList, new SpecifyQuery<MemberLoginCB>() { * public void specify(MemberLoginCB cb) { <span style="color: #3F7E5E">// the two only updated</span> * cb.specify().<span style="color: #FD4747">columnFooStatusCode()</span>; <span style="color: #3F7E5E">// should be modified in any entities</span> * cb.specify().<span style="color: #FD4747">columnBarDate()</span>; <span style="color: #3F7E5E">// should be modified in any entities</span> * } * }); * <span style="color: #3F7E5E">// e.g. update every column in the table</span> * memberLoginBhv.<span style="color: #FD4747">batchUpdate</span>(memberLoginList, new SpecifyQuery<MemberLoginCB>() { * public void specify(MemberLoginCB cb) { <span style="color: #3F7E5E">// all columns are updated</span> * cb.specify().<span style="color: #FD4747">columnEveryColumn()</span>; <span style="color: #3F7E5E">// no check of modified properties</span> * } * }); * </pre> * <p>You can specify update columns used on set clause of update statement. * However you do not need to specify common columns for update * and an optimistic lock column because they are specified implicitly.</p> * <p>And you should specify columns that are modified in any entities (at least one entity). * But if you specify every column, it has no check.</p> * @param memberLoginList The list of the entity. (NotNull, EmptyAllowed, PrimaryKeyNotNull) * @param updateColumnSpec The specification of update columns. (NotNull) * @return The array of updated count. (NotNull, EmptyAllowed) * @exception org.seasar.dbflute.exception.EntityAlreadyDeletedException When the entity has already been deleted. (not found) */ public int[] batchUpdate(List<MemberLogin> memberLoginList, SpecifyQuery<MemberLoginCB> updateColumnSpec) { return doBatchUpdate(memberLoginList, createSpecifiedUpdateOption(updateColumnSpec)); } @Override protected int[] doLumpModifyNonstrict(List<Entity> ls, UpdateOption<? extends ConditionBean> option) { return doLumpModify(ls, option); } /** * Batch-delete the entity list. (NonExclusiveControl) <br /> * This method uses executeBatch() of java.sql.PreparedStatement. * @param memberLoginList The list of the entity. (NotNull, EmptyAllowed, PrimaryKeyNotNull) * @return The array of deleted count. (NotNull, EmptyAllowed) * @exception org.seasar.dbflute.exception.EntityAlreadyDeletedException When the entity has already been deleted. (not found) */ public int[] batchDelete(List<MemberLogin> memberLoginList) { return doBatchDelete(memberLoginList, null); } protected int[] doBatchDelete(List<MemberLogin> memberLoginList, DeleteOption<MemberLoginCB> option) { assertObjectNotNull("memberLoginList", memberLoginList); prepareDeleteOption(option); return delegateBatchDelete(memberLoginList, option); } @Override protected int[] doLumpRemove(List<Entity> ls, DeleteOption<? extends ConditionBean> option) { if (option == null) { return batchDelete(downcast(ls)); } else { return varyingBatchDelete(downcast(ls), downcast(option)); } } @Override protected int[] doLumpRemoveNonstrict(List<Entity> ls, DeleteOption<? extends ConditionBean> option) { return doLumpRemove(ls, option); } // =================================================================================== // Query Update // ============ /** * Insert the several entities by query (modified-only for fixed value). * <pre> * memberLoginBhv.<span style="color: #FD4747">queryInsert</span>(new QueryInsertSetupper&lt;MemberLogin, MemberLoginCB&gt;() { * public ConditionBean setup(memberLogin entity, MemberLoginCB intoCB) { * FooCB cb = FooCB(); * cb.setupSelect_Bar(); * * <span style="color: #3F7E5E">// mapping</span> * intoCB.specify().columnMyName().mappedFrom(cb.specify().columnFooName()); * intoCB.specify().columnMyCount().mappedFrom(cb.specify().columnFooCount()); * intoCB.specify().columnMyDate().mappedFrom(cb.specify().specifyBar().columnBarDate()); * entity.setMyFixedValue("foo"); <span style="color: #3F7E5E">// fixed value</span> * <span style="color: #3F7E5E">// you don't need to set values of common columns</span> * <span style="color: #3F7E5E">//entity.setRegisterUser(value);</span> * <span style="color: #3F7E5E">//entity.set...;</span> * <span style="color: #3F7E5E">// you don't need to set a value of exclusive control column</span> * <span style="color: #3F7E5E">//entity.setVersionNo(value);</span> * * return cb; * } * }); * </pre> * @param setupper The setup-per of query-insert. (NotNull) * @return The inserted count. */ public int queryInsert(QueryInsertSetupper<MemberLogin, MemberLoginCB> setupper) { return doQueryInsert(setupper, null); } protected int doQueryInsert(QueryInsertSetupper<MemberLogin, MemberLoginCB> setupper, InsertOption<MemberLoginCB> option) { assertObjectNotNull("setupper", setupper); prepareInsertOption(option); MemberLogin entity = new MemberLogin(); MemberLoginCB intoCB = createCBForQueryInsert(); ConditionBean resourceCB = setupper.setup(entity, intoCB); return delegateQueryInsert(entity, intoCB, resourceCB, option); } protected MemberLoginCB createCBForQueryInsert() { MemberLoginCB cb = newMyConditionBean(); cb.xsetupForQueryInsert(); return cb; } @Override protected int doRangeCreate(QueryInsertSetupper<? extends Entity, ? extends ConditionBean> setupper, InsertOption<? extends ConditionBean> option) { if (option == null) { return queryInsert(downcast(setupper)); } else { return varyingQueryInsert(downcast(setupper), downcast(option)); } } /** * Update the several entities by query non-strictly modified-only. (NonExclusiveControl) * <pre> * MemberLogin memberLogin = new MemberLogin(); * <span style="color: #3F7E5E">// you don't need to set PK value</span> * <span style="color: #3F7E5E">//memberLogin.setPK...(value);</span> * memberLogin.setFoo...(value); <span style="color: #3F7E5E">// you should set only modified columns</span> * <span style="color: #3F7E5E">// you don't need to set values of common columns</span> * <span style="color: #3F7E5E">//memberLogin.setRegisterUser(value);</span> * <span style="color: #3F7E5E">//memberLogin.set...;</span> * <span style="color: #3F7E5E">// you don't need to set a value of exclusive control column</span> * <span style="color: #3F7E5E">// (auto-increment for version number is valid though non-exclusive control)</span> * <span style="color: #3F7E5E">//memberLogin.setVersionNo(value);</span> * MemberLoginCB cb = new MemberLoginCB(); * cb.query().setFoo...(value); * memberLoginBhv.<span style="color: #FD4747">queryUpdate</span>(memberLogin, cb); * </pre> * @param memberLogin The entity that contains update values. (NotNull, PrimaryKeyNullAllowed) * @param cb The condition-bean of MemberLogin. (NotNull) * @return The updated count. * @exception org.seasar.dbflute.exception.NonQueryUpdateNotAllowedException When the query has no condition. */ public int queryUpdate(MemberLogin memberLogin, MemberLoginCB cb) { return doQueryUpdate(memberLogin, cb, null); } protected int doQueryUpdate(MemberLogin memberLogin, MemberLoginCB cb, UpdateOption<MemberLoginCB> option) { assertObjectNotNull("memberLogin", memberLogin); assertCBStateValid(cb); prepareUpdateOption(option); return checkCountBeforeQueryUpdateIfNeeds(cb) ? delegateQueryUpdate(memberLogin, cb, option) : 0; } @Override protected int doRangeModify(Entity entity, ConditionBean cb, UpdateOption<? extends ConditionBean> option) { if (option == null) { return queryUpdate(downcast(entity), (MemberLoginCB)cb); } else { return varyingQueryUpdate(downcast(entity), (MemberLoginCB)cb, downcast(option)); } } /** * Delete the several entities by query. (NonExclusiveControl) * <pre> * MemberLoginCB cb = new MemberLoginCB(); * cb.query().setFoo...(value); * memberLoginBhv.<span style="color: #FD4747">queryDelete</span>(memberLogin, cb); * </pre> * @param cb The condition-bean of MemberLogin. (NotNull) * @return The deleted count. * @exception org.seasar.dbflute.exception.NonQueryDeleteNotAllowedException When the query has no condition. */ public int queryDelete(MemberLoginCB cb) { return doQueryDelete(cb, null); } protected int doQueryDelete(MemberLoginCB cb, DeleteOption<MemberLoginCB> option) { assertCBStateValid(cb); prepareDeleteOption(option); return checkCountBeforeQueryUpdateIfNeeds(cb) ? delegateQueryDelete(cb, option) : 0; } @Override protected int doRangeRemove(ConditionBean cb, DeleteOption<? extends ConditionBean> option) { if (option == null) { return queryDelete((MemberLoginCB)cb); } else { return varyingQueryDelete((MemberLoginCB)cb, downcast(option)); } } // =================================================================================== // Varying Update // ============== // ----------------------------------------------------- // Entity Update // ------------- /** * Insert the entity with varying requests. <br /> * For example, disableCommonColumnAutoSetup(), disablePrimaryKeyIdentity(). <br /> * Other specifications are same as insert(entity). * <pre> * MemberLogin memberLogin = new MemberLogin(); * <span style="color: #3F7E5E">// if auto-increment, you don't need to set the PK value</span> * memberLogin.setFoo...(value); * memberLogin.setBar...(value); * InsertOption<MemberLoginCB> option = new InsertOption<MemberLoginCB>(); * <span style="color: #3F7E5E">// you can insert by your values for common columns</span> * option.disableCommonColumnAutoSetup(); * memberLoginBhv.<span style="color: #FD4747">varyingInsert</span>(memberLogin, option); * ... = memberLogin.getPK...(); <span style="color: #3F7E5E">// if auto-increment, you can get the value after</span> * </pre> * @param memberLogin The entity of insert target. (NotNull, PrimaryKeyNullAllowed: when auto-increment) * @param option The option of insert for varying requests. (NotNull) * @exception org.seasar.dbflute.exception.EntityAlreadyExistsException When the entity already exists. (unique constraint violation) */ public void varyingInsert(MemberLogin memberLogin, InsertOption<MemberLoginCB> option) { assertInsertOptionNotNull(option); doInsert(memberLogin, option); } /** * Update the entity with varying requests modified-only. (ZeroUpdateException, NonExclusiveControl) <br /> * For example, self(selfCalculationSpecification), specify(updateColumnSpecification), disableCommonColumnAutoSetup(). <br /> * Other specifications are same as update(entity). * <pre> * MemberLogin memberLogin = new MemberLogin(); * memberLogin.setPK...(value); <span style="color: #3F7E5E">// required</span> * memberLogin.setOther...(value); <span style="color: #3F7E5E">// you should set only modified columns</span> * <span style="color: #3F7E5E">// if exclusive control, the value of exclusive control column is required</span> * memberLogin.<span style="color: #FD4747">setVersionNo</span>(value); * try { * <span style="color: #3F7E5E">// you can update by self calculation values</span> * UpdateOption&lt;MemberLoginCB&gt; option = new UpdateOption&lt;MemberLoginCB&gt;(); * option.self(new SpecifyQuery&lt;MemberLoginCB&gt;() { * public void specify(MemberLoginCB cb) { * cb.specify().<span style="color: #FD4747">columnXxxCount()</span>; * } * }).plus(1); <span style="color: #3F7E5E">// XXX_COUNT = XXX_COUNT + 1</span> * memberLoginBhv.<span style="color: #FD4747">varyingUpdate</span>(memberLogin, option); * } catch (EntityAlreadyUpdatedException e) { <span style="color: #3F7E5E">// if concurrent update</span> * ... * } * </pre> * @param memberLogin The entity of update target. (NotNull, PrimaryKeyNotNull, ConcurrencyColumnRequired) * @param option The option of update for varying requests. (NotNull) * @exception org.seasar.dbflute.exception.EntityAlreadyDeletedException When the entity has already been deleted. (not found) * @exception org.seasar.dbflute.exception.EntityDuplicatedException When the entity has been duplicated. * @exception org.seasar.dbflute.exception.EntityAlreadyExistsException When the entity already exists. (unique constraint violation) */ public void varyingUpdate(MemberLogin memberLogin, UpdateOption<MemberLoginCB> option) { assertUpdateOptionNotNull(option); doUpdate(memberLogin, option); } /** * Insert or update the entity with varying requests. (ExclusiveControl: when update) <br /> * Other specifications are same as insertOrUpdate(entity). * @param memberLogin The entity of insert or update target. (NotNull) * @param insertOption The option of insert for varying requests. (NotNull) * @param updateOption The option of update for varying requests. (NotNull) * @exception org.seasar.dbflute.exception.EntityAlreadyDeletedException When the entity has already been deleted. (not found) * @exception org.seasar.dbflute.exception.EntityDuplicatedException When the entity has been duplicated. * @exception org.seasar.dbflute.exception.EntityAlreadyExistsException When the entity already exists. (unique constraint violation) */ public void varyingInsertOrUpdate(MemberLogin memberLogin, InsertOption<MemberLoginCB> insertOption, UpdateOption<MemberLoginCB> updateOption) { assertInsertOptionNotNull(insertOption); assertUpdateOptionNotNull(updateOption); doInesrtOrUpdate(memberLogin, insertOption, updateOption); } /** * Delete the entity with varying requests. (ZeroUpdateException, NonExclusiveControl) <br /> * Now a valid option does not exist. <br /> * Other specifications are same as delete(entity). * @param memberLogin The entity of delete target. (NotNull, PrimaryKeyNotNull, ConcurrencyColumnRequired) * @param option The option of update for varying requests. (NotNull) * @exception org.seasar.dbflute.exception.EntityAlreadyDeletedException When the entity has already been deleted. (not found) * @exception org.seasar.dbflute.exception.EntityDuplicatedException When the entity has been duplicated. */ public void varyingDelete(MemberLogin memberLogin, DeleteOption<MemberLoginCB> option) { assertDeleteOptionNotNull(option); doDelete(memberLogin, option); } // ----------------------------------------------------- // Batch Update // ------------ /** * Batch-insert the list with varying requests. <br /> * For example, disableCommonColumnAutoSetup() * , disablePrimaryKeyIdentity(), limitBatchInsertLogging(). <br /> * Other specifications are same as batchInsert(entityList). * @param memberLoginList The list of the entity. (NotNull, EmptyAllowed, PrimaryKeyNotNull) * @param option The option of insert for varying requests. (NotNull) * @return The array of updated count. (NotNull, EmptyAllowed) */ public int[] varyingBatchInsert(List<MemberLogin> memberLoginList, InsertOption<MemberLoginCB> option) { assertInsertOptionNotNull(option); return doBatchInsert(memberLoginList, option); } /** * Batch-update the list with varying requests. <br /> * For example, self(selfCalculationSpecification), specify(updateColumnSpecification) * , disableCommonColumnAutoSetup(), limitBatchUpdateLogging(). <br /> * Other specifications are same as batchUpdate(entityList). * @param memberLoginList The list of the entity. (NotNull, EmptyAllowed, PrimaryKeyNotNull) * @param option The option of update for varying requests. (NotNull) * @return The array of updated count. (NotNull, EmptyAllowed) */ public int[] varyingBatchUpdate(List<MemberLogin> memberLoginList, UpdateOption<MemberLoginCB> option) { assertUpdateOptionNotNull(option); return doBatchUpdate(memberLoginList, option); } /** * Batch-delete the list with varying requests. <br /> * For example, limitBatchDeleteLogging(). <br /> * Other specifications are same as batchDelete(entityList). * @param memberLoginList The list of the entity. (NotNull, EmptyAllowed, PrimaryKeyNotNull) * @param option The option of delete for varying requests. (NotNull) * @return The array of deleted count. (NotNull, EmptyAllowed) */ public int[] varyingBatchDelete(List<MemberLogin> memberLoginList, DeleteOption<MemberLoginCB> option) { assertDeleteOptionNotNull(option); return doBatchDelete(memberLoginList, option); } // ----------------------------------------------------- // Query Update // ------------ /** * Insert the several entities by query with varying requests (modified-only for fixed value). <br /> * For example, disableCommonColumnAutoSetup(), disablePrimaryKeyIdentity(). <br /> * Other specifications are same as queryInsert(entity, setupper). * @param setupper The setup-per of query-insert. (NotNull) * @param option The option of insert for varying requests. (NotNull) * @return The inserted count. */ public int varyingQueryInsert(QueryInsertSetupper<MemberLogin, MemberLoginCB> setupper, InsertOption<MemberLoginCB> option) { assertInsertOptionNotNull(option); return doQueryInsert(setupper, option); } /** * Update the several entities by query with varying requests non-strictly modified-only. {NonExclusiveControl} <br /> * For example, self(selfCalculationSpecification), specify(updateColumnSpecification) * , disableCommonColumnAutoSetup(), allowNonQueryUpdate(). <br /> * Other specifications are same as queryUpdate(entity, cb). * <pre> * <span style="color: #3F7E5E">// ex) you can update by self calculation values</span> * MemberLogin memberLogin = new MemberLogin(); * <span style="color: #3F7E5E">// you don't need to set PK value</span> * <span style="color: #3F7E5E">//memberLogin.setPK...(value);</span> * memberLogin.setOther...(value); <span style="color: #3F7E5E">// you should set only modified columns</span> * <span style="color: #3F7E5E">// you don't need to set a value of exclusive control column</span> * <span style="color: #3F7E5E">// (auto-increment for version number is valid though non-exclusive control)</span> * <span style="color: #3F7E5E">//memberLogin.setVersionNo(value);</span> * MemberLoginCB cb = new MemberLoginCB(); * cb.query().setFoo...(value); * UpdateOption&lt;MemberLoginCB&gt; option = new UpdateOption&lt;MemberLoginCB&gt;(); * option.self(new SpecifyQuery&lt;MemberLoginCB&gt;() { * public void specify(MemberLoginCB cb) { * cb.specify().<span style="color: #FD4747">columnFooCount()</span>; * } * }).plus(1); <span style="color: #3F7E5E">// FOO_COUNT = FOO_COUNT + 1</span> * memberLoginBhv.<span style="color: #FD4747">varyingQueryUpdate</span>(memberLogin, cb, option); * </pre> * @param memberLogin The entity that contains update values. (NotNull) {PrimaryKeyNotRequired} * @param cb The condition-bean of MemberLogin. (NotNull) * @param option The option of update for varying requests. (NotNull) * @return The updated count. * @exception org.seasar.dbflute.exception.NonQueryUpdateNotAllowedException When the query has no condition (if not allowed). */ public int varyingQueryUpdate(MemberLogin memberLogin, MemberLoginCB cb, UpdateOption<MemberLoginCB> option) { assertUpdateOptionNotNull(option); return doQueryUpdate(memberLogin, cb, option); } /** * Delete the several entities by query with varying requests non-strictly. <br /> * For example, allowNonQueryDelete(). <br /> * Other specifications are same as batchUpdateNonstrict(entityList). * @param cb The condition-bean of MemberLogin. (NotNull) * @param option The option of delete for varying requests. (NotNull) * @return The deleted count. * @exception org.seasar.dbflute.exception.NonQueryDeleteNotAllowedException When the query has no condition (if not allowed). */ public int varyingQueryDelete(MemberLoginCB cb, DeleteOption<MemberLoginCB> option) { assertDeleteOptionNotNull(option); return doQueryDelete(cb, option); } // =================================================================================== // OutsideSql // ========== /** * Prepare the basic executor of outside-SQL to execute it. <br /> * The invoker of behavior command should be not null when you call this method. * <pre> * You can use the methods for outside-SQL are as follows: * {Basic} * o selectList() * o execute() * o call() * * {Entity} * o entityHandling().selectEntity() * o entityHandling().selectEntityWithDeletedCheck() * * {Paging} * o autoPaging().selectList() * o autoPaging().selectPage() * o manualPaging().selectList() * o manualPaging().selectPage() * * {Cursor} * o cursorHandling().selectCursor() * * {Option} * o dynamicBinding().selectList() * o removeBlockComment().selectList() * o removeLineComment().selectList() * o formatSql().selectList() * </pre> * @return The basic executor of outside-SQL. (NotNull) */ public OutsideSqlBasicExecutor<MemberLoginBhv> outsideSql() { return doOutsideSql(); } // =================================================================================== // Delegate Method // =============== // [Behavior Command] // ----------------------------------------------------- // Select // ------ protected int delegateSelectCountUniquely(MemberLoginCB cb) { return invoke(createSelectCountCBCommand(cb, true)); } protected int delegateSelectCountPlainly(MemberLoginCB cb) { return invoke(createSelectCountCBCommand(cb, false)); } protected <ENTITY extends MemberLogin> void delegateSelectCursor(MemberLoginCB cb, EntityRowHandler<ENTITY> erh, Class<ENTITY> et) { invoke(createSelectCursorCBCommand(cb, erh, et)); } protected <ENTITY extends MemberLogin> List<ENTITY> delegateSelectList(MemberLoginCB cb, Class<ENTITY> et) { return invoke(createSelectListCBCommand(cb, et)); } // ----------------------------------------------------- // Update // ------ protected int delegateInsert(MemberLogin e, InsertOption<MemberLoginCB> op) { if (!processBeforeInsert(e, op)) { return 0; } return invoke(createInsertEntityCommand(e, op)); } protected int delegateUpdate(MemberLogin e, UpdateOption<MemberLoginCB> op) { if (!processBeforeUpdate(e, op)) { return 0; } return delegateUpdateNonstrict(e, op); } protected int delegateUpdateNonstrict(MemberLogin e, UpdateOption<MemberLoginCB> op) { if (!processBeforeUpdate(e, op)) { return 0; } return invoke(createUpdateNonstrictEntityCommand(e, op)); } protected int delegateDelete(MemberLogin e, DeleteOption<MemberLoginCB> op) { if (!processBeforeDelete(e, op)) { return 0; } return delegateDeleteNonstrict(e, op); } protected int delegateDeleteNonstrict(MemberLogin e, DeleteOption<MemberLoginCB> op) { if (!processBeforeDelete(e, op)) { return 0; } return invoke(createDeleteNonstrictEntityCommand(e, op)); } protected int[] delegateBatchInsert(List<MemberLogin> ls, InsertOption<MemberLoginCB> op) { if (ls.isEmpty()) { return new int[]{}; } return invoke(createBatchInsertCommand(processBatchInternally(ls, op), op)); } protected int[] delegateBatchUpdate(List<MemberLogin> ls, UpdateOption<MemberLoginCB> op) { if (ls.isEmpty()) { return new int[]{}; } return delegateBatchUpdateNonstrict(ls, op); } protected int[] delegateBatchUpdateNonstrict(List<MemberLogin> ls, UpdateOption<MemberLoginCB> op) { if (ls.isEmpty()) { return new int[]{}; } return invoke(createBatchUpdateNonstrictCommand(processBatchInternally(ls, op, true), op)); } protected int[] delegateBatchDelete(List<MemberLogin> ls, DeleteOption<MemberLoginCB> op) { if (ls.isEmpty()) { return new int[]{}; } return delegateBatchDeleteNonstrict(ls, op); } protected int[] delegateBatchDeleteNonstrict(List<MemberLogin> ls, DeleteOption<MemberLoginCB> op) { if (ls.isEmpty()) { return new int[]{}; } return invoke(createBatchDeleteNonstrictCommand(processBatchInternally(ls, op, true), op)); } protected int delegateQueryInsert(MemberLogin e, MemberLoginCB inCB, ConditionBean resCB, InsertOption<MemberLoginCB> op) { if (!processBeforeQueryInsert(e, inCB, resCB, op)) { return 0; } return invoke(createQueryInsertCBCommand(e, inCB, resCB, op)); } protected int delegateQueryUpdate(MemberLogin e, MemberLoginCB cb, UpdateOption<MemberLoginCB> op) { if (!processBeforeQueryUpdate(e, cb, op)) { return 0; } return invoke(createQueryUpdateCBCommand(e, cb, op)); } protected int delegateQueryDelete(MemberLoginCB cb, DeleteOption<MemberLoginCB> op) { if (!processBeforeQueryDelete(cb, op)) { return 0; } return invoke(createQueryDeleteCBCommand(cb, op)); } // =================================================================================== // Optimistic Lock Info // ==================== /** * {@inheritDoc} */ @Override protected boolean hasVersionNoValue(Entity entity) { return false; } /** * {@inheritDoc} */ @Override protected boolean hasUpdateDateValue(Entity entity) { return false; } // =================================================================================== // Downcast Helper // =============== protected MemberLogin downcast(Entity entity) { return helpEntityDowncastInternally(entity, MemberLogin.class); } protected MemberLoginCB downcast(ConditionBean cb) { return helpConditionBeanDowncastInternally(cb, MemberLoginCB.class); } @SuppressWarnings("unchecked") protected List<MemberLogin> downcast(List<? extends Entity> entityList) { return (List<MemberLogin>)entityList; } @SuppressWarnings("unchecked") protected InsertOption<MemberLoginCB> downcast(InsertOption<? extends ConditionBean> option) { return (InsertOption<MemberLoginCB>)option; } @SuppressWarnings("unchecked") protected UpdateOption<MemberLoginCB> downcast(UpdateOption<? extends ConditionBean> option) { return (UpdateOption<MemberLoginCB>)option; } @SuppressWarnings("unchecked") protected DeleteOption<MemberLoginCB> downcast(DeleteOption<? extends ConditionBean> option) { return (DeleteOption<MemberLoginCB>)option; } @SuppressWarnings("unchecked") protected QueryInsertSetupper<MemberLogin, MemberLoginCB> downcast(QueryInsertSetupper<? extends Entity, ? extends ConditionBean> option) { return (QueryInsertSetupper<MemberLogin, MemberLoginCB>)option; } }
apache-2.0
dremio/dremio-oss
plugins/gcs/src/main/java/com/dremio/plugins/gcs/GCSAsyncClient.java
1711
/* * Copyright (C) 2017-2019 Dremio Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.dremio.plugins.gcs; import java.io.Closeable; import java.io.IOException; import java.util.Collections; import org.apache.hadoop.fs.Path; import org.asynchttpclient.AsyncHttpClient; import com.dremio.http.AsyncHttpClientProvider; import com.dremio.io.AsyncByteReader; import com.google.auth.oauth2.GoogleCredentials; /** * Helper class for constructor and maintaining AsyncHttpClients. */ class GCSAsyncClient implements Closeable { private static final String SCOPE = "https://www.googleapis.com/auth/devstorage.full_control"; private final AsyncHttpClient asyncHttpClient; private final GoogleCredentials credentials; public GCSAsyncClient(String name, GoogleCredentials credentials) throws IOException { this.credentials = credentials.createScoped(Collections.singletonList(SCOPE)); asyncHttpClient = AsyncHttpClientProvider.getInstance(); } public AsyncByteReader newByteReader(Path path, String version) { return new GCSAsyncFileReader(asyncHttpClient, path, version, credentials); } @Override public void close() throws IOException { } }
apache-2.0
LiuJiJiJi/Spring-Boot-example
Thread/src.main.java/com/mobin/thread/Executor/HeartBeat.java
705
package com.mobin.thread.Executor; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; /** * Created by Mobin on 2016/4/26. * ไฝฟ็”จnewScheduledThreadPoolๆฅๆจกๆ‹Ÿๅฟƒ่ทณๆœบๅˆถ */ public class HeartBeat { public static void main(String[] args) { ScheduledExecutorService executor = Executors.newScheduledThreadPool(5); Runnable task = new Runnable() { public void run() { System.out.println("HeartBeat........................."); } }; executor.scheduleAtFixedRate(task,5,3, TimeUnit.SECONDS); } }
apache-2.0
johrstrom/cloud-meter
cloud-meter-core/src/main/java/org/apache/jmeter/samplers/AsynchSampleSender.java
5969
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.jmeter.samplers; import java.io.ObjectStreamException; import java.io.Serializable; import java.rmi.RemoteException; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import org.apache.jmeter.util.JMeterUtils; import org.apache.jorphan.util.JMeterError; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Sends samples in a separate Thread and in Batch mode */ public class AsynchSampleSender extends AbstractSampleSender implements Serializable { private static final long serialVersionUID = 251L; private static final Logger log = LoggerFactory.getLogger(AsynchSampleSender.class); // Create unique object as marker for end of queue private transient static final SampleEvent FINAL_EVENT = new SampleEvent(); private static final int DEFAULT_QUEUE_SIZE = 100; private static final int serverConfiguredCapacity = JMeterUtils.getPropDefault("asynch.batch.queue.size", DEFAULT_QUEUE_SIZE); // $NON-NLS-1$ private final int clientConfiguredCapacity = JMeterUtils.getPropDefault("asynch.batch.queue.size", DEFAULT_QUEUE_SIZE); // $NON-NLS-1$ // created by client private final RemoteSampleListener listener; private transient BlockingQueue<SampleEvent> queue; // created by server in readResolve method private transient long queueWaits; // how many times we had to wait to queue a sample private transient long queueWaitTime; // how long we had to wait (nanoSeconds) /** * Processed by the RMI server code. * * @return this * @throws ObjectStreamException never */ private Object readResolve() throws ObjectStreamException{ int capacity = getCapacity(); log.info("Using batch queue size (asynch.batch.queue.size): " + capacity); // server log file queue = new ArrayBlockingQueue<>(capacity); Worker worker = new Worker(queue, listener); worker.setDaemon(true); worker.start(); return this; } /** * @deprecated only for use by test code */ @Deprecated public AsynchSampleSender(){ this(null); log.warn("Constructor only intended for use in testing"); // $NON-NLS-1$ } // Created by SampleSenderFactory protected AsynchSampleSender(RemoteSampleListener listener) { this.listener = listener; log.info("Using Asynch Remote Sampler for this test run, queue size "+getCapacity()); // client log file } /** * @return capacity */ private int getCapacity() { return isClientConfigured() ? clientConfiguredCapacity : serverConfiguredCapacity; } @Override public void testEnded(String host) { log.debug("Test Ended on " + host); try { listener.testEnded(host); queue.put(FINAL_EVENT); } catch (Exception ex) { log.warn("testEnded(host)"+ex); } if (queueWaits > 0) { log.info("QueueWaits: "+queueWaits+"; QueueWaitTime: "+queueWaitTime+" (nanoseconds)"); } } @Override public void sampleOccurred(SampleEvent e) { try { if (!queue.offer(e)){ // we failed to add the element first time queueWaits++; long t1 = System.nanoTime(); queue.put(e); long t2 = System.nanoTime(); queueWaitTime += t2-t1; } } catch (Exception err) { log.error("sampleOccurred; failed to queue the sample", err); } } private static class Worker extends Thread { private final BlockingQueue<SampleEvent> queue; private final RemoteSampleListener listener; private Worker(BlockingQueue<SampleEvent> q, RemoteSampleListener l){ queue = q; listener = l; } @Override public void run() { try { boolean eof = false; while (!eof) { List<SampleEvent> l = new ArrayList<>(); SampleEvent e = queue.take(); while (!(eof = (e == FINAL_EVENT)) && e != null) { // try to process as many as possible l.add(e); e = queue.poll(); // returns null if nothing on queue currently } int size = l.size(); if (size > 0) { try { listener.processBatch(l); } catch (RemoteException err) { if (err.getCause() instanceof java.net.ConnectException){ throw new JMeterError("Could not return sample",err); } log.error("Failed to return sample", err); } } } } catch (InterruptedException e) { } log.debug("Worker ended"); } } }
apache-2.0
metaborg/spoofax
org.metaborg.core/src/main/java/org/metaborg/core/messages/MessageUtils.java
746
package org.metaborg.core.messages; public class MessageUtils { public static MessageSeverity highestSeverity(Iterable<IMessage> messages) { MessageSeverity maxSeverity = MessageSeverity.NOTE; for(IMessage message : messages) { final MessageSeverity severity = message.severity(); if(severity.value > maxSeverity.value) { maxSeverity = severity; } } return maxSeverity; } public static boolean containsSeverity(Iterable<IMessage> messages, MessageSeverity severity) { for(IMessage message : messages) { if(message.severity().equals(severity)) { return true; } } return false; } }
apache-2.0
MarcosDiegoAzevedo/cachback
cashback-core-model/src/main/java/br/com/cashback/core/model/movimento/Transacao.java
5311
package br.com.cashback.core.model.movimento; import br.com.cashback.core.model.cadastro.Estabelecimento; import br.com.cashback.core.model.cadastro.Usuario; import org.hibernate.annotations.GenericGenerator; import javax.persistence.*; import javax.validation.constraints.Digits; import java.io.Serializable; import java.math.BigDecimal; import java.util.Date; /** * @author Marcos Azevedo */ @Entity @Table(name = "transacao", uniqueConstraints = @UniqueConstraint(columnNames = {"transaction_code"}), indexes = { @Index(columnList = "transaction_code", name = "idx_transacao_code"), @Index(columnList = "merchant_id", name = "idx_transacao_merchant_id"), @Index(columnList = "usuario_id", name = "idx_transacao_usuario_id") } ) public class Transacao implements Serializable { @Id @GeneratedValue(generator = "uuid") @GenericGenerator(name = "uuid", strategy = "uuid2") private String transaction_code; @ManyToOne @JoinColumn(name = "usuario_id") private Usuario usuario; @Digits(integer = 5, fraction = 2) @Column(name = "transaction_value", nullable = false) private BigDecimal transaction_value; @Enumerated(EnumType.STRING) @Column(name = "transaction_day", length = 12, nullable = false) private DiaSemanaEnum transaction_day; @Digits(integer = 5, fraction = 2) @Column(name = "transaction_perc", nullable = false) private BigDecimal transaction_perc; @Temporal(TemporalType.TIMESTAMP) @Column(name = "transaction_date", nullable = false) private Date transaction_date; @Digits(integer = 5, fraction = 2) @Column(name = "transaction_balance", nullable = false) private BigDecimal transaction_balance; @ManyToOne @JoinColumn(name = "merchant_id") private Estabelecimento merchant; @Column(name = "transaction_type", length = 60, nullable = false) private String transaction_type; @Column(name = "transaction_type_name", length = 60, nullable = false) private String transaction_type_name; public Transacao() { transaction_date = new Date(); } public String getTransaction_code() { return transaction_code; } public void setTransaction_code(String transaction_code) { this.transaction_code = transaction_code; } public Usuario getUsuario() { return usuario; } public void setUsuario(Usuario usuario) { this.usuario = usuario; } public BigDecimal getTransaction_value() { return transaction_value; } public void setTransaction_value(BigDecimal transaction_value) { this.transaction_value = transaction_value; } public DiaSemanaEnum getTransaction_day() { return transaction_day; } public void setTransaction_day(DiaSemanaEnum transaction_day) { this.transaction_day = transaction_day; } public BigDecimal getTransaction_perc() { return transaction_perc; } public Date getTransaction_date() { return transaction_date; } public void setTransaction_balance(BigDecimal transaction_balance) { this.transaction_balance = transaction_balance; } public BigDecimal getTransaction_balance() { return transaction_balance; } public void setTransaction_perc(BigDecimal transaction_perc) { this.transaction_perc = transaction_perc; } public void setTransaction_date(Date transaction_date) { this.transaction_date = transaction_date; } public Estabelecimento getMerchant() { return merchant; } public void setMerchant(Estabelecimento merchant) { this.merchant = merchant; } public String getTransaction_type() { return transaction_type; } public void setTransaction_type(String transaction_type) { this.transaction_type = transaction_type; } public String getTransaction_type_name() { return transaction_type_name; } public void setTransaction_type_name(String transaction_type_name) { this.transaction_type_name = transaction_type_name; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Transacao transacao = (Transacao) o; return com.google.common.base.Objects.equal(transaction_code, transacao.transaction_code); } @Override public int hashCode() { return com.google.common.base.Objects.hashCode(transaction_code); } @Override public String toString() { return "Transacao{" + "transaction_type_name='" + transaction_type_name + '\'' + ", transaction_type=" + transaction_type + ", merchant=" + merchant + ", transaction_balance=" + transaction_balance + ", transaction_date=" + transaction_date + ", transaction_perc=" + transaction_perc + ", transaction_day=" + transaction_day + ", transaction_value=" + transaction_value + ", usuario=" + usuario + ", transaction_code='" + transaction_code + '\'' + '}'; } }
apache-2.0
gingerwizard/elasticsearch
server/src/test/java/org/elasticsearch/index/mapper/IdFieldMapperTests.java
5001
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.index.mapper; import org.apache.lucene.index.IndexOptions; import org.apache.lucene.index.IndexableField; import org.elasticsearch.common.Strings; import org.elasticsearch.common.bytes.BytesArray; import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.common.compress.CompressedXContent; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.xcontent.XContentFactory; import org.elasticsearch.common.xcontent.XContentType; import org.elasticsearch.index.IndexService; import org.elasticsearch.index.mapper.MapperService.MergeReason; import org.elasticsearch.indices.IndicesService; import org.elasticsearch.plugins.Plugin; import org.elasticsearch.test.ESSingleNodeTestCase; import org.elasticsearch.test.InternalSettingsPlugin; import java.io.IOException; import java.util.Collection; import java.util.Collections; import static org.elasticsearch.index.mapper.IdFieldMapper.ID_FIELD_DATA_DEPRECATION_MESSAGE; import static org.hamcrest.Matchers.containsString; public class IdFieldMapperTests extends ESSingleNodeTestCase { @Override protected Collection<Class<? extends Plugin>> getPlugins() { return Collections.singleton(InternalSettingsPlugin.class); } public void testIncludeInObjectNotAllowed() throws Exception { String mapping = Strings.toString(XContentFactory.jsonBuilder().startObject().startObject("type").endObject().endObject()); DocumentMapper docMapper = createIndex("test").mapperService().documentMapperParser() .parse("type", new CompressedXContent(mapping)); try { docMapper.parse(new SourceToParse("test", "1", BytesReference.bytes(XContentFactory.jsonBuilder() .startObject().field("_id", "1").endObject()), XContentType.JSON)); fail("Expected failure to parse metadata field"); } catch (MapperParsingException e) { assertTrue(e.getMessage(), e.getMessage().contains("Field [_id] is a metadata field and cannot be added inside a document")); } } public void testDefaults() throws IOException { Settings indexSettings = Settings.EMPTY; MapperService mapperService = createIndex("test", indexSettings).mapperService(); DocumentMapper mapper = mapperService.merge("type", new CompressedXContent("{\"type\":{}}"), MergeReason.MAPPING_UPDATE); ParsedDocument document = mapper.parse(new SourceToParse("index", "id", new BytesArray("{}"), XContentType.JSON)); IndexableField[] fields = document.rootDoc().getFields(IdFieldMapper.NAME); assertEquals(1, fields.length); assertEquals(IndexOptions.DOCS, fields[0].fieldType().indexOptions()); assertTrue(fields[0].fieldType().stored()); assertEquals(Uid.encodeId("id"), fields[0].binaryValue()); } public void testEnableFieldData() throws IOException { IndexService service = createIndex("test", Settings.EMPTY); MapperService mapperService = service.mapperService(); mapperService.merge("type", new CompressedXContent("{\"type\":{}}"), MergeReason.MAPPING_UPDATE); IdFieldMapper.IdFieldType ft = (IdFieldMapper.IdFieldType) service.mapperService().fieldType("_id"); IllegalArgumentException exc = expectThrows(IllegalArgumentException.class, () -> ft.fielddataBuilder("test").build(null, null, mapperService)); assertThat(exc.getMessage(), containsString(IndicesService.INDICES_ID_FIELD_DATA_ENABLED_SETTING.getKey())); client().admin().cluster().prepareUpdateSettings() .setTransientSettings(Settings.builder().put(IndicesService.INDICES_ID_FIELD_DATA_ENABLED_SETTING.getKey(), true)) .get(); try { ft.fielddataBuilder("test").build(null, null, mapperService); assertWarnings(ID_FIELD_DATA_DEPRECATION_MESSAGE); } finally { // unset cluster setting client().admin().cluster().prepareUpdateSettings() .setTransientSettings(Settings.builder().putNull(IndicesService.INDICES_ID_FIELD_DATA_ENABLED_SETTING.getKey())) .get(); } } }
apache-2.0
gureronder/midpoint
model/model-api/src/main/java/com/evolveum/midpoint/model/api/AccessCertificationService.java
4039
/* * Copyright (c) 2010-2015 Evolveum * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.evolveum.midpoint.model.api; import com.evolveum.midpoint.prism.query.ObjectQuery; import com.evolveum.midpoint.schema.GetOperationOptions; import com.evolveum.midpoint.schema.SelectorOptions; import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.task.api.Task; import com.evolveum.midpoint.util.exception.CommunicationException; import com.evolveum.midpoint.util.exception.ConfigurationException; import com.evolveum.midpoint.util.exception.ExpressionEvaluationException; import com.evolveum.midpoint.util.exception.ObjectAlreadyExistsException; import com.evolveum.midpoint.util.exception.ObjectNotFoundException; import com.evolveum.midpoint.util.exception.SchemaException; import com.evolveum.midpoint.util.exception.SecurityViolationException; import com.evolveum.midpoint.xml.ns._public.common.common_3.AccessCertificationCampaignType; import com.evolveum.midpoint.xml.ns._public.common.common_3.AccessCertificationCaseType; import com.evolveum.midpoint.xml.ns._public.common.common_3.AccessCertificationDecisionType; import com.evolveum.midpoint.xml.ns._public.common.common_3.AccessCertificationDefinitionType; import java.util.Collection; import java.util.List; /** * Interface to access certification related functionality. E.g. launching certification campaigns, * filling-in certification forms, etc. * * EXPERIMENTAL. May (and probably will) change in the future. * * Please use CertificationManager for now. * * @author mederly */ public interface AccessCertificationService { AccessCertificationCampaignType createCampaign(AccessCertificationDefinitionType certificationDefinition, AccessCertificationCampaignType campaign, Task task, OperationResult parentResult) throws SchemaException, SecurityViolationException, ConfigurationException, ObjectNotFoundException, CommunicationException, ExpressionEvaluationException, ObjectAlreadyExistsException, PolicyViolationException; void startStage(AccessCertificationCampaignType campaign, Task task, OperationResult parentResult) throws SchemaException, SecurityViolationException, ConfigurationException, ObjectNotFoundException, CommunicationException, ExpressionEvaluationException, ObjectAlreadyExistsException, PolicyViolationException; List<AccessCertificationCaseType> searchCases(String campaignOid, ObjectQuery query, Collection<SelectorOptions<GetOperationOptions>> options, Task task, OperationResult parentResult) throws ObjectNotFoundException, SchemaException, SecurityViolationException, ConfigurationException, CommunicationException; List<AccessCertificationCaseType> searchDecisions(String campaignOid, String reviewerOid, ObjectQuery query, Collection<SelectorOptions<GetOperationOptions>> options, Task task, OperationResult parentResult) throws ObjectNotFoundException, SchemaException, SecurityViolationException, ConfigurationException, CommunicationException; void recordReviewerDecision(String campaignOid, long caseId, AccessCertificationDecisionType decision, Task task, OperationResult parentResult) throws ObjectNotFoundException, SchemaException, SecurityViolationException, ConfigurationException, CommunicationException, ObjectAlreadyExistsException; }
apache-2.0
KPTechnologyLab/spring-data-crate
src/main/java/org/springframework/data/crate/core/ActionType.java
775
/* * Copyright 2002-2014 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.data.crate.core; /** * * @author Hasnain Javed * @since 1.0.0 */ public enum ActionType { INSERT, UPDATE, DELETE; }
apache-2.0
joel-costigliola/assertj-core
src/test/java/org/assertj/core/api/junit/jupiter/SoftAssertionsExtension_PER_CLASS_Concurrency_Test.java
5481
/* * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * * Copyright 2012-2020 the original author or authors. */ package org.assertj.core.api.junit.jupiter; import static java.util.concurrent.TimeUnit.MILLISECONDS; import static org.junit.platform.engine.discovery.DiscoverySelectors.selectClass; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.CountDownLatch; import org.assertj.core.api.AssertionErrorCollector; import org.assertj.core.api.AutoCloseableSoftAssertions; import org.assertj.core.api.SoftAssertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInstance; import org.junit.jupiter.api.TestInstance.Lifecycle; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.api.extension.ExtensionContext; import org.junit.jupiter.api.parallel.Execution; import org.junit.jupiter.api.parallel.ExecutionMode; import org.junit.platform.testkit.engine.EngineTestKit; @DisplayName("SoftAssertionsExtension PER_CLASS concurrent injection test") public class SoftAssertionsExtension_PER_CLASS_Concurrency_Test { // Use CountDownLatches to synchronize between the two parallel running tests to make sure that they overlap in time. @Disabled("Run by the testkit") @ExtendWith(SoftAssertionsExtension.class) @ExtendWith(ExtensionInjector.class) @Execution(ExecutionMode.CONCURRENT) @TestInstance(Lifecycle.PER_CLASS) static class ConcurrencyTest { @InjectSoftAssertions SoftAssertions softly; static CountDownLatch[] flags = new CountDownLatch[6]; static Map<String, AssertionErrorCollector> map = Collections.synchronizedMap(new HashMap<>()); @BeforeAll static void beforeAll() { map.clear(); for (int i = 0; i < flags.length; i++) { flags[i] = new CountDownLatch(1); } } @BeforeEach void beforeEach(ExtensionContext context) { map.put(context.getTestMethod().get().getName(), SoftAssertionsExtension.getAssertionErrorCollector(context)); } static void waitForFlag(int flagNum) { try { if (!flags[flagNum].await(5000, MILLISECONDS)) { throw new IllegalStateException("Timed out while waiting for flag " + flagNum); } } catch (InterruptedException e) { throw new IllegalStateException("Interrupted while waiting for flag " + flagNum, e); } } @Test void test1(ExtensionContext context) { softly.assertThat(1).isEqualTo(0); flags[0].countDown(); waitForFlag(1); softly.assertThat(3).isEqualTo(4); flags[2].countDown(); waitForFlag(3); softly.assertThat(5).isEqualTo(6); map.put(context.getTestMethod().get().getName(), SoftAssertionsExtension.getAssertionErrorCollector(context)); } @Test void test2(@SuppressWarnings("unused") ExtensionContext context) { waitForFlag(0); softly.assertThat(2).isEqualTo(1); flags[1].countDown(); waitForFlag(2); softly.assertThat(4).isEqualTo(5); flags[3].countDown(); } } @Test void concurrent_tests_with_explicit_per_class_annotation_do_not_interfere() { EngineTestKit.engine("junit-jupiter") .selectors(selectClass(ConcurrencyTest.class)) .configurationParameter("junit.jupiter.conditions.deactivate", "*") .configurationParameter("junit.jupiter.execution.parallel.enabled", "true") .execute() .testEvents() .debug(System.err) .assertStatistics(stats -> stats.started(2).succeeded(0).failed(2)) .failed(); try (AutoCloseableSoftAssertions softly = new AutoCloseableSoftAssertions()) { AssertionErrorCollector collector = ConcurrencyTest.map.get("test1"); softly.assertThat(collector).as("test1").isNotNull(); if (softly.wasSuccess()) { List<AssertionError> collected = collector.assertionErrorsCollected(); softly.assertThat(collected).as("size").hasSize(3); softly.assertThat(collected.get(0)).as("zero").hasMessageContainingAll("1", "0"); softly.assertThat(collected.get(1)).as("one").hasMessageContainingAll("3", "4"); softly.assertThat(collected.get(2)).as("two").hasMessageContainingAll("5", "6"); } collector = ConcurrencyTest.map.get("test2"); softly.assertThat(collector).as("test2").isNotNull(); if (softly.wasSuccess()) { List<AssertionError> collected = collector.assertionErrorsCollected(); softly.assertThat(collected).as("size2").hasSize(2); softly.assertThat(collected.get(0)).as("zero2").hasMessageContainingAll("2", "1"); softly.assertThat(collected.get(1)).as("one2").hasMessageContainingAll("4", "5"); } } } }
apache-2.0
ChinaQuants/Strata
modules/pricer/src/test/java/com/opengamma/strata/pricer/capfloor/SabrIborCapletFloorletPeriodPricerTest.java
32634
/** * Copyright (C) 2016 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.strata.pricer.capfloor; import static com.opengamma.strata.basics.currency.Currency.EUR; import static com.opengamma.strata.basics.index.IborIndices.EUR_EURIBOR_3M; import static com.opengamma.strata.collect.TestHelper.assertThrowsIllegalArg; import static com.opengamma.strata.collect.TestHelper.dateUtc; import static com.opengamma.strata.product.common.PutCall.CALL; import static com.opengamma.strata.product.common.PutCall.PUT; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertTrue; import static org.testng.Assert.fail; import java.time.LocalDate; import java.time.ZoneOffset; import java.time.ZonedDateTime; import org.testng.annotations.Test; import com.opengamma.strata.basics.ReferenceData; import com.opengamma.strata.basics.currency.CurrencyAmount; import com.opengamma.strata.basics.date.DayCounts; import com.opengamma.strata.basics.value.ValueDerivatives; import com.opengamma.strata.collect.timeseries.LocalDateDoubleTimeSeries; import com.opengamma.strata.market.model.SabrParameterType; import com.opengamma.strata.market.param.CurrencyParameterSensitivities; import com.opengamma.strata.market.sensitivity.PointSensitivities; import com.opengamma.strata.market.sensitivity.PointSensitivity; import com.opengamma.strata.market.sensitivity.PointSensitivityBuilder; import com.opengamma.strata.market.surface.ConstantSurface; import com.opengamma.strata.market.surface.Surfaces; import com.opengamma.strata.pricer.impl.option.BlackFormulaRepository; import com.opengamma.strata.pricer.impl.swap.DiscountingRatePaymentPeriodPricer; import com.opengamma.strata.pricer.rate.ImmutableRatesProvider; import com.opengamma.strata.pricer.sensitivity.RatesFiniteDifferenceSensitivityCalculator; import com.opengamma.strata.product.capfloor.IborCapletFloorletPeriod; import com.opengamma.strata.product.rate.FixedRateComputation; import com.opengamma.strata.product.rate.IborRateComputation; import com.opengamma.strata.product.swap.RateAccrualPeriod; import com.opengamma.strata.product.swap.RatePaymentPeriod; /** * Test {@link SabrIborCapletFloorletPeriodPricer}. */ @Test public class SabrIborCapletFloorletPeriodPricerTest { private static final ReferenceData REF_DATA = ReferenceData.standard(); private static final ZonedDateTime VALUATION = dateUtc(2008, 8, 18); private static final LocalDate FIXING = LocalDate.of(2011, 1, 3); private static final double NOTIONAL = 1000000; //1m private static final double STRIKE = 0.01; private static final IborRateComputation RATE_COMP = IborRateComputation.of(EUR_EURIBOR_3M, FIXING, REF_DATA); private static final IborCapletFloorletPeriod CAPLET_LONG = IborCapletFloorletPeriod.builder() .caplet(STRIKE) .startDate(RATE_COMP.getEffectiveDate()) .endDate(RATE_COMP.getMaturityDate()) .yearFraction(RATE_COMP.getYearFraction()) .notional(NOTIONAL) .iborRate(RATE_COMP) .build(); private static final IborCapletFloorletPeriod CAPLET_SHORT = IborCapletFloorletPeriod.builder() .caplet(STRIKE) .startDate(RATE_COMP.getEffectiveDate()) .endDate(RATE_COMP.getMaturityDate()) .yearFraction(RATE_COMP.getYearFraction()) .notional(-NOTIONAL) .iborRate(RATE_COMP) .build(); private static final IborCapletFloorletPeriod FLOORLET_LONG = IborCapletFloorletPeriod.builder() .floorlet(STRIKE) .startDate(RATE_COMP.getEffectiveDate()) .endDate(RATE_COMP.getMaturityDate()) .yearFraction(RATE_COMP.getYearFraction()) .notional(NOTIONAL) .iborRate(RATE_COMP) .build(); private static final IborCapletFloorletPeriod FLOORLET_SHORT = IborCapletFloorletPeriod.builder() .floorlet(STRIKE) .startDate(RATE_COMP.getEffectiveDate()) .endDate(RATE_COMP.getMaturityDate()) .yearFraction(RATE_COMP.getYearFraction()) .notional(-NOTIONAL) .iborRate(RATE_COMP) .build(); private static final RateAccrualPeriod IBOR_PERIOD = RateAccrualPeriod.builder() .startDate(CAPLET_LONG.getStartDate()) .endDate(CAPLET_LONG.getEndDate()) .yearFraction(CAPLET_LONG.getYearFraction()) .rateComputation(RATE_COMP) .build(); private static final RatePaymentPeriod IBOR_COUPON = RatePaymentPeriod.builder() .accrualPeriods(IBOR_PERIOD) .paymentDate(CAPLET_LONG.getPaymentDate()) .dayCount(EUR_EURIBOR_3M.getDayCount()) .notional(NOTIONAL) .currency(EUR) .build(); private static final RateAccrualPeriod FIXED_PERIOD = RateAccrualPeriod.builder() .startDate(CAPLET_LONG.getStartDate()) .endDate(CAPLET_LONG.getEndDate()) .rateComputation(FixedRateComputation.of(STRIKE)) .yearFraction(CAPLET_LONG.getYearFraction()) .build(); private static final RatePaymentPeriod FIXED_COUPON = RatePaymentPeriod.builder() .accrualPeriods(FIXED_PERIOD) .paymentDate(CAPLET_LONG.getPaymentDate()) .dayCount(EUR_EURIBOR_3M.getDayCount()) .notional(NOTIONAL) .currency(EUR) .build(); private static final RateAccrualPeriod FIXED_PERIOD_UNIT = RateAccrualPeriod.builder() .startDate(CAPLET_LONG.getStartDate()) .endDate(CAPLET_LONG.getEndDate()) .rateComputation(FixedRateComputation.of(1d)) .yearFraction(CAPLET_LONG.getYearFraction()) .build(); private static final RatePaymentPeriod FIXED_COUPON_UNIT = RatePaymentPeriod.builder() .accrualPeriods(FIXED_PERIOD_UNIT) .paymentDate(CAPLET_LONG.getPaymentDate()) .dayCount(EUR_EURIBOR_3M.getDayCount()) .notional(NOTIONAL) .currency(EUR) .build(); // valuation date before fixing date private static final ImmutableRatesProvider RATES = IborCapletFloorletSabrRateVolatilityDataSet.getRatesProvider( VALUATION.toLocalDate(), EUR_EURIBOR_3M, LocalDateDoubleTimeSeries.empty()); private static final SabrParametersIborCapletFloorletVolatilities VOLS = IborCapletFloorletSabrRateVolatilityDataSet .getVolatilities(VALUATION, EUR_EURIBOR_3M); // valuation date equal to fixing date private static final double OBS_INDEX = 0.013; private static final LocalDateDoubleTimeSeries TIME_SERIES = LocalDateDoubleTimeSeries.of(FIXING, OBS_INDEX); private static final ImmutableRatesProvider RATES_ON_FIX = IborCapletFloorletSabrRateVolatilityDataSet.getRatesProvider(FIXING, EUR_EURIBOR_3M, TIME_SERIES); private static final SabrParametersIborCapletFloorletVolatilities VOLS_ON_FIX = IborCapletFloorletSabrRateVolatilityDataSet .getVolatilities(FIXING.atStartOfDay(ZoneOffset.UTC), EUR_EURIBOR_3M); // valuation date after fixing date private static final ImmutableRatesProvider RATES_AFTER_FIX = IborCapletFloorletSabrRateVolatilityDataSet.getRatesProvider(FIXING.plusWeeks(1), EUR_EURIBOR_3M, TIME_SERIES); private static final SabrParametersIborCapletFloorletVolatilities VOLS_AFTER_FIX = IborCapletFloorletSabrRateVolatilityDataSet .getVolatilities(FIXING.plusWeeks(1).atStartOfDay(ZoneOffset.UTC), EUR_EURIBOR_3M); // valuation date after payment date private static final LocalDate DATE_AFTER_PAY = LocalDate.of(2011, 5, 2); private static final ImmutableRatesProvider RATES_AFTER_PAY = IborCapletFloorletSabrRateVolatilityDataSet.getRatesProvider(DATE_AFTER_PAY, EUR_EURIBOR_3M, TIME_SERIES); private static final SabrParametersIborCapletFloorletVolatilities VOLS_AFTER_PAY = IborCapletFloorletSabrRateVolatilityDataSet .getVolatilities(DATE_AFTER_PAY.plusWeeks(1).atStartOfDay(ZoneOffset.UTC), EUR_EURIBOR_3M); // Black vols private static final BlackIborCapletFloorletExpiryStrikeVolatilities VOLS_BLACK = IborCapletFloorletDataSet .createBlackVolatilities(VALUATION, EUR_EURIBOR_3M); // constatnt shift private static final double SHIFT = IborCapletFloorletSabrRateVolatilityDataSet.CONST_SHIFT; private static final double TOL = 1.0e-14; private static final double EPS_FD = 1.0e-6; private static final SabrIborCapletFloorletPeriodPricer PRICER = SabrIborCapletFloorletPeriodPricer.DEFAULT; private static final VolatilityIborCapletFloorletPeriodPricer PRICER_BASE = VolatilityIborCapletFloorletPeriodPricer.DEFAULT; private static final DiscountingRatePaymentPeriodPricer PRICER_COUPON = DiscountingRatePaymentPeriodPricer.DEFAULT; private static final RatesFiniteDifferenceSensitivityCalculator FD_CAL = new RatesFiniteDifferenceSensitivityCalculator(EPS_FD); //------------------------------------------------------------------------- public void test_presentValue_formula() { CurrencyAmount computedCaplet = PRICER.presentValue(CAPLET_LONG, RATES, VOLS); CurrencyAmount computedFloorlet = PRICER.presentValue(FLOORLET_SHORT, RATES, VOLS); double forward = RATES.iborIndexRates(EUR_EURIBOR_3M).rate(RATE_COMP.getObservation()); double expiry = VOLS.relativeTime(CAPLET_LONG.getFixingDateTime()); double volatility = VOLS.volatility(expiry, STRIKE, forward); double df = RATES.discountFactor(EUR, CAPLET_LONG.getPaymentDate()); double expectedCaplet = NOTIONAL * df * CAPLET_LONG.getYearFraction() * BlackFormulaRepository.price( forward + SHIFT, STRIKE + SHIFT, expiry, volatility, CALL.isCall()); double expectedFloorlet = -NOTIONAL * df * FLOORLET_SHORT.getYearFraction() * BlackFormulaRepository.price( forward + SHIFT, STRIKE + SHIFT, expiry, volatility, PUT.isCall()); assertEquals(computedCaplet.getCurrency(), EUR); assertEquals(computedCaplet.getAmount(), expectedCaplet, NOTIONAL * TOL); assertEquals(computedFloorlet.getCurrency(), EUR); assertEquals(computedFloorlet.getAmount(), expectedFloorlet, NOTIONAL * TOL); // consistency with shifted Black ShiftedBlackIborCapletFloorletExpiryStrikeVolatilities vols = ShiftedBlackIborCapletFloorletExpiryStrikeVolatilities.of( EUR_EURIBOR_3M, VALUATION, ConstantSurface.of("constVol", volatility) .withMetadata(Surfaces.blackVolatilityByExpiryStrike("costVol", DayCounts.ACT_ACT_ISDA)), IborCapletFloorletSabrRateVolatilityDataSet.CURVE_CONST_SHIFT); CurrencyAmount computedCapletBlack = PRICER_BASE.presentValue(CAPLET_LONG, RATES, vols); CurrencyAmount computedFloorletBlack = PRICER_BASE.presentValue(FLOORLET_SHORT, RATES, vols); assertEquals(computedCaplet.getAmount(), computedCapletBlack.getAmount(), NOTIONAL * TOL); assertEquals(computedFloorlet.getAmount(), computedFloorletBlack.getAmount(), NOTIONAL * TOL); } public void test_presentValue_parity() { double capletLong = PRICER.presentValue(CAPLET_LONG, RATES, VOLS).getAmount(); double capletShort = PRICER.presentValue(CAPLET_SHORT, RATES, VOLS).getAmount(); double floorletLong = PRICER.presentValue(FLOORLET_LONG, RATES, VOLS).getAmount(); double floorletShort = PRICER.presentValue(FLOORLET_SHORT, RATES, VOLS).getAmount(); double iborCoupon = PRICER_COUPON.presentValue(IBOR_COUPON, RATES); double fixedCoupon = PRICER_COUPON.presentValue(FIXED_COUPON, RATES); assertEquals(capletLong, -capletShort, NOTIONAL * TOL); assertEquals(floorletLong, -floorletShort, NOTIONAL * TOL); assertEquals(capletLong - floorletLong, iborCoupon - fixedCoupon, NOTIONAL * TOL); assertEquals(capletShort - floorletShort, -iborCoupon + fixedCoupon, NOTIONAL * TOL); } public void test_presentValue_onFix() { CurrencyAmount computedCaplet = PRICER.presentValue(CAPLET_LONG, RATES_ON_FIX, VOLS_ON_FIX); CurrencyAmount computedFloorlet = PRICER.presentValue(FLOORLET_SHORT, RATES_ON_FIX, VOLS_ON_FIX); double expectedCaplet = PRICER_COUPON.presentValue(FIXED_COUPON_UNIT, RATES_ON_FIX) * (OBS_INDEX - STRIKE); double expectedFloorlet = 0d; assertEquals(computedCaplet.getCurrency(), EUR); assertEquals(computedCaplet.getAmount(), expectedCaplet, NOTIONAL * TOL); assertEquals(computedFloorlet.getCurrency(), EUR); assertEquals(computedFloorlet.getAmount(), expectedFloorlet, NOTIONAL * TOL); } public void test_presentValue_afterFix() { CurrencyAmount computedCaplet = PRICER.presentValue(CAPLET_LONG, RATES_AFTER_FIX, VOLS_AFTER_FIX); CurrencyAmount computedFloorlet = PRICER.presentValue(FLOORLET_SHORT, RATES_AFTER_FIX, VOLS_AFTER_FIX); double payoff = (OBS_INDEX - STRIKE) * PRICER_COUPON.presentValue(FIXED_COUPON_UNIT, RATES_AFTER_FIX); assertEquals(computedCaplet.getCurrency(), EUR); assertEquals(computedCaplet.getAmount(), payoff, NOTIONAL * TOL); assertEquals(computedFloorlet.getCurrency(), EUR); assertEquals(computedFloorlet.getAmount(), 0d, NOTIONAL * TOL); } public void test_presentValue_afterPay() { CurrencyAmount computedCaplet = PRICER.presentValue(CAPLET_LONG, RATES_AFTER_PAY, VOLS_AFTER_PAY); CurrencyAmount computedFloorlet = PRICER.presentValue(FLOORLET_SHORT, RATES_AFTER_PAY, VOLS_AFTER_PAY); assertEquals(computedCaplet.getCurrency(), EUR); assertEquals(computedCaplet.getAmount(), 0d, NOTIONAL * TOL); assertEquals(computedFloorlet.getCurrency(), EUR); assertEquals(computedFloorlet.getAmount(), 0d, NOTIONAL * TOL); } //------------------------------------------------------------------------- public void test_impliedVolatility() { double computed = PRICER.impliedVolatility(CAPLET_LONG, RATES, VOLS); double expiry = VOLS.relativeTime(CAPLET_LONG.getFixingDateTime()); double forward = RATES.iborIndexRates(EUR_EURIBOR_3M).rate(RATE_COMP.getObservation()); double expected = VOLS.volatility(expiry, STRIKE, forward); assertEquals(computed, expected, TOL); } public void test_impliedVolatility_onFix() { double computed = PRICER.impliedVolatility(CAPLET_LONG, RATES_ON_FIX, VOLS_ON_FIX); double forward = RATES_ON_FIX.iborIndexRates(EUR_EURIBOR_3M).rate(RATE_COMP.getObservation()); double expected = VOLS.volatility(0d, STRIKE, forward); assertEquals(computed, expected, TOL); } public void test_impliedVolatility_afterFix() { assertThrowsIllegalArg(() -> PRICER.impliedVolatility(CAPLET_LONG, RATES_AFTER_FIX, VOLS_AFTER_FIX)); } //------------------------------------------------------------------------- public void test_presentValueDelta_formula() { CurrencyAmount computedCaplet = PRICER.presentValueDelta(CAPLET_LONG, RATES, VOLS); CurrencyAmount computedFloorlet = PRICER.presentValueDelta(FLOORLET_SHORT, RATES, VOLS); double forward = RATES.iborIndexRates(EUR_EURIBOR_3M).rate(RATE_COMP.getObservation()); double expiry = VOLS.relativeTime(CAPLET_LONG.getFixingDateTime()); double volatility = VOLS.volatility(expiry, STRIKE, forward); double df = RATES.discountFactor(EUR, CAPLET_LONG.getPaymentDate()); double expectedCaplet = NOTIONAL * df * CAPLET_LONG.getYearFraction() * BlackFormulaRepository.delta(forward + SHIFT, STRIKE + SHIFT, expiry, volatility, CALL.isCall()); double expectedFloorlet = -NOTIONAL * df * FLOORLET_SHORT.getYearFraction() * BlackFormulaRepository.delta(forward + SHIFT, STRIKE + SHIFT, expiry, volatility, PUT.isCall()); assertEquals(computedCaplet.getCurrency(), EUR); assertEquals(computedCaplet.getAmount(), expectedCaplet, NOTIONAL * TOL); assertEquals(computedFloorlet.getCurrency(), EUR); assertEquals(computedFloorlet.getAmount(), expectedFloorlet, NOTIONAL * TOL); } public void test_presentValueDelta_parity() { double capletLong = PRICER.presentValueDelta(CAPLET_LONG, RATES, VOLS).getAmount(); double capletShort = PRICER.presentValueDelta(CAPLET_SHORT, RATES, VOLS).getAmount(); double floorletLong = PRICER.presentValueDelta(FLOORLET_LONG, RATES, VOLS).getAmount(); double floorletShort = PRICER.presentValueDelta(FLOORLET_SHORT, RATES, VOLS).getAmount(); double unitCoupon = PRICER_COUPON.presentValue(FIXED_COUPON_UNIT, RATES); assertEquals(capletLong, -capletShort, NOTIONAL * TOL); assertEquals(floorletLong, -floorletShort, NOTIONAL * TOL); assertEquals(capletLong - floorletLong, unitCoupon, NOTIONAL * TOL); assertEquals(capletShort - floorletShort, -unitCoupon, NOTIONAL * TOL); } public void test_presentValueDelta_onFix() { CurrencyAmount computedCaplet = PRICER.presentValueDelta(CAPLET_LONG, RATES_ON_FIX, VOLS_ON_FIX); CurrencyAmount computedFloorlet = PRICER.presentValueDelta(FLOORLET_SHORT, RATES_ON_FIX, VOLS_ON_FIX); double expectedCaplet = PRICER_COUPON.presentValue(FIXED_COUPON_UNIT, RATES_ON_FIX); double expectedFloorlet = 0d; assertEquals(computedCaplet.getCurrency(), EUR); assertEquals(computedCaplet.getAmount(), expectedCaplet, TOL); assertEquals(computedFloorlet.getCurrency(), EUR); assertEquals(computedFloorlet.getAmount(), expectedFloorlet, TOL); } public void test_presentValueDelta_afterFix() { CurrencyAmount computedCaplet = PRICER.presentValueDelta(CAPLET_LONG, RATES_AFTER_FIX, VOLS_AFTER_FIX); CurrencyAmount computedFloorlet = PRICER.presentValueDelta(FLOORLET_SHORT, RATES_AFTER_FIX, VOLS_AFTER_FIX); assertEquals(computedCaplet.getCurrency(), EUR); assertEquals(computedCaplet.getAmount(), 0d, TOL); assertEquals(computedFloorlet.getCurrency(), EUR); assertEquals(computedFloorlet.getAmount(), 0d, TOL); } //------------------------------------------------------------------------- public void test_presentValueGamma_formula() { CurrencyAmount computedCaplet = PRICER.presentValueGamma(CAPLET_LONG, RATES, VOLS); CurrencyAmount computedFloorlet = PRICER.presentValueGamma(FLOORLET_SHORT, RATES, VOLS); double forward = RATES.iborIndexRates(EUR_EURIBOR_3M).rate(RATE_COMP.getObservation()); double expiry = VOLS.relativeTime(CAPLET_LONG.getFixingDateTime()); double volatility = VOLS.volatility(expiry, STRIKE, forward); double df = RATES.discountFactor(EUR, CAPLET_LONG.getPaymentDate()); double expectedCaplet = NOTIONAL * df * CAPLET_LONG.getYearFraction() * BlackFormulaRepository.gamma(forward + SHIFT, STRIKE + SHIFT, expiry, volatility); double expectedFloorlet = -NOTIONAL * df * FLOORLET_SHORT.getYearFraction() * BlackFormulaRepository.gamma(forward + SHIFT, STRIKE + SHIFT, expiry, volatility); assertEquals(computedCaplet.getCurrency(), EUR); assertEquals(computedCaplet.getAmount(), expectedCaplet, NOTIONAL * TOL); assertEquals(computedFloorlet.getCurrency(), EUR); assertEquals(computedFloorlet.getAmount(), expectedFloorlet, NOTIONAL * TOL); } public void test_presentValueGamma_onFix() { CurrencyAmount computedCaplet = PRICER.presentValueGamma(CAPLET_LONG, RATES_ON_FIX, VOLS_ON_FIX); CurrencyAmount computedFloorlet = PRICER.presentValueGamma(FLOORLET_SHORT, RATES_ON_FIX, VOLS_ON_FIX); double expectedCaplet = 0d; double expectedFloorlet = 0d; assertEquals(computedCaplet.getCurrency(), EUR); assertEquals(computedCaplet.getAmount(), expectedCaplet, TOL); assertEquals(computedFloorlet.getCurrency(), EUR); assertEquals(computedFloorlet.getAmount(), expectedFloorlet, TOL); } public void test_presentValueGamma_afterFix() { CurrencyAmount computedCaplet = PRICER.presentValueGamma(CAPLET_LONG, RATES_AFTER_FIX, VOLS_AFTER_FIX); CurrencyAmount computedFloorlet = PRICER.presentValueGamma(FLOORLET_SHORT, RATES_AFTER_FIX, VOLS_AFTER_FIX); assertEquals(computedCaplet.getCurrency(), EUR); assertEquals(computedCaplet.getAmount(), 0d, TOL); assertEquals(computedFloorlet.getCurrency(), EUR); assertEquals(computedFloorlet.getAmount(), 0d, TOL); } //------------------------------------------------------------------------- public void test_presentValueTheta_formula() { CurrencyAmount computedCaplet = PRICER.presentValueTheta(CAPLET_LONG, RATES, VOLS); CurrencyAmount computedFloorlet = PRICER.presentValueTheta(FLOORLET_SHORT, RATES, VOLS); double forward = RATES.iborIndexRates(EUR_EURIBOR_3M).rate(RATE_COMP.getObservation()); double expiry = VOLS.relativeTime(CAPLET_LONG.getFixingDateTime()); double volatility = VOLS.volatility(expiry, STRIKE, forward); double df = RATES.discountFactor(EUR, CAPLET_LONG.getPaymentDate()); double expectedCaplet = NOTIONAL * df * CAPLET_LONG.getYearFraction() * BlackFormulaRepository.driftlessTheta(forward + SHIFT, STRIKE + SHIFT, expiry, volatility); double expectedFloorlet = -NOTIONAL * df * FLOORLET_SHORT.getYearFraction() * BlackFormulaRepository.driftlessTheta(forward + SHIFT, STRIKE + SHIFT, expiry, volatility); assertEquals(computedCaplet.getCurrency(), EUR); assertEquals(computedCaplet.getAmount(), expectedCaplet, NOTIONAL * TOL); assertEquals(computedFloorlet.getCurrency(), EUR); assertEquals(computedFloorlet.getAmount(), expectedFloorlet, NOTIONAL * TOL); } public void test_presentValueTheta_parity() { double capletLong = PRICER.presentValueTheta(CAPLET_LONG, RATES, VOLS).getAmount(); double capletShort = PRICER.presentValueTheta(CAPLET_SHORT, RATES, VOLS).getAmount(); double floorletLong = PRICER.presentValueTheta(FLOORLET_LONG, RATES, VOLS).getAmount(); double floorletShort = PRICER.presentValueTheta(FLOORLET_SHORT, RATES, VOLS).getAmount(); assertEquals(capletLong, -capletShort, NOTIONAL * TOL); assertEquals(floorletLong, -floorletShort, NOTIONAL * TOL); assertEquals(capletLong, floorletLong, NOTIONAL * TOL); assertEquals(capletShort, floorletShort, NOTIONAL * TOL); } public void test_presentValueTheta_onFix() { CurrencyAmount computedCaplet = PRICER.presentValueTheta(CAPLET_LONG, RATES_ON_FIX, VOLS_ON_FIX); CurrencyAmount computedFloorlet = PRICER.presentValueTheta(FLOORLET_SHORT, RATES_ON_FIX, VOLS_ON_FIX); double expectedCaplet = 0d; double expectedFloorlet = 0d; assertEquals(computedCaplet.getCurrency(), EUR); assertEquals(computedCaplet.getAmount(), expectedCaplet, TOL); assertEquals(computedFloorlet.getCurrency(), EUR); assertEquals(computedFloorlet.getAmount(), expectedFloorlet, TOL); } public void test_presentValueTheta_afterFix() { CurrencyAmount computedCaplet = PRICER.presentValueTheta(CAPLET_LONG, RATES_AFTER_FIX, VOLS_AFTER_FIX); CurrencyAmount computedFloorlet = PRICER.presentValueTheta(FLOORLET_SHORT, RATES_AFTER_FIX, VOLS_AFTER_FIX); assertEquals(computedCaplet.getCurrency(), EUR); assertEquals(computedCaplet.getAmount(), 0d, TOL); assertEquals(computedFloorlet.getCurrency(), EUR); assertEquals(computedFloorlet.getAmount(), 0d, TOL); } //------------------------------------------------------------------------- public void test_presentValueSensitivity() { PointSensitivityBuilder pointCaplet = PRICER.presentValueSensitivityRatesStickyModel(CAPLET_LONG, RATES, VOLS); CurrencyParameterSensitivities computedCaplet = RATES.parameterSensitivity(pointCaplet.build()); PointSensitivityBuilder pointFloorlet = PRICER.presentValueSensitivityRatesStickyModel(FLOORLET_SHORT, RATES, VOLS); CurrencyParameterSensitivities computedFloorlet = RATES.parameterSensitivity(pointFloorlet.build()); CurrencyParameterSensitivities expectedCaplet = FD_CAL.sensitivity(RATES, p -> PRICER_BASE.presentValue(CAPLET_LONG, p, VOLS)); CurrencyParameterSensitivities expectedFloorlet = FD_CAL.sensitivity(RATES, p -> PRICER_BASE.presentValue(FLOORLET_SHORT, p, VOLS)); assertTrue(computedCaplet.equalWithTolerance(expectedCaplet, EPS_FD * NOTIONAL * 50d)); assertTrue(computedFloorlet.equalWithTolerance(expectedFloorlet, EPS_FD * NOTIONAL * 50d)); // consistency with shifted Black PointSensitivityBuilder pointCapletBase = PRICER.presentValueSensitivityRates(CAPLET_LONG, RATES, VOLS); PointSensitivityBuilder pointFloorletBase = PRICER.presentValueSensitivityRates(FLOORLET_SHORT, RATES, VOLS); double forward = RATES.iborIndexRates(EUR_EURIBOR_3M).rate(RATE_COMP.getObservation()); double expiry = VOLS.relativeTime(CAPLET_LONG.getFixingDateTime()); double volatility = VOLS.volatility(expiry, STRIKE, forward); ShiftedBlackIborCapletFloorletExpiryStrikeVolatilities vols = ShiftedBlackIborCapletFloorletExpiryStrikeVolatilities.of( EUR_EURIBOR_3M, VALUATION, ConstantSurface.of("constVol", volatility) .withMetadata(Surfaces.blackVolatilityByExpiryStrike("costVol", DayCounts.ACT_ACT_ISDA)), IborCapletFloorletSabrRateVolatilityDataSet.CURVE_CONST_SHIFT); PointSensitivityBuilder pointCapletExp = PRICER_BASE.presentValueSensitivityRates(CAPLET_LONG, RATES, vols); PointSensitivityBuilder pointFloorletExp = PRICER_BASE.presentValueSensitivityRates(FLOORLET_SHORT, RATES, vols); assertEquals(pointCapletBase, pointCapletExp); assertEquals(pointFloorletBase, pointFloorletExp); } public void test_presentValueSensitivity_onFix() { PointSensitivityBuilder pointCaplet = PRICER.presentValueSensitivityRatesStickyModel(CAPLET_LONG, RATES_ON_FIX, VOLS_ON_FIX); CurrencyParameterSensitivities computedCaplet = RATES_ON_FIX.parameterSensitivity(pointCaplet.build()); PointSensitivityBuilder pointFloorlet = PRICER.presentValueSensitivityRatesStickyModel(FLOORLET_SHORT, RATES_ON_FIX, VOLS_ON_FIX); CurrencyParameterSensitivities computedFloorlet = RATES_ON_FIX.parameterSensitivity(pointFloorlet.build()); CurrencyParameterSensitivities expectedCaplet = FD_CAL.sensitivity(RATES_ON_FIX, p -> PRICER_BASE.presentValue(CAPLET_LONG, p, VOLS_ON_FIX)); CurrencyParameterSensitivities expectedFloorlet = FD_CAL.sensitivity(RATES_ON_FIX, p -> PRICER_BASE.presentValue(FLOORLET_SHORT, p, VOLS_ON_FIX)); assertTrue(computedCaplet.equalWithTolerance(expectedCaplet, EPS_FD * NOTIONAL)); assertTrue(computedFloorlet.equalWithTolerance(expectedFloorlet, EPS_FD * NOTIONAL)); } public void test_presentValueSensitivity_afterFix() { PointSensitivityBuilder pointCaplet = PRICER.presentValueSensitivityRatesStickyModel(CAPLET_LONG, RATES_AFTER_FIX, VOLS_AFTER_FIX); CurrencyParameterSensitivities computedCaplet = RATES_AFTER_FIX.parameterSensitivity(pointCaplet.build()); PointSensitivityBuilder pointFloorlet = PRICER.presentValueSensitivityRatesStickyModel(FLOORLET_SHORT, RATES_AFTER_FIX, VOLS_AFTER_FIX); CurrencyParameterSensitivities computedFloorlet = RATES_AFTER_FIX.parameterSensitivity(pointFloorlet.build()); CurrencyParameterSensitivities expectedCaplet = FD_CAL.sensitivity(RATES_AFTER_FIX, p -> PRICER_BASE.presentValue(CAPLET_LONG, p, VOLS_AFTER_FIX)); CurrencyParameterSensitivities expectedFloorlet = FD_CAL.sensitivity(RATES_AFTER_FIX, p -> PRICER_BASE.presentValue(FLOORLET_SHORT, p, VOLS_AFTER_FIX)); assertTrue(computedCaplet.equalWithTolerance(expectedCaplet, EPS_FD * NOTIONAL)); assertTrue(computedFloorlet.equalWithTolerance(expectedFloorlet, EPS_FD * NOTIONAL)); } public void test_presentValueSensitivity_afterPay() { PointSensitivityBuilder computedCaplet = PRICER.presentValueSensitivityRatesStickyModel(CAPLET_LONG, RATES_AFTER_PAY, VOLS_AFTER_PAY); PointSensitivityBuilder computedFloorlet = PRICER.presentValueSensitivityRatesStickyModel(FLOORLET_SHORT, RATES_AFTER_PAY, VOLS_AFTER_PAY); assertEquals(computedCaplet, PointSensitivityBuilder.none()); assertEquals(computedFloorlet, PointSensitivityBuilder.none()); } //------------------------------------------------------------------------- public void test_presentValueSensitivityVolatility() { PointSensitivities pointCaplet = PRICER.presentValueSensitivityModelParamsSabr(CAPLET_LONG, RATES, VOLS).build(); PointSensitivities pointFloorlet = PRICER.presentValueSensitivityModelParamsSabr(FLOORLET_SHORT, RATES, VOLS).build(); double forward = RATES.iborIndexRates(EUR_EURIBOR_3M).rate(RATE_COMP.getObservation()); double expiry = VOLS.relativeTime(CAPLET_LONG.getFixingDateTime()); ValueDerivatives volSensi = VOLS.getParameters().volatilityAdjoint(expiry, STRIKE, forward); double df = RATES.discountFactor(EUR, CAPLET_LONG.getPaymentDate()); double vegaCaplet = NOTIONAL * df * CAPLET_LONG.getYearFraction() * BlackFormulaRepository.vega(forward + SHIFT, STRIKE + SHIFT, expiry, volSensi.getValue()); double vegaFloorlet = -NOTIONAL * df * CAPLET_LONG.getYearFraction() * BlackFormulaRepository.vega(forward + SHIFT, STRIKE + SHIFT, expiry, volSensi.getValue()); assertSensitivity(pointCaplet, SabrParameterType.ALPHA, vegaCaplet * volSensi.getDerivative(2), TOL); assertSensitivity(pointCaplet, SabrParameterType.BETA, vegaCaplet * volSensi.getDerivative(3), TOL); assertSensitivity(pointCaplet, SabrParameterType.RHO, vegaCaplet * volSensi.getDerivative(4), TOL); assertSensitivity(pointCaplet, SabrParameterType.NU, vegaCaplet * volSensi.getDerivative(5), TOL); assertSensitivity(pointFloorlet, SabrParameterType.ALPHA, vegaFloorlet * volSensi.getDerivative(2), TOL); assertSensitivity(pointFloorlet, SabrParameterType.BETA, vegaFloorlet * volSensi.getDerivative(3), TOL); assertSensitivity(pointFloorlet, SabrParameterType.RHO, vegaFloorlet * volSensi.getDerivative(4), TOL); assertSensitivity(pointFloorlet, SabrParameterType.NU, vegaFloorlet * volSensi.getDerivative(5), TOL); PointSensitivities pointCapletVol = PRICER.presentValueSensitivityModelParamsVolatility(CAPLET_LONG, RATES, VOLS).build(); // vol sensitivity in base class PointSensitivities pointFloorletVol = PRICER.presentValueSensitivityModelParamsVolatility(FLOORLET_SHORT, RATES, VOLS).build(); IborCapletFloorletSensitivity pointCapletVolExp = IborCapletFloorletSensitivity.of(VOLS.getName(), expiry, STRIKE, forward, EUR, vegaCaplet); IborCapletFloorletSensitivity pointFloorletVolExp = IborCapletFloorletSensitivity.of(VOLS.getName(), expiry, STRIKE, forward, EUR, vegaFloorlet); assertEquals(pointCapletVol.getSensitivities().get(0), pointCapletVolExp); assertEquals(pointFloorletVol.getSensitivities().get(0), pointFloorletVolExp); } private void assertSensitivity(PointSensitivities points, SabrParameterType type, double expected, double tol) { for (PointSensitivity point : points.getSensitivities()) { IborCapletFloorletSabrSensitivity sens = (IborCapletFloorletSabrSensitivity) point; assertEquals(sens.getCurrency(), EUR); assertEquals(sens.getVolatilitiesName(), VOLS.getName()); if (sens.getSensitivityType() == type) { assertEquals(sens.getSensitivity(), expected, NOTIONAL * tol); return; } } fail("Did not find sensitivity: " + type + " in " + points); } public void test_presentValueSensitivityVolatility_onFix() { PointSensitivityBuilder computedCaplet = PRICER.presentValueSensitivityModelParamsVolatility(CAPLET_LONG, RATES_ON_FIX, VOLS_ON_FIX); PointSensitivityBuilder computedFloorlet = PRICER.presentValueSensitivityModelParamsVolatility(FLOORLET_SHORT, RATES_ON_FIX, VOLS_ON_FIX); assertEquals(computedCaplet, PointSensitivityBuilder.none()); assertEquals(computedFloorlet, PointSensitivityBuilder.none()); } public void test_presentValueSensitivityVolatility_afterFix() { PointSensitivityBuilder computedCaplet = PRICER.presentValueSensitivityModelParamsVolatility(CAPLET_LONG, RATES_AFTER_FIX, VOLS_AFTER_FIX); PointSensitivityBuilder computedFloorlet = PRICER.presentValueSensitivityModelParamsVolatility(FLOORLET_SHORT, RATES_AFTER_FIX, VOLS_AFTER_FIX); assertEquals(computedCaplet, PointSensitivityBuilder.none()); assertEquals(computedFloorlet, PointSensitivityBuilder.none()); } //------------------------------------------------------------------------- public void test_fail_Black() { assertThrowsIllegalArg(() -> PRICER.presentValue(CAPLET_LONG, RATES, VOLS_BLACK)); assertThrowsIllegalArg(() -> PRICER.impliedVolatility(CAPLET_LONG, RATES, VOLS_BLACK)); assertThrowsIllegalArg(() -> PRICER.presentValueDelta(CAPLET_LONG, RATES, VOLS_BLACK)); assertThrowsIllegalArg(() -> PRICER.presentValueGamma(CAPLET_LONG, RATES, VOLS_BLACK)); assertThrowsIllegalArg(() -> PRICER.presentValueTheta(CAPLET_LONG, RATES, VOLS_BLACK)); assertThrowsIllegalArg(() -> PRICER.presentValueSensitivityRates(CAPLET_LONG, RATES, VOLS_BLACK)); assertThrowsIllegalArg(() -> PRICER.presentValueSensitivityModelParamsVolatility(CAPLET_LONG, RATES, VOLS_BLACK)); } }
apache-2.0
aws/aws-sdk-java
aws-java-sdk-lakeformation/src/main/java/com/amazonaws/services/lakeformation/model/transform/GetTableObjectsRequestProtocolMarshaller.java
2658
/* * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.lakeformation.model.transform; import javax.annotation.Generated; import com.amazonaws.SdkClientException; import com.amazonaws.Request; import com.amazonaws.http.HttpMethodName; import com.amazonaws.services.lakeformation.model.*; import com.amazonaws.transform.Marshaller; import com.amazonaws.protocol.*; import com.amazonaws.protocol.Protocol; import com.amazonaws.annotation.SdkInternalApi; /** * GetTableObjectsRequest Marshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") @SdkInternalApi public class GetTableObjectsRequestProtocolMarshaller implements Marshaller<Request<GetTableObjectsRequest>, GetTableObjectsRequest> { private static final OperationInfo SDK_OPERATION_BINDING = OperationInfo.builder().protocol(Protocol.REST_JSON).requestUri("/GetTableObjects") .httpMethodName(HttpMethodName.POST).hasExplicitPayloadMember(false).hasPayloadMembers(true).serviceName("AWSLakeFormation").build(); private final com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory; public GetTableObjectsRequestProtocolMarshaller(com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory) { this.protocolFactory = protocolFactory; } public Request<GetTableObjectsRequest> marshall(GetTableObjectsRequest getTableObjectsRequest) { if (getTableObjectsRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { final ProtocolRequestMarshaller<GetTableObjectsRequest> protocolMarshaller = protocolFactory.createProtocolMarshaller(SDK_OPERATION_BINDING, getTableObjectsRequest); protocolMarshaller.startMarshalling(); GetTableObjectsRequestMarshaller.getInstance().marshall(getTableObjectsRequest, protocolMarshaller); return protocolMarshaller.finishMarshalling(); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
apache-2.0
jentfoo/aws-sdk-java
aws-java-sdk-resourcegroups/src/main/java/com/amazonaws/services/resourcegroups/model/BadRequestException.java
1268
/* * Copyright 2014-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.resourcegroups.model; import javax.annotation.Generated; /** * <p> * The request does not comply with validation rules that are defined for the request parameters. * </p> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class BadRequestException extends com.amazonaws.services.resourcegroups.model.AWSResourceGroupsException { private static final long serialVersionUID = 1L; /** * Constructs a new BadRequestException with the specified error message. * * @param message * Describes the error encountered. */ public BadRequestException(String message) { super(message); } }
apache-2.0
indashnet/InDashNet.Open.UN2000
android/external/bouncycastle/bcprov/src/main/java/org/bouncycastle/asn1/DERObjectIdentifier.java
11400
package org.bouncycastle.asn1; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.math.BigInteger; import org.bouncycastle.util.Arrays; public class DERObjectIdentifier extends ASN1Primitive { String identifier; private byte[] body; /** * return an OID from the passed in object * * @throws IllegalArgumentException if the object cannot be converted. */ public static ASN1ObjectIdentifier getInstance( Object obj) { if (obj == null || obj instanceof ASN1ObjectIdentifier) { return (ASN1ObjectIdentifier)obj; } if (obj instanceof DERObjectIdentifier) { return new ASN1ObjectIdentifier(((DERObjectIdentifier)obj).getId()); } if (obj instanceof ASN1Encodable && ((ASN1Encodable)obj).toASN1Primitive() instanceof ASN1ObjectIdentifier) { return (ASN1ObjectIdentifier)((ASN1Encodable)obj).toASN1Primitive(); } if (obj instanceof byte[]) { return ASN1ObjectIdentifier.fromOctetString((byte[])obj); } throw new IllegalArgumentException("illegal object in getInstance: " + obj.getClass().getName()); } /** * return an Object Identifier from a tagged object. * * @param obj the tagged object holding the object we want * @param explicit true if the object is meant to be explicitly * tagged false otherwise. * @throws IllegalArgumentException if the tagged object cannot * be converted. */ public static ASN1ObjectIdentifier getInstance( ASN1TaggedObject obj, boolean explicit) { ASN1Primitive o = obj.getObject(); if (explicit || o instanceof DERObjectIdentifier) { return getInstance(o); } else { return ASN1ObjectIdentifier.fromOctetString(ASN1OctetString.getInstance(obj.getObject()).getOctets()); } } private static final long LONG_LIMIT = (Long.MAX_VALUE >> 7) - 0x7f; DERObjectIdentifier( byte[] bytes) { StringBuffer objId = new StringBuffer(); long value = 0; BigInteger bigValue = null; boolean first = true; for (int i = 0; i != bytes.length; i++) { int b = bytes[i] & 0xff; if (value <= LONG_LIMIT) { value += (b & 0x7f); if ((b & 0x80) == 0) // end of number reached { if (first) { if (value < 40) { objId.append('0'); } else if (value < 80) { objId.append('1'); value -= 40; } else { objId.append('2'); value -= 80; } first = false; } objId.append('.'); objId.append(value); value = 0; } else { value <<= 7; } } else { if (bigValue == null) { bigValue = BigInteger.valueOf(value); } bigValue = bigValue.or(BigInteger.valueOf(b & 0x7f)); if ((b & 0x80) == 0) { if (first) { objId.append('2'); bigValue = bigValue.subtract(BigInteger.valueOf(80)); first = false; } objId.append('.'); objId.append(bigValue); bigValue = null; value = 0; } else { bigValue = bigValue.shiftLeft(7); } } } // BEGIN android-changed /* * Intern the identifier so there aren't hundreds of duplicates * (in practice). */ this.identifier = objId.toString().intern(); // END android-changed this.body = Arrays.clone(bytes); } public DERObjectIdentifier( String identifier) { if (identifier == null) { throw new IllegalArgumentException("'identifier' cannot be null"); } if (!isValidIdentifier(identifier)) { throw new IllegalArgumentException("string " + identifier + " not an OID"); } // BEGIN android-changed /* * Intern the identifier so there aren't hundreds of duplicates * (in practice). */ this.identifier = identifier.intern(); // END android-changed } DERObjectIdentifier(DERObjectIdentifier oid, String branchID) { if (!isValidBranchID(branchID, 0)) { throw new IllegalArgumentException("string " + branchID + " not a valid OID branch"); } this.identifier = oid.getId() + "." + branchID; } public String getId() { return identifier; } private void writeField( ByteArrayOutputStream out, long fieldValue) { byte[] result = new byte[9]; int pos = 8; result[pos] = (byte)((int)fieldValue & 0x7f); while (fieldValue >= (1L << 7)) { fieldValue >>= 7; result[--pos] = (byte)((int)fieldValue & 0x7f | 0x80); } out.write(result, pos, 9 - pos); } private void writeField( ByteArrayOutputStream out, BigInteger fieldValue) { int byteCount = (fieldValue.bitLength() + 6) / 7; if (byteCount == 0) { out.write(0); } else { BigInteger tmpValue = fieldValue; byte[] tmp = new byte[byteCount]; for (int i = byteCount - 1; i >= 0; i--) { tmp[i] = (byte)((tmpValue.intValue() & 0x7f) | 0x80); tmpValue = tmpValue.shiftRight(7); } tmp[byteCount - 1] &= 0x7f; out.write(tmp, 0, tmp.length); } } private void doOutput(ByteArrayOutputStream aOut) { OIDTokenizer tok = new OIDTokenizer(identifier); int first = Integer.parseInt(tok.nextToken()) * 40; String secondToken = tok.nextToken(); if (secondToken.length() <= 18) { writeField(aOut, first + Long.parseLong(secondToken)); } else { writeField(aOut, new BigInteger(secondToken).add(BigInteger.valueOf(first))); } while (tok.hasMoreTokens()) { String token = tok.nextToken(); if (token.length() <= 18) { writeField(aOut, Long.parseLong(token)); } else { writeField(aOut, new BigInteger(token)); } } } protected synchronized byte[] getBody() { if (body == null) { ByteArrayOutputStream bOut = new ByteArrayOutputStream(); doOutput(bOut); body = bOut.toByteArray(); } return body; } boolean isConstructed() { return false; } int encodedLength() throws IOException { int length = getBody().length; return 1 + StreamUtil.calculateBodyLength(length) + length; } void encode( ASN1OutputStream out) throws IOException { byte[] enc = getBody(); out.write(BERTags.OBJECT_IDENTIFIER); out.writeLength(enc.length); out.write(enc); } public int hashCode() { return identifier.hashCode(); } boolean asn1Equals( ASN1Primitive o) { if (!(o instanceof DERObjectIdentifier)) { return false; } return identifier.equals(((DERObjectIdentifier)o).identifier); } public String toString() { return getId(); } private static boolean isValidBranchID( String branchID, int start) { boolean periodAllowed = false; int pos = branchID.length(); while (--pos >= start) { char ch = branchID.charAt(pos); // TODO Leading zeroes? if ('0' <= ch && ch <= '9') { periodAllowed = true; continue; } if (ch == '.') { if (!periodAllowed) { return false; } periodAllowed = false; continue; } return false; } return periodAllowed; } private static boolean isValidIdentifier( String identifier) { if (identifier.length() < 3 || identifier.charAt(1) != '.') { return false; } char first = identifier.charAt(0); if (first < '0' || first > '2') { return false; } return isValidBranchID(identifier, 2); } private static ASN1ObjectIdentifier[][] cache = new ASN1ObjectIdentifier[256][]; static ASN1ObjectIdentifier fromOctetString(byte[] enc) { if (enc.length < 3) { return new ASN1ObjectIdentifier(enc); } int idx1 = enc[enc.length - 2] & 0xff; // in this case top bit is always zero int idx2 = enc[enc.length - 1] & 0x7f; ASN1ObjectIdentifier possibleMatch; synchronized (cache) { ASN1ObjectIdentifier[] first = cache[idx1]; if (first == null) { first = cache[idx1] = new ASN1ObjectIdentifier[128]; } possibleMatch = first[idx2]; if (possibleMatch == null) { return first[idx2] = new ASN1ObjectIdentifier(enc); } if (Arrays.areEqual(enc, possibleMatch.getBody())) { return possibleMatch; } idx1 = (idx1 + 1) & 0xff; first = cache[idx1]; if (first == null) { first = cache[idx1] = new ASN1ObjectIdentifier[128]; } possibleMatch = first[idx2]; if (possibleMatch == null) { return first[idx2] = new ASN1ObjectIdentifier(enc); } if (Arrays.areEqual(enc, possibleMatch.getBody())) { return possibleMatch; } idx2 = (idx2 + 1) & 0x7f; possibleMatch = first[idx2]; if (possibleMatch == null) { return first[idx2] = new ASN1ObjectIdentifier(enc); } } if (Arrays.areEqual(enc, possibleMatch.getBody())) { return possibleMatch; } return new ASN1ObjectIdentifier(enc); } }
apache-2.0
FangWW/meinv
app/src/main/java/com/meinv/interactor/HomeInteractor.java
1077
/* * Copyright (c) 2015 [1076559197@qq.com | tchen0707@gmail.com] * * Licensed under the Apache License, Version 2.0 (the "Licenseโ€); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.meinv.interactor; import android.content.Context; import com.library.base.BaseLazyFragment; import com.meinv.bean.NavigationEntity; import java.util.List; /** * Author: Tau.Chen * Email: 1076559197@qq.com | tauchen1990@gmail.com * Date: 2015/3/12. * Description: */ public interface HomeInteractor { List<BaseLazyFragment> getPagerFragments(); List<NavigationEntity> getNavigationListData(Context context); }
apache-2.0
taichi/okite
src/main/java/ninja/siden/okite/compiler/emitter/ValidateEmitter.java
1914
/* * Copyright 2015 SATO taichi * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ninja.siden.okite.compiler.emitter; import java.io.PrintWriter; import java.util.Optional; import javax.lang.model.element.AnnotationMirror; import javax.lang.model.element.AnnotationValue; import javax.lang.model.element.Element; import javax.lang.model.element.Name; import javax.lang.model.type.TypeMirror; import ninja.siden.okite.Constraint; import ninja.siden.okite.compiler.AnnotationValues; import ninja.siden.okite.compiler.ConstraintEmitter; import ninja.siden.okite.compiler.Env; import ninja.siden.okite.compiler.RoundEnvironment; /** * @author taichi */ public class ValidateEmitter implements ConstraintEmitter { @Override public boolean emit(Env env, RoundEnvironment roundEnv, PrintWriter pw, AnnotationMirror am, Element element, TypeMirror type) { Name sn = element.getSimpleName(); Optional<? extends AnnotationValue> opt = env.values.get(am, "policy") .findFirst(); String policy = opt .flatMap(AnnotationValues::readEnum) .map(ve -> { return Constraint.Policy.class.getCanonicalName() + "." + ve.getSimpleName(); }) .orElse(Constraint.Policy.ContinueToNextTarget.getClass() .getCanonicalName()); pw.printf( "validations.add((v, c) -> convert(%s, v.%s(newContext(c, \"%s\"))));", policy, sn, sn); return true; } }
apache-2.0
support-project/knowledge
src/test/java/org/support/project/knowledge/tool/DBStart.java
746
package org.support.project.knowledge.tool; import org.h2.tools.Server; import org.support.project.common.config.ConfigLoader; import org.support.project.web.config.AppConfig; public class DBStart { public static void main(String[] args) throws Exception { AppConfig appConfig = ConfigLoader.load(AppConfig.APP_CONFIG, AppConfig.class); String[] parms = { "-tcp", "-baseDir", appConfig.getDatabasePath() }; Server server = Server.createTcpServer(parms); server.start(); System.out.println("Database start..."); int count = 0; while (true) { Thread.sleep(1000); count++; if (count > 300) { break; } } } }
apache-2.0
ChusSenosiain/PhotoChop
PhotoChop/app/src/main/java/es/molestudio/photochop/model/User.java
906
package es.molestudio.photochop.model; /** * Created by Chus on 04/03/15. */ public class User { private String mUserId; private String mUserNickName; private String mUserEmail; private String mUserPassword; public User() { } public String getUserId() { return mUserId; } public void setUserId(String userId) { mUserId = userId; } public String getUserNickName() { return mUserNickName; } public void setUserNickName(String userNickName) { mUserNickName = userNickName; } public String getUserEmail() { return mUserEmail; } public void setUserEmail(String userEmail) { mUserEmail = userEmail; } public String getUserPassword() { return mUserPassword; } public void setUserPassword(String userPassword) { mUserPassword = userPassword; } }
apache-2.0
lgobinath/siddhi
modules/siddhi-core/src/main/java/org/wso2/siddhi/core/stream/input/source/InMemorySource.java
3859
/* * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.siddhi.core.stream.input.source; import org.apache.log4j.Logger; import org.wso2.siddhi.annotation.Example; import org.wso2.siddhi.annotation.Extension; import org.wso2.siddhi.annotation.Parameter; import org.wso2.siddhi.annotation.util.DataType; import org.wso2.siddhi.core.config.ExecutionPlanContext; import org.wso2.siddhi.core.exception.ConnectionUnavailableException; import org.wso2.siddhi.core.util.config.ConfigReader; import org.wso2.siddhi.core.util.transport.InMemoryBroker; import org.wso2.siddhi.core.util.transport.OptionHolder; import java.util.Map; /** * Implementation of {@link Source} to receive events through in-memory transport. */ @Extension( name = "inMemory", namespace = "source", description = "In-memory source that can communicate with other in-memory sinks within the same JVM, it " + "is assumed that the publisher and subscriber of a topic uses same event schema (stream definition).", parameters = @Parameter(name = "topic", type = DataType.STRING, description = "Subscribes to sent on the " + "given topic."), examples = @Example( syntax = "@source(type='inMemory', @map(type='passThrough'),\n" + "define stream BarStream (symbol string, price float, volume long)", description = "In this example BarStream uses inMemory transport which passes the received event " + "internally without using external transport." ) ) public class InMemorySource extends Source { private static final Logger log = Logger.getLogger(InMemorySource.class); private static final String TOPIC_KEY = "topic"; private SourceEventListener sourceEventListener; private InMemoryBroker.Subscriber subscriber; @Override public void init(SourceEventListener sourceEventListener, OptionHolder optionHolder, ConfigReader configReader, ExecutionPlanContext executionPlanContext) { this.sourceEventListener = sourceEventListener; String topic = optionHolder.validateAndGetStaticValue(TOPIC_KEY, "input inMemory source"); this.subscriber = new InMemoryBroker.Subscriber() { @Override public void onMessage(Object event) { sourceEventListener.onEvent(event); } @Override public String getTopic() { return topic; } }; } @Override public void connect() throws ConnectionUnavailableException { InMemoryBroker.subscribe(subscriber); } @Override public void disconnect() { InMemoryBroker.unsubscribe(subscriber); } @Override public void destroy() { // do nothing } @Override public void pause() { InMemoryBroker.unsubscribe(subscriber); } @Override public void resume() { InMemoryBroker.subscribe(subscriber); } @Override public Map<String, Object> currentState() { return null; } @Override public void restoreState(Map<String, Object> state) { // no state } }
apache-2.0
ufoscout/ApacheSparck-POC
src/test/java/ufo/test/spark/SparkApplicationTests.java
275
package ufo.test.spark; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest public abstract class SparkApplicationTests { }
apache-2.0
hortonworks/cloudbreak
cloud-reactor-api/src/main/java/com/sequenceiq/cloudbreak/cloud/event/resource/LaunchStackRequest.java
1253
package com.sequenceiq.cloudbreak.cloud.event.resource; import java.util.StringJoiner; import com.sequenceiq.cloudbreak.cloud.context.CloudContext; import com.sequenceiq.cloudbreak.cloud.model.CloudCredential; import com.sequenceiq.cloudbreak.cloud.model.CloudStack; import com.sequenceiq.common.api.adjustment.AdjustmentTypeWithThreshold; import com.sequenceiq.common.api.type.AdjustmentType; public class LaunchStackRequest extends CloudStackRequest<LaunchStackResult> { private final AdjustmentTypeWithThreshold adjustmentTypeWithThreshold; public LaunchStackRequest(CloudContext cloudCtx, CloudCredential cloudCredential, CloudStack cloudStack, AdjustmentType adjustmentType, Long threshold) { super(cloudCtx, cloudCredential, cloudStack); this.adjustmentTypeWithThreshold = new AdjustmentTypeWithThreshold(adjustmentType, threshold); } public AdjustmentTypeWithThreshold getAdjustmentWithThreshold() { return adjustmentTypeWithThreshold; } @Override public String toString() { return new StringJoiner(", ", LaunchStackRequest.class.getSimpleName() + "[", "]") .add("adjustmentTypeWithThreshold=" + adjustmentTypeWithThreshold) .toString(); } }
apache-2.0
heriram/incubator-asterixdb
asterixdb/asterix-common/src/main/java/org/apache/asterix/common/config/ClusterProperties.java
4355
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.asterix.common.config; import java.io.InputStream; import java.util.Optional; import java.util.stream.Collectors; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Unmarshaller; import org.apache.asterix.common.replication.IReplicationStrategy; import org.apache.asterix.common.replication.ReplicationStrategyFactory; import org.apache.asterix.event.schema.cluster.Cluster; import org.apache.asterix.event.schema.cluster.Node; import org.apache.asterix.event.schema.cluster.Replica; import org.apache.commons.lang3.StringUtils; import org.apache.hyracks.api.exceptions.HyracksDataException; public class ClusterProperties { public static final ClusterProperties INSTANCE = new ClusterProperties(); public static final String CLUSTER_CONFIGURATION_FILE = "cluster.xml"; public static final String DEFAULT_STORAGE_DIR_NAME = "storage"; private String nodeNamePrefix = StringUtils.EMPTY; private Cluster cluster; private ClusterProperties() { InputStream is = this.getClass().getClassLoader().getResourceAsStream(CLUSTER_CONFIGURATION_FILE); if (is != null) { try { JAXBContext ctx = JAXBContext.newInstance(Cluster.class); Unmarshaller unmarshaller = ctx.createUnmarshaller(); cluster = (Cluster) unmarshaller.unmarshal(is); nodeNamePrefix = cluster.getInstanceName() + "_"; updateNodeIdToFullName(); } catch (JAXBException e) { throw new IllegalStateException("Failed to read configuration file " + CLUSTER_CONFIGURATION_FILE, e); } } } public Cluster getCluster() { return cluster; } public String getStorageDirectoryName() { if (cluster != null) { return cluster.getStore(); } // virtual cluster without cluster config file return DEFAULT_STORAGE_DIR_NAME; } public Node getNodeById(String nodeId) { Optional<Node> matchingNode = cluster.getNode().stream().filter(node -> node.getId().equals(nodeId)).findAny(); return matchingNode.isPresent() ? matchingNode.get() : null; } public int getNodeIndex(String nodeId) { for (int i = 0; i < cluster.getNode().size(); i++) { Node node = cluster.getNode().get(i); if (node.getId().equals(nodeId)) { return i; } } return -1; } public IReplicationStrategy getReplicationStrategy() throws HyracksDataException { return ReplicationStrategyFactory.create(cluster); } private String getNodeFullName(String nodeId) { if (nodeId.startsWith(nodeNamePrefix)) { return nodeId; } return nodeNamePrefix + nodeId; } private void updateNodeIdToFullName() { cluster.getNode().forEach(node -> node.setId(getNodeFullName(node.getId()))); if (cluster.getMetadataNode() != null) { cluster.setMetadataNode(getNodeFullName(cluster.getMetadataNode())); } if (cluster.getHighAvailability() != null && cluster.getHighAvailability().getFaultTolerance() != null && cluster.getHighAvailability().getFaultTolerance().getReplica() != null) { Replica replicas = cluster.getHighAvailability().getFaultTolerance().getReplica(); replicas.setNodeId(replicas.getNodeId().stream().map(this::getNodeFullName).collect(Collectors.toList())); } } }
apache-2.0
bhargavms/QrCodeGenerator
sample/src/androidTest/java/com/bhargavms/qrcodegenerator/ExampleInstrumentedTest.java
762
package com.bhargavms.qrcodegenerator; import android.content.Context; import android.support.test.InstrumentationRegistry; import android.support.test.runner.AndroidJUnit4; import org.junit.Test; import org.junit.runner.RunWith; import static org.junit.Assert.*; /** * Instrumentation test, which will execute on an Android device. * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ @RunWith(AndroidJUnit4.class) public class ExampleInstrumentedTest { @Test public void useAppContext() throws Exception { // Context of the app under test. Context appContext = InstrumentationRegistry.getTargetContext(); assertEquals("com.bhargavms.qrcodegenerator", appContext.getPackageName()); } }
apache-2.0
fchrist/companian
cpmodel/src/main/java/de/fct/fdmm/architecturedl/behaviordl/BehaviorDlProxy.java
924
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fct.fdmm.architecturedl.behaviordl; public interface BehaviorDlProxy { public Process getProcess(String processFile); }
apache-2.0
ahjsrhj/Projects
NewLogin/app/src/main/java/cn/imrhj/newlogin/model/UserInfo.java
871
package cn.imrhj.newlogin.model; import android.text.TextUtils; import android.util.Base64; /** * Created by rhj on 16/4/17. * ็”จๆˆทไฟกๆฏๅฎžไฝ“็ฑป */ public class UserInfo { private String username; private String password; public UserInfo(String username, String password) { this.username = username; this.password = password; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public boolean isEmpty() { if (TextUtils.isEmpty(username) || TextUtils.isEmpty(password)) { return true; } else { return false; } } }
apache-2.0
twuni/xmppt
src/main/java/org/twuni/xmppt/xmpp/sasl/SASLSuccess.java
418
package org.twuni.xmppt.xmpp.sasl; import org.twuni.xmppt.xml.XMLElement; public class SASLSuccess extends Success { public static boolean is( XMLElement element ) { return Success.is( element ) && element.belongsTo( SASLAuthentication.NAMESPACE ); } public static SASLSuccess from( XMLElement element ) { return new SASLSuccess(); } public SASLSuccess() { super( SASLAuthentication.NAMESPACE ); } }
apache-2.0
LifeLogTLeaf/TLeafDiaryAndroid
src/com/tleaf/tiary/util/SemiRoundImageView.java
4133
package com.tleaf.tiary.util; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Bitmap.Config; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.PorterDuff; import android.graphics.PorterDuffXfermode; import android.graphics.Rect; import android.graphics.RectF; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.util.AttributeSet; import android.widget.ImageView; import com.tleaf.tiary.R; /** ์ด๋ฏธ์ง€ ๋ทฐ์˜ ์ƒ๋‹จ ๋ถ€๋ถ„๋งŒ ๋ผ์šด๋”ฉ ํ•ด์ฃผ๋Š” ์ปค์Šคํ…€ ์ด๋ฏธ์ง€๋ทฐ * ๋‹ค์ด์–ด๋ฆฌ ๋ฆฌ์ŠคํŠธ ๋ทฐ์˜ ํ•œ ๋‹ค์ด์–ด๋ฆฌ ์ด๋ฏธ์ง€์— ์‚ฌ์šฉํ•œ๋‹ค**/ public class SemiRoundImageView extends ImageView { public SemiRoundImageView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); init(context); } public SemiRoundImageView(Context context, AttributeSet attrs) { super(context, attrs); init(context); } public SemiRoundImageView(Context context) { super(context); init(context); } private void init(Context context) { setBackgroundResource(R.drawable.shape); } @Override protected void onDraw(Canvas canvas) { // super.onDraw(canvas); Drawable drawable = getDrawable(); if (drawable == null || ((BitmapDrawable) drawable).getBitmap() == null) { super.onDraw(canvas); return; } Bitmap b = ((BitmapDrawable) drawable).getBitmap(); Bitmap bitmap = b.copy(Bitmap.Config.ARGB_8888, true); int w = getWidth(), h = getHeight(); int pixels = (int) (3 * getResources().getDisplayMetrics().density); Bitmap roundBitmap = RoundImageView.getRoundedCornerBitmap( getContext(), bitmap, pixels, w, h, false, false, true, true); canvas.drawBitmap(roundBitmap, 0, 0, null); } public static Bitmap getRoundedCornerBitmap(Context context, Bitmap input, int pixels, int w, int h, boolean squareTL, boolean squareTR, boolean squareBL, boolean squareBR) { Bitmap output = Bitmap.createBitmap(w, h, Config.ARGB_8888); Canvas canvas = new Canvas(output); final float densityMultiplier = context.getResources() .getDisplayMetrics().density; final int color = context.getResources().getColor( R.color.background_skyblue); final Paint paint = new Paint(); final Rect rect = new Rect(0, 0, w, h); final RectF rectF = new RectF(rect); // make sure that our rounded corner is scaled appropriately final float roundPx = pixels * densityMultiplier; paint.setAntiAlias(true); canvas.drawARGB(0, 0, 0, 0); paint.setColor(color); canvas.drawRoundRect(rectF, roundPx, roundPx, paint); // draw rectangles over the corners we want to be square if (squareTL) { canvas.drawRect(0, 0, w / 2, h / 2, paint); } if (squareTR) { canvas.drawRect(w / 2, 0, w, h / 2, paint); } if (squareBL) { canvas.drawRect(0, h / 2, w / 2, h, paint); } if (squareBR) { canvas.drawRect(w / 2, h / 2, w, h, paint); } paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN)); int sourceWidth = input.getWidth(); int sourceHeight = input.getHeight(); float xScale = (float) w / sourceWidth; float yScale = (float) h / sourceHeight; float scale;// = Math.max(xScale, yScale); scale = Math.max(xScale, yScale); // Now get the size of the source bitmap when scaled float scaledWidth = scale * sourceWidth; float scaledHeight = scale * sourceHeight; // Let's find out the upper left coordinates if the scaled bitmap // should be centered in the new size give by the parameters float left = (w - scaledWidth) / 2; float top = (h - scaledHeight) / 2; // The target rectangle for the new, scaled version of the source bitmap // will now // be RectF targetRect = new RectF(left, top, left + scaledWidth, top + scaledHeight); // Finally, we create a new bitmap of the specified size and draw our // new, // scaled bitmap onto it. canvas.drawBitmap(input, null, targetRect, paint); // Bitmap scaled = Bitmap.createScaledBitmap(input, w, h, true); // canvas.drawBitmap(scaled, 0, 0, paint); return output; } }
apache-2.0
ceylon/ceylon
cmr-aether/src/org/eclipse/ceylon/cmr/resolver/aether/DependencyDescriptor.java
1066
/******************************************************************************** * Copyright (c) 2011-2017 Red Hat Inc. and/or its affiliates and others * * This program and the accompanying materials are made available under the * terms of the Apache License, Version 2.0 which is available at * http://www.apache.org/licenses/LICENSE-2.0 * * SPDX-License-Identifier: Apache-2.0 ********************************************************************************/ package org.eclipse.ceylon.cmr.resolver.aether; import java.io.File; import java.util.List; public interface DependencyDescriptor { public File getFile(); public List<DependencyDescriptor> getDependencies(); public List<ExclusionDescriptor> getExclusions(); public String getGroupId(); public String getArtifactId(); public String getClassifier(); public String getVersion(); public boolean isOptional(); public boolean isProvidedScope(); public boolean isCompileScope(); public boolean isRuntimeScope(); public boolean isTestScope(); }
apache-2.0
GE159/Weather-S
src/com/gwk/weathers/model/City.java
767
package com.gwk.weathers.model; import android.R.integer; /* *ไฝœ่€…๏ผš่‘›ๆ–‡ๅ‡ฏ *้‚ฎ็ฎฑ๏ผš651517957@qq.com *ๆ—ถ้—ด๏ผš2015ๅนด12ๆœˆ1ๆ—ฅไธŠๅˆ11:34:22 */ public class City { private int id; private String cityName; private String cityCode; private int provinceId; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getCityName() { return cityName; } public void setCityName(String cityName) { this.cityName = cityName; } public String getCityCode() { return cityCode; } public void setCityCode(String cityCode) { this.cityCode = cityCode; } public int getProvinceId() { return provinceId; } public void setProvinceId(int provinceId) { this.provinceId = provinceId; } }
apache-2.0
lburgazzoli/spring-cloud-etcd
spring-cloud-etcd-core/src/main/java/org/springframework/cloud/etcd/EtcdEndpoint.java
1339
/* * Copyright 2013-2015 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.cloud.etcd; import mousio.etcd4j.EtcdClient; import org.springframework.boot.actuate.endpoint.AbstractEndpoint; import org.springframework.boot.context.properties.ConfigurationProperties; /** * @author Spencer Gibb */ @ConfigurationProperties(prefix = "endpoints.etcd", ignoreUnknownFields = false) public class EtcdEndpoint extends AbstractEndpoint<EtcdEndpoint.Data> { private EtcdClient etcd; public EtcdEndpoint(EtcdClient etcd) { super("etcd", false, true); this.etcd = etcd; } @Override public Data invoke() { Data data = new Data(); data.setVersion(etcd.getVersion()); return data; } @lombok.Data public static class Data { private String version; } }
apache-2.0
Haulmont/platform-sample-library
modules/gui/src/com/sample/library/gui/bookpublication/YearFormatter.java
1203
/* * Copyright (c) 2015 Haulmont * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.sample.library.gui.bookpublication; import com.haulmont.cuba.gui.components.Formatter; /** * This formatter is needed because the default format for {@link com.haulmont.chile.core.datatypes.impl.IntegerDatatype} * contains grouping separator. We could redefine the whole <code>datatypes.xml</code> for the project, but we * chose to create this custom formatter and use it in UI components explicitly. */ public class YearFormatter implements Formatter<Integer> { @Override public String format(Integer value) { return value == null ? "" : String.valueOf(value); } }
apache-2.0
fernandojerez/ff
src/main/asm/ff/org/objectweb/asm/ClassReader.java
81405
/*** * ASM: a very small and fast Java bytecode manipulation framework * Copyright (c) 2000-2011 INRIA, France Telecom * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ package ff.org.objectweb.asm; import java.io.IOException; import java.io.InputStream; /** * A Java class parser to make a {@link ClassVisitor} visit an existing class. * This class parses a byte array conforming to the Java class file format and * calls the appropriate visit methods of a given class visitor for each field, * method and bytecode instruction encountered. * * @author Eric Bruneton * @author Eugene Kuleshov */ public class ClassReader { /** * True to enable signatures support. */ static final boolean SIGNATURES = true; /** * True to enable annotations support. */ static final boolean ANNOTATIONS = true; /** * True to enable stack map frames support. */ static final boolean FRAMES = true; /** * True to enable bytecode writing support. */ static final boolean WRITER = true; /** * True to enable JSR_W and GOTO_W support. */ static final boolean RESIZE = true; /** * Flag to skip method code. If this class is set <code>CODE</code> * attribute won't be visited. This can be used, for example, to retrieve * annotations for methods and method parameters. */ public static final int SKIP_CODE = 1; /** * Flag to skip the debug information in the class. If this flag is set the * debug information of the class is not visited, i.e. the * {@link MethodVisitor#visitLocalVariable visitLocalVariable} and * {@link MethodVisitor#visitLineNumber visitLineNumber} methods will not be * called. */ public static final int SKIP_DEBUG = 2; /** * Flag to skip the stack map frames in the class. If this flag is set the * stack map frames of the class is not visited, i.e. the * {@link MethodVisitor#visitFrame visitFrame} method will not be called. * This flag is useful when the {@link ClassWriter#COMPUTE_FRAMES} option is * used: it avoids visiting frames that will be ignored and recomputed from * scratch in the class writer. */ public static final int SKIP_FRAMES = 4; /** * Flag to expand the stack map frames. By default stack map frames are * visited in their original format (i.e. "expanded" for classes whose * version is less than V1_6, and "compressed" for the other classes). If * this flag is set, stack map frames are always visited in expanded format * (this option adds a decompression/recompression step in ClassReader and * ClassWriter which degrades performances quite a lot). */ public static final int EXPAND_FRAMES = 8; /** * Flag to expand the ASM pseudo instructions into an equivalent sequence of * standard bytecode instructions. When resolving a forward jump it may * happen that the signed 2 bytes offset reserved for it is not sufficient * to store the bytecode offset. In this case the jump instruction is * replaced with a temporary ASM pseudo instruction using an unsigned 2 * bytes offset (see Label#resolve). This internal flag is used to re-read * classes containing such instructions, in order to replace them with * standard instructions. In addition, when this flag is used, GOTO_W and * JSR_W are <i>not</i> converted into GOTO and JSR, to make sure that * infinite loops where a GOTO_W is replaced with a GOTO in ClassReader and * converted back to a GOTO_W in ClassWriter cannot occur. */ static final int EXPAND_ASM_INSNS = 256; /** * Reads the bytecode of a class. * * @param is * an input stream from which to read the class. * @param close * true to close the input stream after reading. * @return the bytecode read from the given input stream. * @throws IOException * if a problem occurs during reading. */ private static byte[] readClass(final InputStream is, boolean close) throws IOException { if (is == null) { throw new IOException("Class not found"); } try { byte[] b = new byte[is.available()]; int len = 0; while (true) { int n = is.read(b, len, b.length - len); if (n == -1) { if (len < b.length) { byte[] c = new byte[len]; System.arraycopy(b, 0, c, 0, len); b = c; } return b; } len += n; if (len == b.length) { int last = is.read(); if (last < 0) { return b; } byte[] c = new byte[b.length + 1000]; System.arraycopy(b, 0, c, 0, len); c[len++] = (byte) last; b = c; } } } finally { if (close) { is.close(); } } } /** * The class to be parsed. <i>The content of this array must not be * modified. This field is intended for {@link Attribute} sub classes, and * is normally not needed by class generators or adapters.</i> */ public final byte[] b; /** * The start index of each constant pool item in {@link #b b}, plus one. The * one byte offset skips the constant pool item tag that indicates its type. */ private final int[] items; /** * The String objects corresponding to the CONSTANT_Utf8 items. This cache * avoids multiple parsing of a given CONSTANT_Utf8 constant pool item, * which GREATLY improves performances (by a factor 2 to 3). This caching * strategy could be extended to all constant pool items, but its benefit * would not be so great for these items (because they are much less * expensive to parse than CONSTANT_Utf8 items). */ private final String[] strings; /** * Maximum length of the strings contained in the constant pool of the * class. */ private final int maxStringLength; // ------------------------------------------------------------------------ // Constructors // ------------------------------------------------------------------------ /** * Start index of the class header information (access, name...) in * {@link #b b}. */ public final int header; /** * Constructs a new {@link ClassReader} object. * * @param b * the bytecode of the class to be read. */ public ClassReader(final byte[] b) { this(b, 0, b.length); } /** * Constructs a new {@link ClassReader} object. * * @param b * the bytecode of the class to be read. * @param off * the start offset of the class data. * @param len * the length of the class data. */ public ClassReader(final byte[] b, final int off, final int len) { this.b = b; // checks the class version if (readShort(off + 6) > Opcodes.V1_8) { throw new IllegalArgumentException(); } // parses the constant pool items = new int[readUnsignedShort(off + 8)]; int n = items.length; strings = new String[n]; int max = 0; int index = off + 10; for (int i = 1; i < n; ++i) { items[i] = index + 1; int size; switch (b[index]) { case ClassWriter.FIELD: case ClassWriter.METH: case ClassWriter.IMETH: case ClassWriter.INT: case ClassWriter.FLOAT: case ClassWriter.NAME_TYPE: case ClassWriter.INDY: size = 5; break; case ClassWriter.LONG: case ClassWriter.DOUBLE: size = 9; ++i; break; case ClassWriter.UTF8: size = 3 + readUnsignedShort(index + 1); if (size > max) { max = size; } break; case ClassWriter.HANDLE: size = 4; break; // case ClassWriter.CLASS: // case ClassWriter.STR: // case ClassWriter.MTYPE default: size = 3; break; } index += size; } maxStringLength = max; // the class header information starts just after the constant pool header = index; } /** * Constructs a new {@link ClassReader} object. * * @param is * an input stream from which to read the class. * @throws IOException * if a problem occurs during reading. */ public ClassReader(final InputStream is) throws IOException { this(readClass(is, false)); } /** * Constructs a new {@link ClassReader} object. * * @param name * the binary qualified name of the class to be read. * @throws IOException * if an exception occurs during reading. */ public ClassReader(final String name) throws IOException { this(readClass(ClassLoader.getSystemResourceAsStream(name.replace('.', '/') + ".class"), true)); } /** * Makes the given visitor visit the Java class of this {@link ClassReader}. * This class is the one specified in the constructor (see * {@link #ClassReader(byte[]) ClassReader}). * * @param classVisitor * the visitor that must visit this class. * @param attrs * prototypes of the attributes that must be parsed during the * visit of the class. Any attribute whose type is not equal to * the type of one the prototypes will not be parsed: its byte * array value will be passed unchanged to the ClassWriter. * <i>This may corrupt it if this value contains references to * the constant pool, or has syntactic or semantic links with a * class element that has been transformed by a class adapter * between the reader and the writer</i>. * @param flags * option flags that can be used to modify the default behavior * of this class. See {@link #SKIP_DEBUG}, {@link #EXPAND_FRAMES} * , {@link #SKIP_FRAMES}, {@link #SKIP_CODE}. */ public void accept(final ClassVisitor classVisitor, final Attribute[] attrs, final int flags) { int u = header; // current offset in the class file char[] c = new char[maxStringLength]; // buffer used to read strings Context context = new Context(); context.attrs = attrs; context.flags = flags; context.buffer = c; // reads the class declaration int access = readUnsignedShort(u); String name = readClass(u + 2, c); String superClass = readClass(u + 4, c); String[] interfaces = new String[readUnsignedShort(u + 6)]; u += 8; for (int i = 0; i < interfaces.length; ++i) { interfaces[i] = readClass(u, c); u += 2; } // reads the class attributes String signature = null; String sourceFile = null; String sourceDebug = null; String enclosingOwner = null; String enclosingName = null; String enclosingDesc = null; int anns = 0; int ianns = 0; int tanns = 0; int itanns = 0; int innerClasses = 0; Attribute attributes = null; u = getAttributes(); for (int i = readUnsignedShort(u); i > 0; --i) { String attrName = readUTF8(u + 2, c); // tests are sorted in decreasing frequency order // (based on frequencies observed on typical classes) if ("SourceFile".equals(attrName)) { sourceFile = readUTF8(u + 8, c); } else if ("InnerClasses".equals(attrName)) { innerClasses = u + 8; } else if ("EnclosingMethod".equals(attrName)) { enclosingOwner = readClass(u + 8, c); int item = readUnsignedShort(u + 10); if (item != 0) { enclosingName = readUTF8(items[item], c); enclosingDesc = readUTF8(items[item] + 2, c); } } else if (SIGNATURES && "Signature".equals(attrName)) { signature = readUTF8(u + 8, c); } else if (ANNOTATIONS && "RuntimeVisibleAnnotations".equals(attrName)) { anns = u + 8; } else if (ANNOTATIONS && "RuntimeVisibleTypeAnnotations".equals(attrName)) { tanns = u + 8; } else if ("Deprecated".equals(attrName)) { access |= Opcodes.ACC_DEPRECATED; } else if ("Synthetic".equals(attrName)) { access |= Opcodes.ACC_SYNTHETIC | ClassWriter.ACC_SYNTHETIC_ATTRIBUTE; } else if ("SourceDebugExtension".equals(attrName)) { int len = readInt(u + 4); sourceDebug = readUTF(u + 8, len, new char[len]); } else if (ANNOTATIONS && "RuntimeInvisibleAnnotations".equals(attrName)) { ianns = u + 8; } else if (ANNOTATIONS && "RuntimeInvisibleTypeAnnotations".equals(attrName)) { itanns = u + 8; } else if ("BootstrapMethods".equals(attrName)) { int[] bootstrapMethods = new int[readUnsignedShort(u + 8)]; for (int j = 0, v = u + 10; j < bootstrapMethods.length; j++) { bootstrapMethods[j] = v; v += 2 + readUnsignedShort(v + 2) << 1; } context.bootstrapMethods = bootstrapMethods; } else { Attribute attr = readAttribute(attrs, attrName, u + 8, readInt(u + 4), c, -1, null); if (attr != null) { attr.next = attributes; attributes = attr; } } u += 6 + readInt(u + 4); } // visits the class declaration classVisitor.visit(readInt(items[1] - 7), access, name, signature, superClass, interfaces); // visits the source and debug info if ((flags & SKIP_DEBUG) == 0 && (sourceFile != null || sourceDebug != null)) { classVisitor.visitSource(sourceFile, sourceDebug); } // visits the outer class if (enclosingOwner != null) { classVisitor.visitOuterClass(enclosingOwner, enclosingName, enclosingDesc); } // visits the class annotations and type annotations if (ANNOTATIONS && anns != 0) { for (int i = readUnsignedShort(anns), v = anns + 2; i > 0; --i) { v = readAnnotationValues(v + 2, c, true, classVisitor.visitAnnotation(readUTF8(v, c), true)); } } if (ANNOTATIONS && ianns != 0) { for (int i = readUnsignedShort(ianns), v = ianns + 2; i > 0; --i) { v = readAnnotationValues(v + 2, c, true, classVisitor.visitAnnotation(readUTF8(v, c), false)); } } if (ANNOTATIONS && tanns != 0) { for (int i = readUnsignedShort(tanns), v = tanns + 2; i > 0; --i) { v = readAnnotationTarget(context, v); v = readAnnotationValues(v + 2, c, true, classVisitor.visitTypeAnnotation(context.typeRef, context.typePath, readUTF8(v, c), true)); } } if (ANNOTATIONS && itanns != 0) { for (int i = readUnsignedShort(itanns), v = itanns + 2; i > 0; --i) { v = readAnnotationTarget(context, v); v = readAnnotationValues(v + 2, c, true, classVisitor.visitTypeAnnotation(context.typeRef, context.typePath, readUTF8(v, c), false)); } } // visits the attributes while (attributes != null) { Attribute attr = attributes.next; attributes.next = null; classVisitor.visitAttribute(attributes); attributes = attr; } // visits the inner classes if (innerClasses != 0) { int v = innerClasses + 2; for (int i = readUnsignedShort(innerClasses); i > 0; --i) { classVisitor.visitInnerClass(readClass(v, c), readClass(v + 2, c), readUTF8(v + 4, c), readUnsignedShort(v + 6)); v += 8; } } // visits the fields and methods u = header + 10 + 2 * interfaces.length; for (int i = readUnsignedShort(u - 2); i > 0; --i) { u = readField(classVisitor, context, u); } u += 2; for (int i = readUnsignedShort(u - 2); i > 0; --i) { u = readMethod(classVisitor, context, u); } // visits the end of the class classVisitor.visitEnd(); } /** * Makes the given visitor visit the Java class of this {@link ClassReader} * . This class is the one specified in the constructor (see * {@link #ClassReader(byte[]) ClassReader}). * * @param classVisitor * the visitor that must visit this class. * @param flags * option flags that can be used to modify the default behavior * of this class. See {@link #SKIP_DEBUG}, {@link #EXPAND_FRAMES} * , {@link #SKIP_FRAMES}, {@link #SKIP_CODE}. */ public void accept(final ClassVisitor classVisitor, final int flags) { accept(classVisitor, new Attribute[0], flags); } /** * Copies the bootstrap method data into the given {@link ClassWriter}. * Should be called before the {@link #accept(ClassVisitor,int)} method. * * @param classWriter * the {@link ClassWriter} to copy bootstrap methods into. */ private void copyBootstrapMethods(final ClassWriter classWriter, final Item[] items, final char[] c) { // finds the "BootstrapMethods" attribute int u = getAttributes(); boolean found = false; for (int i = readUnsignedShort(u); i > 0; --i) { String attrName = readUTF8(u + 2, c); if ("BootstrapMethods".equals(attrName)) { found = true; break; } u += 6 + readInt(u + 4); } if (!found) { return; } // copies the bootstrap methods in the class writer int boostrapMethodCount = readUnsignedShort(u + 8); for (int j = 0, v = u + 10; j < boostrapMethodCount; j++) { int position = v - u - 10; int hashCode = readConst(readUnsignedShort(v), c).hashCode(); for (int k = readUnsignedShort(v + 2); k > 0; --k) { hashCode ^= readConst(readUnsignedShort(v + 4), c).hashCode(); v += 2; } v += 4; Item item = new Item(j); item.set(position, hashCode & 0x7FFFFFFF); int index = item.hashCode % items.length; item.next = items[index]; items[index] = item; } int attrSize = readInt(u + 4); ByteVector bootstrapMethods = new ByteVector(attrSize + 62); bootstrapMethods.putByteArray(b, u + 10, attrSize - 2); classWriter.bootstrapMethodsCount = boostrapMethodCount; classWriter.bootstrapMethods = bootstrapMethods; } /** * Copies the constant pool data into the given {@link ClassWriter}. Should * be called before the {@link #accept(ClassVisitor,int)} method. * * @param classWriter * the {@link ClassWriter} to copy constant pool into. */ void copyPool(final ClassWriter classWriter) { char[] buf = new char[maxStringLength]; int ll = items.length; Item[] items2 = new Item[ll]; for (int i = 1; i < ll; i++) { int index = items[i]; int tag = b[index - 1]; Item item = new Item(i); int nameType; switch (tag) { case ClassWriter.FIELD: case ClassWriter.METH: case ClassWriter.IMETH: nameType = items[readUnsignedShort(index + 2)]; item.set(tag, readClass(index, buf), readUTF8(nameType, buf), readUTF8(nameType + 2, buf)); break; case ClassWriter.INT: item.set(readInt(index)); break; case ClassWriter.FLOAT: item.set(Float.intBitsToFloat(readInt(index))); break; case ClassWriter.NAME_TYPE: item.set(tag, readUTF8(index, buf), readUTF8(index + 2, buf), null); break; case ClassWriter.LONG: item.set(readLong(index)); ++i; break; case ClassWriter.DOUBLE: item.set(Double.longBitsToDouble(readLong(index))); ++i; break; case ClassWriter.UTF8: { String s = strings[i]; if (s == null) { index = items[i]; s = strings[i] = readUTF(index + 2, readUnsignedShort(index), buf); } item.set(tag, s, null, null); break; } case ClassWriter.HANDLE: { int fieldOrMethodRef = items[readUnsignedShort(index + 1)]; nameType = items[readUnsignedShort(fieldOrMethodRef + 2)]; item.set(ClassWriter.HANDLE_BASE + readByte(index), readClass(fieldOrMethodRef, buf), readUTF8(nameType, buf), readUTF8(nameType + 2, buf)); break; } case ClassWriter.INDY: if (classWriter.bootstrapMethods == null) { copyBootstrapMethods(classWriter, items2, buf); } nameType = items[readUnsignedShort(index + 2)]; item.set(readUTF8(nameType, buf), readUTF8(nameType + 2, buf), readUnsignedShort(index)); break; // case ClassWriter.STR: // case ClassWriter.CLASS: // case ClassWriter.MTYPE default: item.set(tag, readUTF8(index, buf), null, null); break; } int index2 = item.hashCode % items2.length; item.next = items2[index2]; items2[index2] = item; } int off = items[1] - 1; classWriter.pool.putByteArray(b, off, header - off); classWriter.items = items2; classWriter.threshold = (int) (0.75d * ll); classWriter.index = ll; } /** * Returns the class's access flags (see {@link Opcodes}). This value may * not reflect Deprecated and Synthetic flags when bytecode is before 1.5 * and those flags are represented by attributes. * * @return the class access flags * * @see ClassVisitor#visit(int, int, String, String, String, String[]) */ public int getAccess() { return readUnsignedShort(header); } /** * Returns the start index of the attribute_info structure of this class. * * @return the start index of the attribute_info structure of this class. */ private int getAttributes() { // skips the header int u = header + 8 + readUnsignedShort(header + 6) * 2; // skips fields and methods for (int i = readUnsignedShort(u); i > 0; --i) { for (int j = readUnsignedShort(u + 8); j > 0; --j) { u += 6 + readInt(u + 12); } u += 8; } u += 2; for (int i = readUnsignedShort(u); i > 0; --i) { for (int j = readUnsignedShort(u + 8); j > 0; --j) { u += 6 + readInt(u + 12); } u += 8; } // the attribute_info structure starts just after the methods return u + 2; } // ------------------------------------------------------------------------ // Public methods // ------------------------------------------------------------------------ /** * Returns the internal name of the class (see {@link Type#getInternalName() * getInternalName}). * * @return the internal class name * * @see ClassVisitor#visit(int, int, String, String, String, String[]) */ public String getClassName() { return readClass(header + 2, new char[maxStringLength]); } /** * Computes the implicit frame of the method currently being parsed (as * defined in the given {@link Context}) and stores it in the given context. * * @param frame * information about the class being parsed. */ private void getImplicitFrame(final Context frame) { String desc = frame.desc; Object[] locals = frame.local; int local = 0; if ((frame.access & Opcodes.ACC_STATIC) == 0) { if ("<init>".equals(frame.name)) { locals[local++] = Opcodes.UNINITIALIZED_THIS; } else { locals[local++] = readClass(header + 2, frame.buffer); } } int i = 1; loop: while (true) { int j = i; switch (desc.charAt(i++)) { case 'Z': case 'C': case 'B': case 'S': case 'I': locals[local++] = Opcodes.INTEGER; break; case 'F': locals[local++] = Opcodes.FLOAT; break; case 'J': locals[local++] = Opcodes.LONG; break; case 'D': locals[local++] = Opcodes.DOUBLE; break; case '[': while (desc.charAt(i) == '[') { ++i; } if (desc.charAt(i) == 'L') { ++i; while (desc.charAt(i) != ';') { ++i; } } locals[local++] = desc.substring(j, ++i); break; case 'L': while (desc.charAt(i) != ';') { ++i; } locals[local++] = desc.substring(j + 1, i++); break; default: break loop; } } frame.localCount = local; } /** * Returns the internal names of the class's interfaces (see * {@link Type#getInternalName() getInternalName}). * * @return the array of internal names for all implemented interfaces or * <tt>null</tt>. * * @see ClassVisitor#visit(int, int, String, String, String, String[]) */ public String[] getInterfaces() { int index = header + 6; int n = readUnsignedShort(index); String[] interfaces = new String[n]; if (n > 0) { char[] buf = new char[maxStringLength]; for (int i = 0; i < n; ++i) { index += 2; interfaces[i] = readClass(index, buf); } } return interfaces; } /** * Returns the start index of the constant pool item in {@link #b b}, plus * one. <i>This method is intended for {@link Attribute} sub classes, and is * normally not needed by class generators or adapters.</i> * * @param item * the index a constant pool item. * @return the start index of the constant pool item in {@link #b b}, plus * one. */ public int getItem(final int item) { return items[item]; } /** * Returns the number of constant pool items in {@link #b b}. * * @return the number of constant pool items in {@link #b b}. */ public int getItemCount() { return items.length; } /** * Returns the maximum length of the strings contained in the constant pool * of the class. * * @return the maximum length of the strings contained in the constant pool * of the class. */ public int getMaxStringLength() { return maxStringLength; } /** * Returns the internal of name of the super class (see * {@link Type#getInternalName() getInternalName}). For interfaces, the * super class is {@link Object}. * * @return the internal name of super class, or <tt>null</tt> for * {@link Object} class. * * @see ClassVisitor#visit(int, int, String, String, String, String[]) */ public String getSuperName() { return readClass(header + 4, new char[maxStringLength]); } /** * Parses the header of a type annotation to extract its target_type and * target_path (the result is stored in the given context), and returns the * start offset of the rest of the type_annotation structure (i.e. the * offset to the type_index field, which is followed by * num_element_value_pairs and then the name,value pairs). * * @param context * information about the class being parsed. This is where the * extracted target_type and target_path must be stored. * @param u * the start offset of a type_annotation structure. * @return the start offset of the rest of the type_annotation structure. */ private int readAnnotationTarget(final Context context, int u) { int target = readInt(u); switch (target >>> 24) { case 0x00: // CLASS_TYPE_PARAMETER case 0x01: // METHOD_TYPE_PARAMETER case 0x16: // METHOD_FORMAL_PARAMETER target &= 0xFFFF0000; u += 2; break; case 0x13: // FIELD case 0x14: // METHOD_RETURN case 0x15: // METHOD_RECEIVER target &= 0xFF000000; u += 1; break; case 0x40: // LOCAL_VARIABLE case 0x41: { // RESOURCE_VARIABLE target &= 0xFF000000; int n = readUnsignedShort(u + 1); context.start = new Label[n]; context.end = new Label[n]; context.index = new int[n]; u += 3; for (int i = 0; i < n; ++i) { int start = readUnsignedShort(u); int length = readUnsignedShort(u + 2); context.start[i] = readLabel(start, context.labels); context.end[i] = readLabel(start + length, context.labels); context.index[i] = readUnsignedShort(u + 4); u += 6; } break; } case 0x47: // CAST case 0x48: // CONSTRUCTOR_INVOCATION_TYPE_ARGUMENT case 0x49: // METHOD_INVOCATION_TYPE_ARGUMENT case 0x4A: // CONSTRUCTOR_REFERENCE_TYPE_ARGUMENT case 0x4B: // METHOD_REFERENCE_TYPE_ARGUMENT target &= 0xFF0000FF; u += 4; break; // case 0x10: // CLASS_EXTENDS // case 0x11: // CLASS_TYPE_PARAMETER_BOUND // case 0x12: // METHOD_TYPE_PARAMETER_BOUND // case 0x17: // THROWS // case 0x42: // EXCEPTION_PARAMETER // case 0x43: // INSTANCEOF // case 0x44: // NEW // case 0x45: // CONSTRUCTOR_REFERENCE // case 0x46: // METHOD_REFERENCE default: target &= (target >>> 24) < 0x43 ? 0xFFFFFF00 : 0xFF000000; u += 3; break; } int pathLength = readByte(u); context.typeRef = target; context.typePath = pathLength == 0 ? null : new TypePath(b, u); return u + 1 + 2 * pathLength; } /** * Reads a value of an annotation and makes the given visitor visit it. * * @param v * the start offset in {@link #b b} of the value to be read * (<i>not including the value name constant pool index</i>). * @param buf * buffer to be used to call {@link #readUTF8 readUTF8}, * {@link #readClass(int,char[]) readClass} or {@link #readConst * readConst}. * @param name * the name of the value to be read. * @param av * the visitor that must visit the value. * @return the end offset of the annotation value. */ private int readAnnotationValue(int v, final char[] buf, final String name, final AnnotationVisitor av) { int i; if (av == null) { switch (b[v] & 0xFF) { case 'e': // enum_const_value return v + 5; case '@': // annotation_value return readAnnotationValues(v + 3, buf, true, null); case '[': // array_value return readAnnotationValues(v + 1, buf, false, null); default: return v + 3; } } switch (b[v++] & 0xFF) { case 'I': // pointer to CONSTANT_Integer case 'J': // pointer to CONSTANT_Long case 'F': // pointer to CONSTANT_Float case 'D': // pointer to CONSTANT_Double av.visit(name, readConst(readUnsignedShort(v), buf)); v += 2; break; case 'B': // pointer to CONSTANT_Byte av.visit(name, (byte) readInt(items[readUnsignedShort(v)])); v += 2; break; case 'Z': // pointer to CONSTANT_Boolean av.visit(name, readInt(items[readUnsignedShort(v)]) == 0 ? Boolean.FALSE : Boolean.TRUE); v += 2; break; case 'S': // pointer to CONSTANT_Short av.visit(name, (short) readInt(items[readUnsignedShort(v)])); v += 2; break; case 'C': // pointer to CONSTANT_Char av.visit(name, (char) readInt(items[readUnsignedShort(v)])); v += 2; break; case 's': // pointer to CONSTANT_Utf8 av.visit(name, readUTF8(v, buf)); v += 2; break; case 'e': // enum_const_value av.visitEnum(name, readUTF8(v, buf), readUTF8(v + 2, buf)); v += 4; break; case 'c': // class_info av.visit(name, Type.getType(readUTF8(v, buf))); v += 2; break; case '@': // annotation_value v = readAnnotationValues(v + 2, buf, true, av.visitAnnotation(name, readUTF8(v, buf))); break; case '[': // array_value int size = readUnsignedShort(v); v += 2; if (size == 0) { return readAnnotationValues(v - 2, buf, false, av.visitArray(name)); } switch (this.b[v++] & 0xFF) { case 'B': byte[] bv = new byte[size]; for (i = 0; i < size; i++) { bv[i] = (byte) readInt(items[readUnsignedShort(v)]); v += 3; } av.visit(name, bv); --v; break; case 'Z': boolean[] zv = new boolean[size]; for (i = 0; i < size; i++) { zv[i] = readInt(items[readUnsignedShort(v)]) != 0; v += 3; } av.visit(name, zv); --v; break; case 'S': short[] sv = new short[size]; for (i = 0; i < size; i++) { sv[i] = (short) readInt(items[readUnsignedShort(v)]); v += 3; } av.visit(name, sv); --v; break; case 'C': char[] cv = new char[size]; for (i = 0; i < size; i++) { cv[i] = (char) readInt(items[readUnsignedShort(v)]); v += 3; } av.visit(name, cv); --v; break; case 'I': int[] iv = new int[size]; for (i = 0; i < size; i++) { iv[i] = readInt(items[readUnsignedShort(v)]); v += 3; } av.visit(name, iv); --v; break; case 'J': long[] lv = new long[size]; for (i = 0; i < size; i++) { lv[i] = readLong(items[readUnsignedShort(v)]); v += 3; } av.visit(name, lv); --v; break; case 'F': float[] fv = new float[size]; for (i = 0; i < size; i++) { fv[i] = Float.intBitsToFloat(readInt(items[readUnsignedShort(v)])); v += 3; } av.visit(name, fv); --v; break; case 'D': double[] dv = new double[size]; for (i = 0; i < size; i++) { dv[i] = Double.longBitsToDouble(readLong(items[readUnsignedShort(v)])); v += 3; } av.visit(name, dv); --v; break; default: v = readAnnotationValues(v - 3, buf, false, av.visitArray(name)); } } return v; } /** * Reads the values of an annotation and makes the given visitor visit them. * * @param v * the start offset in {@link #b b} of the values to be read * (including the unsigned short that gives the number of * values). * @param buf * buffer to be used to call {@link #readUTF8 readUTF8}, * {@link #readClass(int,char[]) readClass} or {@link #readConst * readConst}. * @param named * if the annotation values are named or not. * @param av * the visitor that must visit the values. * @return the end offset of the annotation values. */ private int readAnnotationValues(int v, final char[] buf, final boolean named, final AnnotationVisitor av) { int i = readUnsignedShort(v); v += 2; if (named) { for (; i > 0; --i) { v = readAnnotationValue(v + 2, buf, readUTF8(v, buf), av); } } else { for (; i > 0; --i) { v = readAnnotationValue(v, buf, null, av); } } if (av != null) { av.visitEnd(); } return v; } /** * Reads an attribute in {@link #b b}. * * @param attrs * prototypes of the attributes that must be parsed during the * visit of the class. Any attribute whose type is not equal to * the type of one the prototypes is ignored (i.e. an empty * {@link Attribute} instance is returned). * @param type * the type of the attribute. * @param off * index of the first byte of the attribute's content in * {@link #b b}. The 6 attribute header bytes, containing the * type and the length of the attribute, are not taken into * account here (they have already been read). * @param len * the length of the attribute's content. * @param buf * buffer to be used to call {@link #readUTF8 readUTF8}, * {@link #readClass(int,char[]) readClass} or {@link #readConst * readConst}. * @param codeOff * index of the first byte of code's attribute content in * {@link #b b}, or -1 if the attribute to be read is not a code * attribute. The 6 attribute header bytes, containing the type * and the length of the attribute, are not taken into account * here. * @param labels * the labels of the method's code, or <tt>null</tt> if the * attribute to be read is not a code attribute. * @return the attribute that has been read, or <tt>null</tt> to skip this * attribute. */ private Attribute readAttribute(final Attribute[] attrs, final String type, final int off, final int len, final char[] buf, final int codeOff, final Label[] labels) { for (int i = 0; i < attrs.length; ++i) { if (attrs[i].type.equals(type)) { return attrs[i].read(this, off, len, buf, codeOff, labels); } } return new Attribute(type).read(this, off, len, null, -1, null); } /** * Reads a byte value in {@link #b b}. <i>This method is intended for * {@link Attribute} sub classes, and is normally not needed by class * generators or adapters.</i> * * @param index * the start index of the value to be read in {@link #b b}. * @return the read value. */ public int readByte(final int index) { return b[index] & 0xFF; } /** * Reads a class constant pool item in {@link #b b}. <i>This method is * intended for {@link Attribute} sub classes, and is normally not needed by * class generators or adapters.</i> * * @param index * the start index of an unsigned short value in {@link #b b}, * whose value is the index of a class constant pool item. * @param buf * buffer to be used to read the item. This buffer must be * sufficiently large. It is not automatically resized. * @return the String corresponding to the specified class item. */ public String readClass(final int index, final char[] buf) { // computes the start index of the CONSTANT_Class item in b // and reads the CONSTANT_Utf8 item designated by // the first two bytes of this CONSTANT_Class item return readUTF8(items[readUnsignedShort(index)], buf); } /** * Reads the bytecode of a method and makes the given visitor visit it. * * @param mv * the visitor that must visit the method's code. * @param context * information about the class being parsed. * @param u * the start offset of the code attribute in the class file. */ private void readCode(final MethodVisitor mv, final Context context, int u) { // reads the header byte[] b = this.b; char[] c = context.buffer; int maxStack = readUnsignedShort(u); int maxLocals = readUnsignedShort(u + 2); int codeLength = readInt(u + 4); u += 8; // reads the bytecode to find the labels int codeStart = u; int codeEnd = u + codeLength; Label[] labels = context.labels = new Label[codeLength + 2]; readLabel(codeLength + 1, labels); while (u < codeEnd) { int offset = u - codeStart; int opcode = b[u] & 0xFF; switch (ClassWriter.TYPE[opcode]) { case ClassWriter.NOARG_INSN: case ClassWriter.IMPLVAR_INSN: u += 1; break; case ClassWriter.LABEL_INSN: readLabel(offset + readShort(u + 1), labels); u += 3; break; case ClassWriter.ASM_LABEL_INSN: readLabel(offset + readUnsignedShort(u + 1), labels); u += 3; break; case ClassWriter.LABELW_INSN: readLabel(offset + readInt(u + 1), labels); u += 5; break; case ClassWriter.WIDE_INSN: opcode = b[u + 1] & 0xFF; if (opcode == Opcodes.IINC) { u += 6; } else { u += 4; } break; case ClassWriter.TABL_INSN: // skips 0 to 3 padding bytes u = u + 4 - (offset & 3); // reads instruction readLabel(offset + readInt(u), labels); for (int i = readInt(u + 8) - readInt(u + 4) + 1; i > 0; --i) { readLabel(offset + readInt(u + 12), labels); u += 4; } u += 12; break; case ClassWriter.LOOK_INSN: // skips 0 to 3 padding bytes u = u + 4 - (offset & 3); // reads instruction readLabel(offset + readInt(u), labels); for (int i = readInt(u + 4); i > 0; --i) { readLabel(offset + readInt(u + 12), labels); u += 8; } u += 8; break; case ClassWriter.VAR_INSN: case ClassWriter.SBYTE_INSN: case ClassWriter.LDC_INSN: u += 2; break; case ClassWriter.SHORT_INSN: case ClassWriter.LDCW_INSN: case ClassWriter.FIELDORMETH_INSN: case ClassWriter.TYPE_INSN: case ClassWriter.IINC_INSN: u += 3; break; case ClassWriter.ITFMETH_INSN: case ClassWriter.INDYMETH_INSN: u += 5; break; // case MANA_INSN: default: u += 4; break; } } // reads the try catch entries to find the labels, and also visits them for (int i = readUnsignedShort(u); i > 0; --i) { Label start = readLabel(readUnsignedShort(u + 2), labels); Label end = readLabel(readUnsignedShort(u + 4), labels); Label handler = readLabel(readUnsignedShort(u + 6), labels); String type = readUTF8(items[readUnsignedShort(u + 8)], c); mv.visitTryCatchBlock(start, end, handler, type); u += 8; } u += 2; // reads the code attributes int[] tanns = null; // start index of each visible type annotation int[] itanns = null; // start index of each invisible type annotation int tann = 0; // current index in tanns array int itann = 0; // current index in itanns array int ntoff = -1; // next visible type annotation code offset int nitoff = -1; // next invisible type annotation code offset int varTable = 0; int varTypeTable = 0; boolean zip = true; boolean unzip = (context.flags & EXPAND_FRAMES) != 0; int stackMap = 0; int stackMapSize = 0; int frameCount = 0; Context frame = null; Attribute attributes = null; for (int i = readUnsignedShort(u); i > 0; --i) { String attrName = readUTF8(u + 2, c); if ("LocalVariableTable".equals(attrName)) { if ((context.flags & SKIP_DEBUG) == 0) { varTable = u + 8; for (int j = readUnsignedShort(u + 8), v = u; j > 0; --j) { int label = readUnsignedShort(v + 10); if (labels[label] == null) { readLabel(label, labels).status |= Label.DEBUG; } label += readUnsignedShort(v + 12); if (labels[label] == null) { readLabel(label, labels).status |= Label.DEBUG; } v += 10; } } } else if ("LocalVariableTypeTable".equals(attrName)) { varTypeTable = u + 8; } else if ("LineNumberTable".equals(attrName)) { if ((context.flags & SKIP_DEBUG) == 0) { for (int j = readUnsignedShort(u + 8), v = u; j > 0; --j) { int label = readUnsignedShort(v + 10); if (labels[label] == null) { readLabel(label, labels).status |= Label.DEBUG; } Label l = labels[label]; while (l.line > 0) { if (l.next == null) { l.next = new Label(); } l = l.next; } l.line = readUnsignedShort(v + 12); v += 4; } } } else if (ANNOTATIONS && "RuntimeVisibleTypeAnnotations".equals(attrName)) { tanns = readTypeAnnotations(mv, context, u + 8, true); ntoff = tanns.length == 0 || readByte(tanns[0]) < 0x43 ? -1 : readUnsignedShort(tanns[0] + 1); } else if (ANNOTATIONS && "RuntimeInvisibleTypeAnnotations".equals(attrName)) { itanns = readTypeAnnotations(mv, context, u + 8, false); nitoff = itanns.length == 0 || readByte(itanns[0]) < 0x43 ? -1 : readUnsignedShort(itanns[0] + 1); } else if (FRAMES && "StackMapTable".equals(attrName)) { if ((context.flags & SKIP_FRAMES) == 0) { stackMap = u + 10; stackMapSize = readInt(u + 4); frameCount = readUnsignedShort(u + 8); } /* * here we do not extract the labels corresponding to the * attribute content. This would require a full parsing of the * attribute, which would need to be repeated in the second * phase (see below). Instead the content of the attribute is * read one frame at a time (i.e. after a frame has been * visited, the next frame is read), and the labels it contains * are also extracted one frame at a time. Thanks to the * ordering of frames, having only a "one frame lookahead" is * not a problem, i.e. it is not possible to see an offset * smaller than the offset of the current insn and for which no * Label exist. */ /* * This is not true for UNINITIALIZED type offsets. We solve * this by parsing the stack map table without a full decoding * (see below). */ } else if (FRAMES && "StackMap".equals(attrName)) { if ((context.flags & SKIP_FRAMES) == 0) { zip = false; stackMap = u + 10; stackMapSize = readInt(u + 4); frameCount = readUnsignedShort(u + 8); } /* * IMPORTANT! here we assume that the frames are ordered, as in * the StackMapTable attribute, although this is not guaranteed * by the attribute format. */ } else { for (int j = 0; j < context.attrs.length; ++j) { if (context.attrs[j].type.equals(attrName)) { Attribute attr = context.attrs[j].read(this, u + 8, readInt(u + 4), c, codeStart - 8, labels); if (attr != null) { attr.next = attributes; attributes = attr; } } } } u += 6 + readInt(u + 4); } u += 2; // generates the first (implicit) stack map frame if (FRAMES && stackMap != 0) { /* * for the first explicit frame the offset is not offset_delta + 1 * but only offset_delta; setting the implicit frame offset to -1 * allow the use of the "offset_delta + 1" rule in all cases */ frame = context; frame.offset = -1; frame.mode = 0; frame.localCount = 0; frame.localDiff = 0; frame.stackCount = 0; frame.local = new Object[maxLocals]; frame.stack = new Object[maxStack]; if (unzip) { getImplicitFrame(context); } /* * Finds labels for UNINITIALIZED frame types. Instead of decoding * each element of the stack map table, we look for 3 consecutive * bytes that "look like" an UNINITIALIZED type (tag 8, offset * within code bounds, NEW instruction at this offset). We may find * false positives (i.e. not real UNINITIALIZED types), but this * should be rare, and the only consequence will be the creation of * an unneeded label. This is better than creating a label for each * NEW instruction, and faster than fully decoding the whole stack * map table. */ for (int i = stackMap; i < stackMap + stackMapSize - 2; ++i) { if (b[i] == 8) { // UNINITIALIZED FRAME TYPE int v = readUnsignedShort(i + 1); if (v >= 0 && v < codeLength) { if ((b[codeStart + v] & 0xFF) == Opcodes.NEW) { readLabel(v, labels); } } } } } if ((context.flags & EXPAND_ASM_INSNS) != 0) { // Expanding the ASM pseudo instructions can introduce F_INSERT // frames, even if the method does not currently have any frame. // Also these inserted frames must be computed by simulating the // effect of the bytecode instructions one by one, starting from the // first one and the last existing frame (or the implicit first // one). Finally, due to the way MethodWriter computes this (with // the compute = INSERTED_FRAMES option), MethodWriter needs to know // maxLocals before the first instruction is visited. For all these // reasons we always visit the implicit first frame in this case // (passing only maxLocals - the rest can be and is computed in // MethodWriter). mv.visitFrame(Opcodes.F_NEW, maxLocals, null, 0, null); } // visits the instructions int opcodeDelta = (context.flags & EXPAND_ASM_INSNS) == 0 ? -33 : 0; u = codeStart; while (u < codeEnd) { int offset = u - codeStart; // visits the label and line number for this offset, if any Label l = labels[offset]; if (l != null) { Label next = l.next; l.next = null; mv.visitLabel(l); if ((context.flags & SKIP_DEBUG) == 0 && l.line > 0) { mv.visitLineNumber(l.line, l); while (next != null) { mv.visitLineNumber(next.line, l); next = next.next; } } } // visits the frame for this offset, if any while (FRAMES && frame != null && (frame.offset == offset || frame.offset == -1)) { // if there is a frame for this offset, makes the visitor visit // it, and reads the next frame if there is one. if (frame.offset != -1) { if (!zip || unzip) { mv.visitFrame(Opcodes.F_NEW, frame.localCount, frame.local, frame.stackCount, frame.stack); } else { mv.visitFrame(frame.mode, frame.localDiff, frame.local, frame.stackCount, frame.stack); } } if (frameCount > 0) { stackMap = readFrame(stackMap, zip, unzip, frame); --frameCount; } else { frame = null; } } // visits the instruction at this offset int opcode = b[u] & 0xFF; switch (ClassWriter.TYPE[opcode]) { case ClassWriter.NOARG_INSN: mv.visitInsn(opcode); u += 1; break; case ClassWriter.IMPLVAR_INSN: if (opcode > Opcodes.ISTORE) { opcode -= 59; // ISTORE_0 mv.visitVarInsn(Opcodes.ISTORE + (opcode >> 2), opcode & 0x3); } else { opcode -= 26; // ILOAD_0 mv.visitVarInsn(Opcodes.ILOAD + (opcode >> 2), opcode & 0x3); } u += 1; break; case ClassWriter.LABEL_INSN: mv.visitJumpInsn(opcode, labels[offset + readShort(u + 1)]); u += 3; break; case ClassWriter.LABELW_INSN: mv.visitJumpInsn(opcode + opcodeDelta, labels[offset + readInt(u + 1)]); u += 5; break; case ClassWriter.ASM_LABEL_INSN: { // changes temporary opcodes 202 to 217 (inclusive), 218 // and 219 to IFEQ ... JSR (inclusive), IFNULL and // IFNONNULL opcode = opcode < 218 ? opcode - 49 : opcode - 20; Label target = labels[offset + readUnsignedShort(u + 1)]; // replaces GOTO with GOTO_W, JSR with JSR_W and IFxxx // <l> with IFNOTxxx <l'> GOTO_W <l>, where IFNOTxxx is // the "opposite" opcode of IFxxx (i.e., IFNE for IFEQ) // and where <l'> designates the instruction just after // the GOTO_W. if (opcode == Opcodes.GOTO || opcode == Opcodes.JSR) { mv.visitJumpInsn(opcode + 33, target); } else { opcode = opcode <= 166 ? ((opcode + 1) ^ 1) - 1 : opcode ^ 1; Label endif = new Label(); mv.visitJumpInsn(opcode, endif); mv.visitJumpInsn(200, target); // GOTO_W mv.visitLabel(endif); // since we introduced an unconditional jump instruction we // also need to insert a stack map frame here, unless there // is already one. The actual frame content will be computed // in MethodWriter. if (FRAMES && stackMap != 0 && (frame == null || frame.offset != offset + 3)) { mv.visitFrame(ClassWriter.F_INSERT, 0, null, 0, null); } } u += 3; break; } case ClassWriter.WIDE_INSN: opcode = b[u + 1] & 0xFF; if (opcode == Opcodes.IINC) { mv.visitIincInsn(readUnsignedShort(u + 2), readShort(u + 4)); u += 6; } else { mv.visitVarInsn(opcode, readUnsignedShort(u + 2)); u += 4; } break; case ClassWriter.TABL_INSN: { // skips 0 to 3 padding bytes u = u + 4 - (offset & 3); // reads instruction int label = offset + readInt(u); int min = readInt(u + 4); int max = readInt(u + 8); Label[] table = new Label[max - min + 1]; u += 12; for (int i = 0; i < table.length; ++i) { table[i] = labels[offset + readInt(u)]; u += 4; } mv.visitTableSwitchInsn(min, max, labels[label], table); break; } case ClassWriter.LOOK_INSN: { // skips 0 to 3 padding bytes u = u + 4 - (offset & 3); // reads instruction int label = offset + readInt(u); int len = readInt(u + 4); int[] keys = new int[len]; Label[] values = new Label[len]; u += 8; for (int i = 0; i < len; ++i) { keys[i] = readInt(u); values[i] = labels[offset + readInt(u + 4)]; u += 8; } mv.visitLookupSwitchInsn(labels[label], keys, values); break; } case ClassWriter.VAR_INSN: mv.visitVarInsn(opcode, b[u + 1] & 0xFF); u += 2; break; case ClassWriter.SBYTE_INSN: mv.visitIntInsn(opcode, b[u + 1]); u += 2; break; case ClassWriter.SHORT_INSN: mv.visitIntInsn(opcode, readShort(u + 1)); u += 3; break; case ClassWriter.LDC_INSN: mv.visitLdcInsn(readConst(b[u + 1] & 0xFF, c)); u += 2; break; case ClassWriter.LDCW_INSN: mv.visitLdcInsn(readConst(readUnsignedShort(u + 1), c)); u += 3; break; case ClassWriter.FIELDORMETH_INSN: case ClassWriter.ITFMETH_INSN: { int cpIndex = items[readUnsignedShort(u + 1)]; boolean itf = b[cpIndex - 1] == ClassWriter.IMETH; String iowner = readClass(cpIndex, c); cpIndex = items[readUnsignedShort(cpIndex + 2)]; String iname = readUTF8(cpIndex, c); String idesc = readUTF8(cpIndex + 2, c); if (opcode < Opcodes.INVOKEVIRTUAL) { mv.visitFieldInsn(opcode, iowner, iname, idesc); } else { mv.visitMethodInsn(opcode, iowner, iname, idesc, itf); } if (opcode == Opcodes.INVOKEINTERFACE) { u += 5; } else { u += 3; } break; } case ClassWriter.INDYMETH_INSN: { int cpIndex = items[readUnsignedShort(u + 1)]; int bsmIndex = context.bootstrapMethods[readUnsignedShort(cpIndex)]; Handle bsm = (Handle) readConst(readUnsignedShort(bsmIndex), c); int bsmArgCount = readUnsignedShort(bsmIndex + 2); Object[] bsmArgs = new Object[bsmArgCount]; bsmIndex += 4; for (int i = 0; i < bsmArgCount; i++) { bsmArgs[i] = readConst(readUnsignedShort(bsmIndex), c); bsmIndex += 2; } cpIndex = items[readUnsignedShort(cpIndex + 2)]; String iname = readUTF8(cpIndex, c); String idesc = readUTF8(cpIndex + 2, c); mv.visitInvokeDynamicInsn(iname, idesc, bsm, bsmArgs); u += 5; break; } case ClassWriter.TYPE_INSN: mv.visitTypeInsn(opcode, readClass(u + 1, c)); u += 3; break; case ClassWriter.IINC_INSN: mv.visitIincInsn(b[u + 1] & 0xFF, b[u + 2]); u += 3; break; // case MANA_INSN: default: mv.visitMultiANewArrayInsn(readClass(u + 1, c), b[u + 3] & 0xFF); u += 4; break; } // visit the instruction annotations, if any while (tanns != null && tann < tanns.length && ntoff <= offset) { if (ntoff == offset) { int v = readAnnotationTarget(context, tanns[tann]); readAnnotationValues(v + 2, c, true, mv.visitInsnAnnotation(context.typeRef, context.typePath, readUTF8(v, c), true)); } ntoff = ++tann >= tanns.length || readByte(tanns[tann]) < 0x43 ? -1 : readUnsignedShort(tanns[tann] + 1); } while (itanns != null && itann < itanns.length && nitoff <= offset) { if (nitoff == offset) { int v = readAnnotationTarget(context, itanns[itann]); readAnnotationValues(v + 2, c, true, mv.visitInsnAnnotation(context.typeRef, context.typePath, readUTF8(v, c), false)); } nitoff = ++itann >= itanns.length || readByte(itanns[itann]) < 0x43 ? -1 : readUnsignedShort(itanns[itann] + 1); } } if (labels[codeLength] != null) { mv.visitLabel(labels[codeLength]); } // visits the local variable tables if ((context.flags & SKIP_DEBUG) == 0 && varTable != 0) { int[] typeTable = null; if (varTypeTable != 0) { u = varTypeTable + 2; typeTable = new int[readUnsignedShort(varTypeTable) * 3]; for (int i = typeTable.length; i > 0;) { typeTable[--i] = u + 6; // signature typeTable[--i] = readUnsignedShort(u + 8); // index typeTable[--i] = readUnsignedShort(u); // start u += 10; } } u = varTable + 2; for (int i = readUnsignedShort(varTable); i > 0; --i) { int start = readUnsignedShort(u); int length = readUnsignedShort(u + 2); int index = readUnsignedShort(u + 8); String vsignature = null; if (typeTable != null) { for (int j = 0; j < typeTable.length; j += 3) { if (typeTable[j] == start && typeTable[j + 1] == index) { vsignature = readUTF8(typeTable[j + 2], c); break; } } } mv.visitLocalVariable(readUTF8(u + 4, c), readUTF8(u + 6, c), vsignature, labels[start], labels[start + length], index); u += 10; } } // visits the local variables type annotations if (tanns != null) { for (int i = 0; i < tanns.length; ++i) { if ((readByte(tanns[i]) >> 1) == (0x40 >> 1)) { int v = readAnnotationTarget(context, tanns[i]); v = readAnnotationValues(v + 2, c, true, mv.visitLocalVariableAnnotation(context.typeRef, context.typePath, context.start, context.end, context.index, readUTF8(v, c), true)); } } } if (itanns != null) { for (int i = 0; i < itanns.length; ++i) { if ((readByte(itanns[i]) >> 1) == (0x40 >> 1)) { int v = readAnnotationTarget(context, itanns[i]); v = readAnnotationValues(v + 2, c, true, mv.visitLocalVariableAnnotation(context.typeRef, context.typePath, context.start, context.end, context.index, readUTF8(v, c), false)); } } } // visits the code attributes while (attributes != null) { Attribute attr = attributes.next; attributes.next = null; mv.visitAttribute(attributes); attributes = attr; } // visits the max stack and max locals values mv.visitMaxs(maxStack, maxLocals); } /** * Reads a numeric or string constant pool item in {@link #b b}. <i>This * method is intended for {@link Attribute} sub classes, and is normally not * needed by class generators or adapters.</i> * * @param item * the index of a constant pool item. * @param buf * buffer to be used to read the item. This buffer must be * sufficiently large. It is not automatically resized. * @return the {@link Integer}, {@link Float}, {@link Long}, {@link Double}, * {@link String}, {@link Type} or {@link Handle} corresponding to * the given constant pool item. */ public Object readConst(final int item, final char[] buf) { int index = items[item]; switch (b[index - 1]) { case ClassWriter.INT: return readInt(index); case ClassWriter.FLOAT: return Float.intBitsToFloat(readInt(index)); case ClassWriter.LONG: return readLong(index); case ClassWriter.DOUBLE: return Double.longBitsToDouble(readLong(index)); case ClassWriter.CLASS: return Type.getObjectType(readUTF8(index, buf)); case ClassWriter.STR: return readUTF8(index, buf); case ClassWriter.MTYPE: return Type.getMethodType(readUTF8(index, buf)); default: // case ClassWriter.HANDLE_BASE + [1..9]: int tag = readByte(index); int[] items = this.items; int cpIndex = items[readUnsignedShort(index + 1)]; boolean itf = b[cpIndex - 1] == ClassWriter.IMETH; String owner = readClass(cpIndex, buf); cpIndex = items[readUnsignedShort(cpIndex + 2)]; String name = readUTF8(cpIndex, buf); String desc = readUTF8(cpIndex + 2, buf); return new Handle(tag, owner, name, desc, itf); } } /** * Reads a field and makes the given visitor visit it. * * @param classVisitor * the visitor that must visit the field. * @param context * information about the class being parsed. * @param u * the start offset of the field in the class file. * @return the offset of the first byte following the field in the class. */ private int readField(final ClassVisitor classVisitor, final Context context, int u) { // reads the field declaration char[] c = context.buffer; int access = readUnsignedShort(u); String name = readUTF8(u + 2, c); String desc = readUTF8(u + 4, c); u += 6; // reads the field attributes String signature = null; int anns = 0; int ianns = 0; int tanns = 0; int itanns = 0; Object value = null; Attribute attributes = null; for (int i = readUnsignedShort(u); i > 0; --i) { String attrName = readUTF8(u + 2, c); // tests are sorted in decreasing frequency order // (based on frequencies observed on typical classes) if ("ConstantValue".equals(attrName)) { int item = readUnsignedShort(u + 8); value = item == 0 ? null : readConst(item, c); } else if (SIGNATURES && "Signature".equals(attrName)) { signature = readUTF8(u + 8, c); } else if ("Deprecated".equals(attrName)) { access |= Opcodes.ACC_DEPRECATED; } else if ("Synthetic".equals(attrName)) { access |= Opcodes.ACC_SYNTHETIC | ClassWriter.ACC_SYNTHETIC_ATTRIBUTE; } else if (ANNOTATIONS && "RuntimeVisibleAnnotations".equals(attrName)) { anns = u + 8; } else if (ANNOTATIONS && "RuntimeVisibleTypeAnnotations".equals(attrName)) { tanns = u + 8; } else if (ANNOTATIONS && "RuntimeInvisibleAnnotations".equals(attrName)) { ianns = u + 8; } else if (ANNOTATIONS && "RuntimeInvisibleTypeAnnotations".equals(attrName)) { itanns = u + 8; } else { Attribute attr = readAttribute(context.attrs, attrName, u + 8, readInt(u + 4), c, -1, null); if (attr != null) { attr.next = attributes; attributes = attr; } } u += 6 + readInt(u + 4); } u += 2; // visits the field declaration FieldVisitor fv = classVisitor.visitField(access, name, desc, signature, value); if (fv == null) { return u; } // visits the field annotations and type annotations if (ANNOTATIONS && anns != 0) { for (int i = readUnsignedShort(anns), v = anns + 2; i > 0; --i) { v = readAnnotationValues(v + 2, c, true, fv.visitAnnotation(readUTF8(v, c), true)); } } if (ANNOTATIONS && ianns != 0) { for (int i = readUnsignedShort(ianns), v = ianns + 2; i > 0; --i) { v = readAnnotationValues(v + 2, c, true, fv.visitAnnotation(readUTF8(v, c), false)); } } if (ANNOTATIONS && tanns != 0) { for (int i = readUnsignedShort(tanns), v = tanns + 2; i > 0; --i) { v = readAnnotationTarget(context, v); v = readAnnotationValues(v + 2, c, true, fv.visitTypeAnnotation(context.typeRef, context.typePath, readUTF8(v, c), true)); } } if (ANNOTATIONS && itanns != 0) { for (int i = readUnsignedShort(itanns), v = itanns + 2; i > 0; --i) { v = readAnnotationTarget(context, v); v = readAnnotationValues(v + 2, c, true, fv.visitTypeAnnotation(context.typeRef, context.typePath, readUTF8(v, c), false)); } } // visits the field attributes while (attributes != null) { Attribute attr = attributes.next; attributes.next = null; fv.visitAttribute(attributes); attributes = attr; } // visits the end of the field fv.visitEnd(); return u; } // ------------------------------------------------------------------------ // Utility methods: low level parsing // ------------------------------------------------------------------------ /** * Reads a stack map frame and stores the result in the given * {@link Context} object. * * @param stackMap * the start offset of a stack map frame in the class file. * @param zip * if the stack map frame at stackMap is compressed or not. * @param unzip * if the stack map frame must be uncompressed. * @param frame * where the parsed stack map frame must be stored. * @return the offset of the first byte following the parsed frame. */ private int readFrame(int stackMap, boolean zip, boolean unzip, Context frame) { char[] c = frame.buffer; Label[] labels = frame.labels; int tag; int delta; if (zip) { tag = b[stackMap++] & 0xFF; } else { tag = MethodWriter.FULL_FRAME; frame.offset = -1; } frame.localDiff = 0; if (tag < MethodWriter.SAME_LOCALS_1_STACK_ITEM_FRAME) { delta = tag; frame.mode = Opcodes.F_SAME; frame.stackCount = 0; } else if (tag < MethodWriter.RESERVED) { delta = tag - MethodWriter.SAME_LOCALS_1_STACK_ITEM_FRAME; stackMap = readFrameType(frame.stack, 0, stackMap, c, labels); frame.mode = Opcodes.F_SAME1; frame.stackCount = 1; } else { delta = readUnsignedShort(stackMap); stackMap += 2; if (tag == MethodWriter.SAME_LOCALS_1_STACK_ITEM_FRAME_EXTENDED) { stackMap = readFrameType(frame.stack, 0, stackMap, c, labels); frame.mode = Opcodes.F_SAME1; frame.stackCount = 1; } else if (tag >= MethodWriter.CHOP_FRAME && tag < MethodWriter.SAME_FRAME_EXTENDED) { frame.mode = Opcodes.F_CHOP; frame.localDiff = MethodWriter.SAME_FRAME_EXTENDED - tag; frame.localCount -= frame.localDiff; frame.stackCount = 0; } else if (tag == MethodWriter.SAME_FRAME_EXTENDED) { frame.mode = Opcodes.F_SAME; frame.stackCount = 0; } else if (tag < MethodWriter.FULL_FRAME) { int local = unzip ? frame.localCount : 0; for (int i = tag - MethodWriter.SAME_FRAME_EXTENDED; i > 0; i--) { stackMap = readFrameType(frame.local, local++, stackMap, c, labels); } frame.mode = Opcodes.F_APPEND; frame.localDiff = tag - MethodWriter.SAME_FRAME_EXTENDED; frame.localCount += frame.localDiff; frame.stackCount = 0; } else { // if (tag == FULL_FRAME) { frame.mode = Opcodes.F_FULL; int n = readUnsignedShort(stackMap); stackMap += 2; frame.localDiff = n; frame.localCount = n; for (int local = 0; n > 0; n--) { stackMap = readFrameType(frame.local, local++, stackMap, c, labels); } n = readUnsignedShort(stackMap); stackMap += 2; frame.stackCount = n; for (int stack = 0; n > 0; n--) { stackMap = readFrameType(frame.stack, stack++, stackMap, c, labels); } } } frame.offset += delta + 1; readLabel(frame.offset, labels); return stackMap; } /** * Reads a stack map frame type and stores it at the given index in the * given array. * * @param frame * the array where the parsed type must be stored. * @param index * the index in 'frame' where the parsed type must be stored. * @param v * the start offset of the stack map frame type to read. * @param buf * a buffer to read strings. * @param labels * the labels of the method currently being parsed, indexed by * their offset. If the parsed type is an Uninitialized type, a * new label for the corresponding NEW instruction is stored in * this array if it does not already exist. * @return the offset of the first byte after the parsed type. */ private int readFrameType(final Object[] frame, final int index, int v, final char[] buf, final Label[] labels) { int type = b[v++] & 0xFF; switch (type) { case 0: frame[index] = Opcodes.TOP; break; case 1: frame[index] = Opcodes.INTEGER; break; case 2: frame[index] = Opcodes.FLOAT; break; case 3: frame[index] = Opcodes.DOUBLE; break; case 4: frame[index] = Opcodes.LONG; break; case 5: frame[index] = Opcodes.NULL; break; case 6: frame[index] = Opcodes.UNINITIALIZED_THIS; break; case 7: // Object frame[index] = readClass(v, buf); v += 2; break; default: // Uninitialized frame[index] = readLabel(readUnsignedShort(v), labels); v += 2; } return v; } /** * Reads a signed int value in {@link #b b}. <i>This method is intended for * {@link Attribute} sub classes, and is normally not needed by class * generators or adapters.</i> * * @param index * the start index of the value to be read in {@link #b b}. * @return the read value. */ public int readInt(final int index) { byte[] b = this.b; return ((b[index] & 0xFF) << 24) | ((b[index + 1] & 0xFF) << 16) | ((b[index + 2] & 0xFF) << 8) | (b[index + 3] & 0xFF); } /** * Returns the label corresponding to the given offset. The default * implementation of this method creates a label for the given offset if it * has not been already created. * * @param offset * a bytecode offset in a method. * @param labels * the already created labels, indexed by their offset. If a * label already exists for offset this method must not create a * new one. Otherwise it must store the new label in this array. * @return a non null Label, which must be equal to labels[offset]. */ protected Label readLabel(int offset, Label[] labels) { if (labels[offset] == null) { labels[offset] = new Label(); } return labels[offset]; } /** * Reads a signed long value in {@link #b b}. <i>This method is intended for * {@link Attribute} sub classes, and is normally not needed by class * generators or adapters.</i> * * @param index * the start index of the value to be read in {@link #b b}. * @return the read value. */ public long readLong(final int index) { long l1 = readInt(index); long l0 = readInt(index + 4) & 0xFFFFFFFFL; return (l1 << 32) | l0; } /** * Reads a method and makes the given visitor visit it. * * @param classVisitor * the visitor that must visit the method. * @param context * information about the class being parsed. * @param u * the start offset of the method in the class file. * @return the offset of the first byte following the method in the class. */ private int readMethod(final ClassVisitor classVisitor, final Context context, int u) { // reads the method declaration char[] c = context.buffer; context.access = readUnsignedShort(u); context.name = readUTF8(u + 2, c); context.desc = readUTF8(u + 4, c); u += 6; // reads the method attributes int code = 0; int exception = 0; String[] exceptions = null; String signature = null; int methodParameters = 0; int anns = 0; int ianns = 0; int tanns = 0; int itanns = 0; int dann = 0; int mpanns = 0; int impanns = 0; int firstAttribute = u; Attribute attributes = null; for (int i = readUnsignedShort(u); i > 0; --i) { String attrName = readUTF8(u + 2, c); // tests are sorted in decreasing frequency order // (based on frequencies observed on typical classes) if ("Code".equals(attrName)) { if ((context.flags & SKIP_CODE) == 0) { code = u + 8; } } else if ("Exceptions".equals(attrName)) { exceptions = new String[readUnsignedShort(u + 8)]; exception = u + 10; for (int j = 0; j < exceptions.length; ++j) { exceptions[j] = readClass(exception, c); exception += 2; } } else if (SIGNATURES && "Signature".equals(attrName)) { signature = readUTF8(u + 8, c); } else if ("Deprecated".equals(attrName)) { context.access |= Opcodes.ACC_DEPRECATED; } else if (ANNOTATIONS && "RuntimeVisibleAnnotations".equals(attrName)) { anns = u + 8; } else if (ANNOTATIONS && "RuntimeVisibleTypeAnnotations".equals(attrName)) { tanns = u + 8; } else if (ANNOTATIONS && "AnnotationDefault".equals(attrName)) { dann = u + 8; } else if ("Synthetic".equals(attrName)) { context.access |= Opcodes.ACC_SYNTHETIC | ClassWriter.ACC_SYNTHETIC_ATTRIBUTE; } else if (ANNOTATIONS && "RuntimeInvisibleAnnotations".equals(attrName)) { ianns = u + 8; } else if (ANNOTATIONS && "RuntimeInvisibleTypeAnnotations".equals(attrName)) { itanns = u + 8; } else if (ANNOTATIONS && "RuntimeVisibleParameterAnnotations".equals(attrName)) { mpanns = u + 8; } else if (ANNOTATIONS && "RuntimeInvisibleParameterAnnotations".equals(attrName)) { impanns = u + 8; } else if ("MethodParameters".equals(attrName)) { methodParameters = u + 8; } else { Attribute attr = readAttribute(context.attrs, attrName, u + 8, readInt(u + 4), c, -1, null); if (attr != null) { attr.next = attributes; attributes = attr; } } u += 6 + readInt(u + 4); } u += 2; // visits the method declaration MethodVisitor mv = classVisitor.visitMethod(context.access, context.name, context.desc, signature, exceptions); if (mv == null) { return u; } /* * if the returned MethodVisitor is in fact a MethodWriter, it means * there is no method adapter between the reader and the writer. If, in * addition, the writer's constant pool was copied from this reader * (mw.cw.cr == this), and the signature and exceptions of the method * have not been changed, then it is possible to skip all visit events * and just copy the original code of the method to the writer (the * access, name and descriptor can have been changed, this is not * important since they are not copied as is from the reader). */ if (WRITER && mv instanceof MethodWriter) { MethodWriter mw = (MethodWriter) mv; if (mw.cw.cr == this && signature == mw.signature) { boolean sameExceptions = false; if (exceptions == null) { sameExceptions = mw.exceptionCount == 0; } else if (exceptions.length == mw.exceptionCount) { sameExceptions = true; for (int j = exceptions.length - 1; j >= 0; --j) { exception -= 2; if (mw.exceptions[j] != readUnsignedShort(exception)) { sameExceptions = false; break; } } } if (sameExceptions) { /* * we do not copy directly the code into MethodWriter to * save a byte array copy operation. The real copy will be * done in ClassWriter.toByteArray(). */ mw.classReaderOffset = firstAttribute; mw.classReaderLength = u - firstAttribute; return u; } } } // visit the method parameters if (methodParameters != 0) { for (int i = b[methodParameters] & 0xFF, v = methodParameters + 1; i > 0; --i, v = v + 4) { mv.visitParameter(readUTF8(v, c), readUnsignedShort(v + 2)); } } // visits the method annotations if (ANNOTATIONS && dann != 0) { AnnotationVisitor dv = mv.visitAnnotationDefault(); readAnnotationValue(dann, c, null, dv); if (dv != null) { dv.visitEnd(); } } if (ANNOTATIONS && anns != 0) { for (int i = readUnsignedShort(anns), v = anns + 2; i > 0; --i) { v = readAnnotationValues(v + 2, c, true, mv.visitAnnotation(readUTF8(v, c), true)); } } if (ANNOTATIONS && ianns != 0) { for (int i = readUnsignedShort(ianns), v = ianns + 2; i > 0; --i) { v = readAnnotationValues(v + 2, c, true, mv.visitAnnotation(readUTF8(v, c), false)); } } if (ANNOTATIONS && tanns != 0) { for (int i = readUnsignedShort(tanns), v = tanns + 2; i > 0; --i) { v = readAnnotationTarget(context, v); v = readAnnotationValues(v + 2, c, true, mv.visitTypeAnnotation(context.typeRef, context.typePath, readUTF8(v, c), true)); } } if (ANNOTATIONS && itanns != 0) { for (int i = readUnsignedShort(itanns), v = itanns + 2; i > 0; --i) { v = readAnnotationTarget(context, v); v = readAnnotationValues(v + 2, c, true, mv.visitTypeAnnotation(context.typeRef, context.typePath, readUTF8(v, c), false)); } } if (ANNOTATIONS && mpanns != 0) { readParameterAnnotations(mv, context, mpanns, true); } if (ANNOTATIONS && impanns != 0) { readParameterAnnotations(mv, context, impanns, false); } // visits the method attributes while (attributes != null) { Attribute attr = attributes.next; attributes.next = null; mv.visitAttribute(attributes); attributes = attr; } // visits the method code if (code != 0) { mv.visitCode(); readCode(mv, context, code); } // visits the end of the method mv.visitEnd(); return u; } /** * Reads parameter annotations and makes the given visitor visit them. * * @param mv * the visitor that must visit the annotations. * @param context * information about the class being parsed. * @param v * start offset in {@link #b b} of the annotations to be read. * @param visible * <tt>true</tt> if the annotations to be read are visible at * runtime. */ private void readParameterAnnotations(final MethodVisitor mv, final Context context, int v, final boolean visible) { int i; int n = b[v++] & 0xFF; // workaround for a bug in javac (javac compiler generates a parameter // annotation array whose size is equal to the number of parameters in // the Java source file, while it should generate an array whose size is // equal to the number of parameters in the method descriptor - which // includes the synthetic parameters added by the compiler). This work- // around supposes that the synthetic parameters are the first ones. int synthetics = Type.getArgumentTypes(context.desc).length - n; AnnotationVisitor av; for (i = 0; i < synthetics; ++i) { // virtual annotation to detect synthetic parameters in MethodWriter av = mv.visitParameterAnnotation(i, "Ljava/lang/Synthetic;", false); if (av != null) { av.visitEnd(); } } char[] c = context.buffer; for (; i < n + synthetics; ++i) { int j = readUnsignedShort(v); v += 2; for (; j > 0; --j) { av = mv.visitParameterAnnotation(i, readUTF8(v, c), visible); v = readAnnotationValues(v + 2, c, true, av); } } } /** * Reads a signed short value in {@link #b b}. <i>This method is intended * for {@link Attribute} sub classes, and is normally not needed by class * generators or adapters.</i> * * @param index * the start index of the value to be read in {@link #b b}. * @return the read value. */ public short readShort(final int index) { byte[] b = this.b; return (short) (((b[index] & 0xFF) << 8) | (b[index + 1] & 0xFF)); } /** * Parses a type annotation table to find the labels, and to visit the try * catch block annotations. * * @param u * the start offset of a type annotation table. * @param mv * the method visitor to be used to visit the try catch block * annotations. * @param context * information about the class being parsed. * @param visible * if the type annotation table to parse contains runtime visible * annotations. * @return the start offset of each type annotation in the parsed table. */ private int[] readTypeAnnotations(final MethodVisitor mv, final Context context, int u, boolean visible) { char[] c = context.buffer; int[] offsets = new int[readUnsignedShort(u)]; u += 2; for (int i = 0; i < offsets.length; ++i) { offsets[i] = u; int target = readInt(u); switch (target >>> 24) { case 0x00: // CLASS_TYPE_PARAMETER case 0x01: // METHOD_TYPE_PARAMETER case 0x16: // METHOD_FORMAL_PARAMETER u += 2; break; case 0x13: // FIELD case 0x14: // METHOD_RETURN case 0x15: // METHOD_RECEIVER u += 1; break; case 0x40: // LOCAL_VARIABLE case 0x41: // RESOURCE_VARIABLE for (int j = readUnsignedShort(u + 1); j > 0; --j) { int start = readUnsignedShort(u + 3); int length = readUnsignedShort(u + 5); readLabel(start, context.labels); readLabel(start + length, context.labels); u += 6; } u += 3; break; case 0x47: // CAST case 0x48: // CONSTRUCTOR_INVOCATION_TYPE_ARGUMENT case 0x49: // METHOD_INVOCATION_TYPE_ARGUMENT case 0x4A: // CONSTRUCTOR_REFERENCE_TYPE_ARGUMENT case 0x4B: // METHOD_REFERENCE_TYPE_ARGUMENT u += 4; break; // case 0x10: // CLASS_EXTENDS // case 0x11: // CLASS_TYPE_PARAMETER_BOUND // case 0x12: // METHOD_TYPE_PARAMETER_BOUND // case 0x17: // THROWS // case 0x42: // EXCEPTION_PARAMETER // case 0x43: // INSTANCEOF // case 0x44: // NEW // case 0x45: // CONSTRUCTOR_REFERENCE // case 0x46: // METHOD_REFERENCE default: u += 3; break; } int pathLength = readByte(u); if ((target >>> 24) == 0x42) { TypePath path = pathLength == 0 ? null : new TypePath(b, u); u += 1 + 2 * pathLength; u = readAnnotationValues(u + 2, c, true, mv.visitTryCatchAnnotation(target, path, readUTF8(u, c), visible)); } else { u = readAnnotationValues(u + 3 + 2 * pathLength, c, true, null); } } return offsets; } /** * Reads an unsigned short value in {@link #b b}. <i>This method is intended * for {@link Attribute} sub classes, and is normally not needed by class * generators or adapters.</i> * * @param index * the start index of the value to be read in {@link #b b}. * @return the read value. */ public int readUnsignedShort(final int index) { byte[] b = this.b; return ((b[index] & 0xFF) << 8) | (b[index + 1] & 0xFF); } /** * Reads UTF8 string in {@link #b b}. * * @param index * start offset of the UTF8 string to be read. * @param utfLen * length of the UTF8 string to be read. * @param buf * buffer to be used to read the string. This buffer must be * sufficiently large. It is not automatically resized. * @return the String corresponding to the specified UTF8 string. */ private String readUTF(int index, final int utfLen, final char[] buf) { int endIndex = index + utfLen; byte[] b = this.b; int strLen = 0; int c; int st = 0; char cc = 0; while (index < endIndex) { c = b[index++]; switch (st) { case 0: c = c & 0xFF; if (c < 0x80) { // 0xxxxxxx buf[strLen++] = (char) c; } else if (c < 0xE0 && c > 0xBF) { // 110x xxxx 10xx xxxx cc = (char) (c & 0x1F); st = 1; } else { // 1110 xxxx 10xx xxxx 10xx xxxx cc = (char) (c & 0x0F); st = 2; } break; case 1: // byte 2 of 2-byte char or byte 3 of 3-byte char buf[strLen++] = (char) ((cc << 6) | (c & 0x3F)); st = 0; break; case 2: // byte 2 of 3-byte char cc = (char) ((cc << 6) | (c & 0x3F)); st = 1; break; } } return new String(buf, 0, strLen); } /** * Reads an UTF8 string constant pool item in {@link #b b}. <i>This method * is intended for {@link Attribute} sub classes, and is normally not needed * by class generators or adapters.</i> * * @param index * the start index of an unsigned short value in {@link #b b}, * whose value is the index of an UTF8 constant pool item. * @param buf * buffer to be used to read the item. This buffer must be * sufficiently large. It is not automatically resized. * @return the String corresponding to the specified UTF8 item. */ public String readUTF8(int index, final char[] buf) { int item = readUnsignedShort(index); if (index == 0 || item == 0) { return null; } String s = strings[item]; if (s != null) { return s; } index = items[item]; return strings[item] = readUTF(index + 2, readUnsignedShort(index), buf); } }
apache-2.0
suoluo/inforshuttle
inforshuttle-mybatis/src/main/java/com/inforshuttle/mybatis/dto/OrderDto.java
1111
package com.inforshuttle.mybatis.dto; /** * @author gacl * ๅฎšไน‰orders่กจๅฏนๅบ”็š„ๅฎžไฝ“็ฑป */ public class OrderDto { /** * CREATE TABLE orders( order_id INT PRIMARY KEY AUTO_INCREMENT, order_no VARCHAR(20), order_price FLOAT ); */ //Orderๅฎžไฝ“็ฑปไธญๅฑžๆ€งๅๅ’Œorders่กจไธญ็š„ๅญ—ๆฎตๅๆ˜ฏไธไธ€ๆ ท็š„ private int id; //id===>order_id private String orderNo; //orderNo===>order_no private float price; //price===>order_price public int getId() { return id; } public void setId(int id) { this.id = id; } public String getOrderNo() { return orderNo; } public void setOrderNo(String orderNo) { this.orderNo = orderNo; } public float getPrice() { return price; } public void setPrice(float price) { this.price = price; } @Override public String toString() { return "Order [id=" + id + ", orderNo=" + orderNo + ", price=" + price+ "]"; } }
apache-2.0
kiritbasu/datacollector
container/src/test/java/com/streamsets/datacollector/restapi/bean/TestErrorMessageBean.java
2326
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.streamsets.datacollector.restapi.bean; import org.junit.Assert; import org.junit.Test; import com.streamsets.datacollector.restapi.bean.ErrorMessageJson; public class TestErrorMessageBean { @Test(expected = NullPointerException.class) public void testErrorMessageBeanNull() { ErrorMessageJson errorMessageJson = new ErrorMessageJson(null); } @Test public void testErrorMessageBean() { com.streamsets.pipeline.api.impl.ErrorMessage errorMessage = new com.streamsets.pipeline.api.impl.ErrorMessage("errorCode", "Hello World", System.currentTimeMillis()); ErrorMessageJson errorMessageJsonBean = new ErrorMessageJson(errorMessage); Assert.assertEquals(errorMessage.getErrorCode(), errorMessageJsonBean.getErrorCode()); Assert.assertEquals(errorMessage.getLocalized(), errorMessageJsonBean.getLocalized()); Assert.assertEquals(errorMessage.getNonLocalized(), errorMessageJsonBean.getNonLocalized()); Assert.assertEquals(errorMessage.getTimestamp(), errorMessageJsonBean.getTimestamp()); //check underlying Assert.assertEquals(errorMessage.getErrorCode(), errorMessageJsonBean.getErrorMessage().getErrorCode()); Assert.assertEquals(errorMessage.getLocalized(), errorMessageJsonBean.getErrorMessage().getLocalized()); Assert.assertEquals(errorMessage.getNonLocalized(), errorMessageJsonBean.getErrorMessage().getNonLocalized()); Assert.assertEquals(errorMessage.getTimestamp(), errorMessageJsonBean.getErrorMessage().getTimestamp()); } }
apache-2.0
justinmuller/buck
src/com/facebook/buck/jvm/java/intellij/IjProjectTemplateDataPreparer.java
20772
/* * Copyright 2015-present Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.facebook.buck.jvm.java.intellij; import com.facebook.buck.io.MorePaths; import com.facebook.buck.io.ProjectFilesystem; import com.facebook.buck.jvm.core.JavaPackageFinder; import com.facebook.buck.util.MoreCollectors; import com.facebook.buck.util.immutables.BuckStyleImmutable; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Function; import com.google.common.base.Joiner; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSortedSet; import com.google.common.collect.Ordering; import org.immutables.value.Value; import java.io.File; import java.io.IOException; import java.nio.file.FileVisitResult; import java.nio.file.FileVisitor; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.attribute.BasicFileAttributes; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.stream.Stream; import javax.annotation.Nullable; /** * Does the converting of abstract data structures to a format immediately consumable by the * StringTemplate-based templates employed by {@link IjProjectWriter}. This is a separate class * mainly for testing convenience. */ @VisibleForTesting public class IjProjectTemplateDataPreparer { private static final String ANDROID_MANIFEST_TEMPLATE_PARAMETER = "android_manifest"; private static final String APK_PATH_TEMPLATE_PARAMETER = "apk_path"; private static final String ASSETS_FOLDER_TEMPLATE_PARAMETER = "asset_folder"; private static final String PROGUARD_CONFIG_TEMPLATE_PARAMETER = "proguard_config"; private static final String RESOURCES_RELATIVE_PATH_TEMPLATE_PARAMETER = "res"; private static final String EMPTY_STRING = ""; private JavaPackageFinder javaPackageFinder; private IjModuleGraph moduleGraph; private ProjectFilesystem projectFilesystem; private IjSourceRootSimplifier sourceRootSimplifier; private ImmutableSet<Path> referencedFolderPaths; private ImmutableSet<Path> filesystemTraversalBoundaryPaths; private ImmutableSet<IjModule> modulesToBeWritten; private ImmutableSet<IjLibrary> librariesToBeWritten; public IjProjectTemplateDataPreparer( JavaPackageFinder javaPackageFinder, IjModuleGraph moduleGraph, ProjectFilesystem projectFilesystem) { this.javaPackageFinder = javaPackageFinder; this.moduleGraph = moduleGraph; this.projectFilesystem = projectFilesystem; this.sourceRootSimplifier = new IjSourceRootSimplifier(javaPackageFinder); this.modulesToBeWritten = createModulesToBeWritten(moduleGraph); this.librariesToBeWritten = moduleGraph .getNodes() .stream() .filter(node -> node instanceof IjLibrary) .map(IjLibrary.class::cast) .collect(MoreCollectors.toImmutableSet()); this.filesystemTraversalBoundaryPaths = createFilesystemTraversalBoundaryPathSet(modulesToBeWritten); this.referencedFolderPaths = createReferencedFolderPathsSet(modulesToBeWritten); } private static void addPathAndParents(Set<Path> pathSet, Path path) { do { pathSet.add(path); path = path.getParent(); } while(path != null && !pathSet.contains(path)); } public static ImmutableSet<Path> createReferencedFolderPathsSet(ImmutableSet<IjModule> modules) { Set<Path> pathSet = new HashSet<>(); for (IjModule module : modules) { addPathAndParents(pathSet, module.getModuleBasePath()); for (IjFolder folder : module.getFolders()) { addPathAndParents(pathSet, folder.getPath()); } } return ImmutableSet.copyOf(pathSet); } public static ImmutableSet<Path> createFilesystemTraversalBoundaryPathSet( ImmutableSet<IjModule> modules) { return Stream .concat( modules.stream().map(IjModule::getModuleBasePath), Stream.of(IjProjectWriter.IDEA_CONFIG_DIR_PREFIX)) .collect(MoreCollectors.toImmutableSet()); } public static ImmutableSet<Path> createPackageLookupPathSet(IjModuleGraph moduleGraph) { ImmutableSet.Builder<Path> builder = ImmutableSet.builder(); for (IjModule module : moduleGraph.getModuleNodes()) { for (IjFolder folder : module.getFolders()) { if (!folder.getWantsPackagePrefix()) { continue; } Optional<Path> firstJavaFile = folder.getInputs().stream() .filter(input -> input.getFileName().toString().endsWith(".java")) .findFirst(); if (firstJavaFile.isPresent()) { builder.add(firstJavaFile.get()); } } } return builder.build(); } private static ImmutableSet<IjModule> createModulesToBeWritten(IjModuleGraph graph) { Path rootModuleBasePath = Paths.get(""); boolean hasRootModule = graph .getModuleNodes() .stream() .anyMatch(module -> rootModuleBasePath.equals(module.getModuleBasePath())); ImmutableSet<IjModule> supplementalModules = ImmutableSet.of(); if (!hasRootModule) { supplementalModules = ImmutableSet.of( IjModule.builder() .setModuleBasePath(rootModuleBasePath) .setTargets(ImmutableSet.of()) .build()); } return Stream .concat(graph.getModuleNodes().stream(), supplementalModules.stream()) .collect(MoreCollectors.toImmutableSet()); } /** * @param path path to folder. * @param moduleLocationBasePath path to the location of the .iml file. * @return a path, relative to the module .iml file location describing a folder * in IntelliJ format. */ private static String toModuleDirRelativeString(Path path, Path moduleLocationBasePath) { String moduleRelativePath = moduleLocationBasePath.relativize(path).toString(); if (moduleRelativePath.isEmpty()) { return "file://$MODULE_DIR$"; } else { return "file://$MODULE_DIR$/" + moduleRelativePath; } } private static String toProjectDirRelativeString(Path projectRelativePath) { String path = projectRelativePath.toString(); if (path.isEmpty()) { return "file://$PROJECT_DIR$"; } else { return "file://$PROJECT_DIR$/" + MorePaths.pathWithUnixSeparators(path); } } @Value.Immutable @BuckStyleImmutable abstract static class AbstractIjSourceFolder implements Comparable<IjSourceFolder> { public abstract String getType(); public abstract String getUrl(); public abstract boolean getIsTestSource(); public abstract boolean getIsAndroidResources(); @Nullable public abstract String getPackagePrefix(); @Override public int compareTo(IjSourceFolder o) { if (this == o) { return 0; } return getUrl().compareTo(o.getUrl()); } } @Value.Immutable @BuckStyleImmutable abstract static class AbstractContentRoot implements Comparable<ContentRoot> { public abstract String getUrl(); public abstract ImmutableSortedSet<IjSourceFolder> getFolders(); @Override public int compareTo(ContentRoot o) { if (this == o) { return 0; } return getUrl().compareTo(o.getUrl()); } } public ImmutableSet<IjModule> getModulesToBeWritten() { return modulesToBeWritten; } public ImmutableSet<IjLibrary> getLibrariesToBeWritten() { return librariesToBeWritten; } private ContentRoot createContentRoot( final IjModule module, Path contentRootPath, ImmutableSet<IjFolder> folders, final Path moduleLocationBasePath) { String url = toModuleDirRelativeString(contentRootPath, moduleLocationBasePath); ImmutableSet<IjFolder> simplifiedFolders = sourceRootSimplifier.simplify( SimplificationLimit.of(contentRootPath.getNameCount()), folders); IjFolderToIjSourceFolderTransform transformToFolder = new IjFolderToIjSourceFolderTransform(module); ImmutableSortedSet<IjSourceFolder> sourceFolders = simplifiedFolders .stream() .map(transformToFolder::apply) .collect(MoreCollectors.toImmutableSortedSet(Ordering.natural())); return ContentRoot.builder() .setUrl(url) .setFolders(sourceFolders) .build(); } public ImmutableSet<IjFolder> createExcludes(final IjModule module) throws IOException { final ImmutableSet.Builder<IjFolder> excludesBuilder = ImmutableSet.builder(); final Path moduleBasePath = module.getModuleBasePath(); projectFilesystem.walkRelativeFileTree( moduleBasePath, new FileVisitor<Path>() { @Override public FileVisitResult preVisitDirectory( Path dir, BasicFileAttributes attrs) throws IOException { // This is another module that's nested in this one. The entire subtree will be handled // When we create excludes for that module. if (filesystemTraversalBoundaryPaths.contains(dir) && !moduleBasePath.equals(dir)) { return FileVisitResult.SKIP_SUBTREE; } if (isRootAndroidResourceDirectory(module, dir)) { return FileVisitResult.SKIP_SUBTREE; } if (!referencedFolderPaths.contains(dir)) { excludesBuilder.add(new ExcludeFolder(dir)); return FileVisitResult.SKIP_SUBTREE; } return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFile( Path file, BasicFileAttributes attrs) throws IOException { return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException { return FileVisitResult.CONTINUE; } @Override public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { return FileVisitResult.CONTINUE; } }); return excludesBuilder.build(); } private boolean isRootAndroidResourceDirectory(IjModule module, Path dir) { if (!module.getAndroidFacet().isPresent()) { return false; } for (Path resourcePath : module.getAndroidFacet().get().getResourcePaths()) { if (dir.equals(resourcePath)) { return true; } } return false; } public ContentRoot getContentRoot(IjModule module) throws IOException { Path moduleBasePath = module.getModuleBasePath(); Path moduleLocation = module.getModuleImlFilePath(); final Path moduleLocationBasePath = (moduleLocation.getParent() == null) ? Paths.get("") : moduleLocation.getParent(); ImmutableSet<IjFolder> sourcesAndExcludes = Stream .concat(module.getFolders().stream(), createExcludes(module).stream()) .collect(MoreCollectors.toImmutableSet()); return createContentRoot(module, moduleBasePath, sourcesAndExcludes, moduleLocationBasePath); } public ImmutableSet<IjSourceFolder> getGeneratedSourceFolders(final IjModule module) { return module.getGeneratedSourceCodeFolders().stream() .map(new IjFolderToIjSourceFolderTransform(module)::apply) .collect(MoreCollectors.toImmutableSet()); } public ImmutableSet<DependencyEntry> getDependencies(IjModule module) { ImmutableMap<IjProjectElement, IjModuleGraph.DependencyType> deps = moduleGraph.getDepsFor(module); IjDependencyListBuilder dependencyListBuilder = new IjDependencyListBuilder(); for (Map.Entry<IjProjectElement, IjModuleGraph.DependencyType> entry : deps.entrySet()) { IjProjectElement element = entry.getKey(); IjModuleGraph.DependencyType dependencyType = entry.getValue(); element.addAsDependency(dependencyType, dependencyListBuilder); } return dependencyListBuilder.build(); } @Value.Immutable @BuckStyleImmutable abstract static class AbstractModuleIndexEntry implements Comparable<ModuleIndexEntry> { public abstract String getFileUrl(); public abstract Path getFilePath(); @Nullable public abstract String getGroup(); @Override public int compareTo(ModuleIndexEntry o) { if (this == o) { return 0; } return getFilePath() .toString() .replace(File.separatorChar, ' ') .compareTo(o.getFilePath() .toString() .replace(File.separatorChar, ' ')); } } public ImmutableSortedSet<ModuleIndexEntry> getModuleIndexEntries() { return modulesToBeWritten .stream() .map( module -> { Path moduleOutputFilePath = module.getModuleImlFilePath(); String fileUrl = toProjectDirRelativeString(moduleOutputFilePath); // The root project module cannot belong to any group. String group = (module.getModuleBasePath().toString().isEmpty()) ? null : "modules"; return ModuleIndexEntry.builder() .setFileUrl(fileUrl) .setFilePath(moduleOutputFilePath) .setGroup(group) .build(); }) .collect(MoreCollectors.toImmutableSortedSet(Ordering.natural())); } public Map<String, Object> getAndroidProperties(IjModule module) { Map<String, Object> androidProperties = new HashMap<>(); Optional<IjModuleAndroidFacet> androidFacetOptional = module.getAndroidFacet(); boolean isAndroidFacetPresent = androidFacetOptional.isPresent(); androidProperties.put("enabled", isAndroidFacetPresent); if (!isAndroidFacetPresent) { return androidProperties; } IjModuleAndroidFacet androidFacet = androidFacetOptional.get(); androidProperties.put("is_android_library_project", androidFacet.isAndroidLibrary()); androidProperties.put( "autogenerate_sources", androidFacet.autogenerateSources()); Path basePath = module.getModuleBasePath(); addAndroidConstants(androidProperties); addAndroidApkPaths(androidProperties, module, basePath, androidFacet); addAndroidAssetPaths(androidProperties, androidFacet); addAndroidGenPath(androidProperties, androidFacet, basePath); addAndroidManifestPath(androidProperties, basePath, androidFacet); addAndroidProguardPath(androidProperties, androidFacet); addAndroidResourcePaths(androidProperties, module, androidFacet); return androidProperties; } private void addAndroidConstants(Map<String, Object> androidProperties) { androidProperties.put("run_proguard", false); // TODO(alsutton): Fix keystore detection androidProperties.put("keystore", ""); // TODO(alsutton): See if we need nativeLibs and libs androidProperties.put("libs_path", "/libs"); } private void addAndroidApkPaths( Map<String, Object> androidProperties, IjModule module, Path moduleBasePath, IjModuleAndroidFacet androidFacet) { if (androidFacet.isAndroidLibrary()) { androidProperties.put(APK_PATH_TEMPLATE_PARAMETER, EMPTY_STRING); return; } Path apkPath = moduleBasePath .relativize(Paths.get("")) .resolve(Project.getAndroidApkDir(projectFilesystem)) .resolve(Paths.get("").relativize(moduleBasePath)) .resolve(module.getName() + ".apk"); androidProperties.put(APK_PATH_TEMPLATE_PARAMETER, apkPath); } private void addAndroidAssetPaths( Map<String, Object> androidProperties, IjModuleAndroidFacet androidFacet) { ImmutableSet<Path> assetPaths = androidFacet.getAssetPaths(); if (assetPaths.isEmpty()) { androidProperties.put(ASSETS_FOLDER_TEMPLATE_PARAMETER, "/assets"); } else { androidProperties.put( ASSETS_FOLDER_TEMPLATE_PARAMETER, "/" + Joiner.on(";/").join(androidFacet.getAssetPaths())); } } private void addAndroidGenPath( Map<String, Object> androidProperties, IjModuleAndroidFacet androidFacet, Path moduleBasePath) { Path genPath = moduleBasePath .relativize(androidFacet.getGeneratedSourcePath()); androidProperties.put( "module_gen_path", "/" + MorePaths.pathWithUnixSeparators(genPath)); } private void addAndroidManifestPath( Map<String, Object> androidProperties, Path moduleBasePath, IjModuleAndroidFacet androidFacet) { Optional<Path> androidManifestPath = androidFacet.getManifestPath(); Path manifestPath; if (androidManifestPath.isPresent()) { manifestPath = projectFilesystem.resolve(moduleBasePath) .relativize(androidManifestPath.get()); } else { manifestPath = moduleBasePath .relativize( Paths .get("") .resolve("android_res/AndroidManifest.xml")); } androidProperties.put(ANDROID_MANIFEST_TEMPLATE_PARAMETER, "/" + manifestPath); } private void addAndroidProguardPath( Map<String, Object> androidProperties, IjModuleAndroidFacet androidFacet) { Optional<Path> proguardPath = androidFacet.getProguardConfigPath(); if (proguardPath.isPresent()) { androidProperties.put(PROGUARD_CONFIG_TEMPLATE_PARAMETER, proguardPath.get()); } else { androidProperties.put(PROGUARD_CONFIG_TEMPLATE_PARAMETER, EMPTY_STRING); } } private void addAndroidResourcePaths( Map<String, Object> androidProperties, IjModule module, IjModuleAndroidFacet androidFacet) { ImmutableSet<Path> resourcePaths = androidFacet.getResourcePaths(); if (resourcePaths.isEmpty()) { androidProperties.put(RESOURCES_RELATIVE_PATH_TEMPLATE_PARAMETER, EMPTY_STRING); } else { Set<Path> relativeResourcePaths = new HashSet<>(resourcePaths.size()); Path moduleBase = module.getModuleBasePath(); for (Path resourcePath : resourcePaths) { relativeResourcePaths.add(moduleBase.relativize(resourcePath)); } androidProperties.put( RESOURCES_RELATIVE_PATH_TEMPLATE_PARAMETER, "/" + Joiner.on(";/").join(relativeResourcePaths)); } } private class IjFolderToIjSourceFolderTransform implements Function<IjFolder, IjSourceFolder> { private Path moduleBasePath; private Optional<IjModuleAndroidFacet> androidFacet; IjFolderToIjSourceFolderTransform(IjModule module) { moduleBasePath = module.getModuleBasePath(); androidFacet = module.getAndroidFacet(); } @Override public IjSourceFolder apply(IjFolder input) { String packagePrefix; if (input instanceof AndroidResourceFolder && androidFacet.isPresent() && androidFacet.get().getPackageName().isPresent()) { packagePrefix = androidFacet.get().getPackageName().get(); } else { packagePrefix = getPackagePrefix(input); } return createSourceFolder(input, moduleBasePath, packagePrefix); } private IjSourceFolder createSourceFolder( IjFolder folder, Path moduleLocationBasePath, String packagePrefix) { return IjSourceFolder.builder() .setType(folder.getIjName()) .setUrl(toModuleDirRelativeString(folder.getPath(), moduleLocationBasePath)) .setIsTestSource(folder instanceof TestFolder) .setIsAndroidResources(folder instanceof AndroidResourceFolder) .setPackagePrefix(packagePrefix) .build(); } @Nullable private String getPackagePrefix(IjFolder folder) { if (!folder.getWantsPackagePrefix()) { return null; } Path fileToLookupPackageIn; if (!folder.getInputs().isEmpty() && folder.getInputs().first().getParent().equals(folder.getPath())) { fileToLookupPackageIn = folder.getInputs().first(); } else { fileToLookupPackageIn = folder.getPath().resolve("notfound"); } String packagePrefix = javaPackageFinder.findJavaPackage(fileToLookupPackageIn); if (packagePrefix.isEmpty()) { // It doesn't matter either way, but an empty prefix looks confusing. return null; } return packagePrefix; } } }
apache-2.0
edu1910/LinuxFi_2015_1
ExercicioFinal/app/src/main/java/br/com/ceducarneiro/exerciciofinal/model/Author.java
1176
package br.com.ceducarneiro.exerciciofinal.model; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.orm.SugarRecord; import java.util.List; @JsonIgnoreProperties(value = {"modified"}) public class Author extends SugarRecord { @JsonProperty(value = "id") private Long guid; private String name; private boolean modified; public static List<Author> findAllModified() { return Author.find(Author.class, "modified = ?", Boolean.TRUE.toString()); } public static Author findByGuid(Long guid) { List<Author> authors = Author.find(Author.class, "guid= ?", String.valueOf(guid)); return authors.isEmpty() ? null : authors.get(0); } public Long getGuid() { return guid; } public void setGuid(Long guid) { this.guid = guid; } public String getName() { return name; } public void setName(String name) { this.name = name; } public boolean isModified() { return modified; } public void setModified(boolean modified) { this.modified = modified; } }
apache-2.0
mygreen/super-csv-annotation1
src/main/java/org/supercsv/ext/io/CsvAnnotationBeanWriter.java
2732
/* * CsvAnnotationBeanWriter.java * created in 2013/03/06 * * (C) Copyright 2003-2013 GreenDay Project. All rights reserved. */ package org.supercsv.ext.io; import java.io.IOException; import java.io.Writer; import java.util.Collection; import org.supercsv.ext.builder.CsvAnnotationBeanParser; import org.supercsv.ext.builder.CsvBeanMapping; import org.supercsv.prefs.CsvPreference; /** * * * @author T.TSUCHIE * */ public class CsvAnnotationBeanWriter<T> extends ValidatableCsvBeanWriter { protected CsvAnnotationBeanParser beanParser = new CsvAnnotationBeanParser(); protected final CsvBeanMapping<T> beanMapping; protected final BeanMappingCache mappingCache; public CsvAnnotationBeanWriter(final Class<T> clazz, final Writer writer, final CsvPreference preferences) { this(clazz, writer, preferences, false); } public CsvAnnotationBeanWriter(final Class<T> clazz, final Writer writer, final CsvPreference preferences, final boolean ignoreValidationProcessor, final CsvAnnotationBeanParser beanParser) { super(writer, preferences); this.beanParser = beanParser; this.beanMapping = beanParser.parse(clazz, ignoreValidationProcessor); this.mappingCache = new BeanMappingCache(beanMapping); } public CsvAnnotationBeanWriter(final Class<T> clazz, Writer writer, final CsvPreference preferences, final boolean ignoreValidationProcessor) { super(writer, preferences); this.beanMapping = beanParser.parse(clazz, ignoreValidationProcessor); this.mappingCache = new BeanMappingCache(beanMapping); } public CsvAnnotationBeanWriter(final CsvBeanMapping<T> beanMapping, final Writer writer, final CsvPreference preferences) { super(writer, preferences); this.beanMapping = beanMapping; this.mappingCache = new BeanMappingCache(this.beanMapping); } public boolean hasHeader() { return getBeanMapping().isHeader(); } public void writeHeader() throws IOException { writeHeader(getMappingCache().getHeader()); } public void write(final T source) throws IOException { write(source, getMappingCache().getNameMapping(), getMappingCache().getOutputCellProcessors()); } public void writeAll(final Collection<T> collection) throws IOException { for(T item : collection) { write(item, getMappingCache().getNameMapping(), getMappingCache().getOutputCellProcessors()); } } public CsvBeanMapping<T> getBeanMapping() { return beanMapping; } public BeanMappingCache getMappingCache() { return mappingCache; } }
apache-2.0
jorgevillaverde/dacs
java/jax-ws-client/src/main/java/ar/edu/utn/frre/dacs/ws/client/ListProvincias.java
745
package ar.edu.utn.frre.dacs.ws.client; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; /** * <p>Clase Java para listProvincias complex type. * * <p>El siguiente fragmento de esquema especifica el contenido que se espera que haya en esta clase. * * <pre> * &lt;complexType name="listProvincias"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "listProvincias") public class ListProvincias { }
apache-2.0
stackmagic/arangodb-wal-client
src/test/java/net/swisstech/arangodb/model/wal/WalEventTest.java
313
package net.swisstech.arangodb.model.wal; import java.io.IOException; import net.swisstech.swissarmyknife.test.DtoTesterUtil; import org.testng.annotations.Test; public class WalEventTest { @Test public void propertiesCoverage() throws IOException { DtoTesterUtil.testAllProperties(new WalEvent()); } }
apache-2.0
java110/MicroCommunity
service-front/src/main/java/com/java110/front/smo/complaint/IDeleteComplaintSMO.java
414
package com.java110.front.smo.complaint; import com.java110.core.context.IPageData; import org.springframework.http.ResponseEntity; /** * ๆทปๅŠ ๆŠ•่ฏ‰ๅปบ่ฎฎๆŽฅๅฃ * * add by wuxw 2019-06-30 */ public interface IDeleteComplaintSMO { /** * ๆทปๅŠ ๆŠ•่ฏ‰ๅปบ่ฎฎ * @param pd ้กต้ขๆ•ฐๆฎๅฐ่ฃ… * @return ResponseEntity ๅฏน่ฑก */ ResponseEntity<String> deleteComplaint(IPageData pd); }
apache-2.0
dimone-kun/cuba
modules/gui/src/com/haulmont/cuba/gui/xml/layout/loaders/ContainerLoader.java
4745
/* * Copyright (c) 2008-2016 Haulmont. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.haulmont.cuba.gui.xml.layout.loaders; import com.haulmont.cuba.gui.GuiDevelopmentException; import com.haulmont.cuba.gui.components.Component; import com.haulmont.cuba.gui.components.ComponentContainer; import com.haulmont.cuba.gui.components.ExpandingLayout; import com.haulmont.cuba.gui.components.HasSpacing; import com.haulmont.cuba.gui.xml.layout.ComponentLoader; import com.haulmont.cuba.gui.xml.layout.LayoutLoader; import org.apache.commons.lang3.StringUtils; import org.dom4j.Element; import java.util.ArrayList; import java.util.List; public abstract class ContainerLoader<T extends Component> extends AbstractComponentLoader<T> { protected List<ComponentLoader> pendingLoadComponents = new ArrayList<>(); protected void loadSubComponents() { for (ComponentLoader componentLoader : pendingLoadComponents) { componentLoader.loadComponent(); } pendingLoadComponents.clear(); } @Override public void setMessagesPack(String messagesPack) { super.setMessagesPack(messagesPack); for (ComponentLoader loader : pendingLoadComponents) { if (!(loader instanceof FragmentComponentLoader) && !(loader instanceof RuntimePropertiesFrameLoader)) { loader.setMessagesPack(messagesPack); } } } protected void loadSpacing(HasSpacing layout, Element element) { String spacing = element.attributeValue("spacing"); if (StringUtils.isNotEmpty(spacing)) { layout.setSpacing(Boolean.parseBoolean(spacing)); } } protected void createSubComponents(ComponentContainer container, Element containerElement) { LayoutLoader loader = beanLocator.getPrototype(LayoutLoader.NAME, context); loader.setLocale(getLocale()); loader.setMessagesPack(getMessagesPack()); //noinspection unchecked for (Element subElement : containerElement.elements()) { if (!isChildElementIgnored(subElement)) { ComponentLoader componentLoader = loader.createComponent(subElement); pendingLoadComponents.add(componentLoader); container.add(componentLoader.getResultComponent()); } } } /** * Checks if child element should have a separate loader or not. * For instance, if a child element doesn't represent a UI component. * * @param subElement the element to be checked * @return {@code true} if child element should have no separate loader, {@code false} otherwise */ protected boolean isChildElementIgnored(Element subElement) { return false; } protected void loadSubComponentsAndExpand(ExpandingLayout layout, Element element) { loadSubComponents(); String expand = element.attributeValue("expand"); if (StringUtils.isNotEmpty(expand)) { if (!expand.contains(";")) { Component componentToExpand = layout.getOwnComponent(expand); layout.expand(componentToExpand); } else { // legacy behaviour String[] parts = expand.split(";"); String targetId = parts[0]; Component componentToExpand = layout.getOwnComponent(targetId); if (componentToExpand != null) { String height = find(parts, "height"); String width = find(parts, "width"); layout.expand(componentToExpand, height, width); } else { throw new GuiDevelopmentException( String.format("Illegal expand target '%s' for container", targetId), context.getFullFrameId(), "component", targetId); } } } } protected String find(String[] parts, String name) { String prefix = name + "="; for (String part : parts) { if (part.trim().startsWith(prefix)) { return part.trim().substring((prefix).length()).trim(); } } return null; } }
apache-2.0
googleapis/java-aiplatform
proto-google-cloud-aiplatform-v1beta1/src/main/java/com/google/cloud/aiplatform/v1beta1/BatchCreateTensorboardRunsRequest.java
44326
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/aiplatform/v1beta1/tensorboard_service.proto package com.google.cloud.aiplatform.v1beta1; /** * * * <pre> * Request message for [TensorboardService.BatchCreateTensorboardRuns][google.cloud.aiplatform.v1beta1.TensorboardService.BatchCreateTensorboardRuns]. * </pre> * * Protobuf type {@code google.cloud.aiplatform.v1beta1.BatchCreateTensorboardRunsRequest} */ public final class BatchCreateTensorboardRunsRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.aiplatform.v1beta1.BatchCreateTensorboardRunsRequest) BatchCreateTensorboardRunsRequestOrBuilder { private static final long serialVersionUID = 0L; // Use BatchCreateTensorboardRunsRequest.newBuilder() to construct. private BatchCreateTensorboardRunsRequest( com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private BatchCreateTensorboardRunsRequest() { parent_ = ""; requests_ = java.util.Collections.emptyList(); } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new BatchCreateTensorboardRunsRequest(); } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private BatchCreateTensorboardRunsRequest( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { java.lang.String s = input.readStringRequireUtf8(); parent_ = s; break; } case 18: { if (!((mutable_bitField0_ & 0x00000001) != 0)) { requests_ = new java.util.ArrayList< com.google.cloud.aiplatform.v1beta1.CreateTensorboardRunRequest>(); mutable_bitField0_ |= 0x00000001; } requests_.add( input.readMessage( com.google.cloud.aiplatform.v1beta1.CreateTensorboardRunRequest.parser(), extensionRegistry)); break; } default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { done = true; } break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e).setUnfinishedMessage(this); } finally { if (((mutable_bitField0_ & 0x00000001) != 0)) { requests_ = java.util.Collections.unmodifiableList(requests_); } this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.aiplatform.v1beta1.TensorboardServiceProto .internal_static_google_cloud_aiplatform_v1beta1_BatchCreateTensorboardRunsRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.aiplatform.v1beta1.TensorboardServiceProto .internal_static_google_cloud_aiplatform_v1beta1_BatchCreateTensorboardRunsRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.aiplatform.v1beta1.BatchCreateTensorboardRunsRequest.class, com.google.cloud.aiplatform.v1beta1.BatchCreateTensorboardRunsRequest.Builder.class); } public static final int PARENT_FIELD_NUMBER = 1; private volatile java.lang.Object parent_; /** * * * <pre> * Required. The resource name of the TensorboardExperiment to create the * TensorboardRuns in. Format: * `projects/{project}/locations/{location}/tensorboards/{tensorboard}/experiments/{experiment}` * The parent field in the CreateTensorboardRunRequest messages must match * this field. * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The parent. */ @java.lang.Override public java.lang.String getParent() { java.lang.Object ref = parent_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); parent_ = s; return s; } } /** * * * <pre> * Required. The resource name of the TensorboardExperiment to create the * TensorboardRuns in. Format: * `projects/{project}/locations/{location}/tensorboards/{tensorboard}/experiments/{experiment}` * The parent field in the CreateTensorboardRunRequest messages must match * this field. * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The bytes for parent. */ @java.lang.Override public com.google.protobuf.ByteString getParentBytes() { java.lang.Object ref = parent_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); parent_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int REQUESTS_FIELD_NUMBER = 2; private java.util.List<com.google.cloud.aiplatform.v1beta1.CreateTensorboardRunRequest> requests_; /** * * * <pre> * Required. The request message specifying the TensorboardRuns to create. * A maximum of 1000 TensorboardRuns can be created in a batch. * </pre> * * <code> * repeated .google.cloud.aiplatform.v1beta1.CreateTensorboardRunRequest requests = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ @java.lang.Override public java.util.List<com.google.cloud.aiplatform.v1beta1.CreateTensorboardRunRequest> getRequestsList() { return requests_; } /** * * * <pre> * Required. The request message specifying the TensorboardRuns to create. * A maximum of 1000 TensorboardRuns can be created in a batch. * </pre> * * <code> * repeated .google.cloud.aiplatform.v1beta1.CreateTensorboardRunRequest requests = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ @java.lang.Override public java.util.List< ? extends com.google.cloud.aiplatform.v1beta1.CreateTensorboardRunRequestOrBuilder> getRequestsOrBuilderList() { return requests_; } /** * * * <pre> * Required. The request message specifying the TensorboardRuns to create. * A maximum of 1000 TensorboardRuns can be created in a batch. * </pre> * * <code> * repeated .google.cloud.aiplatform.v1beta1.CreateTensorboardRunRequest requests = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ @java.lang.Override public int getRequestsCount() { return requests_.size(); } /** * * * <pre> * Required. The request message specifying the TensorboardRuns to create. * A maximum of 1000 TensorboardRuns can be created in a batch. * </pre> * * <code> * repeated .google.cloud.aiplatform.v1beta1.CreateTensorboardRunRequest requests = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ @java.lang.Override public com.google.cloud.aiplatform.v1beta1.CreateTensorboardRunRequest getRequests(int index) { return requests_.get(index); } /** * * * <pre> * Required. The request message specifying the TensorboardRuns to create. * A maximum of 1000 TensorboardRuns can be created in a batch. * </pre> * * <code> * repeated .google.cloud.aiplatform.v1beta1.CreateTensorboardRunRequest requests = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ @java.lang.Override public com.google.cloud.aiplatform.v1beta1.CreateTensorboardRunRequestOrBuilder getRequestsOrBuilder(int index) { return requests_.get(index); } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(parent_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, parent_); } for (int i = 0; i < requests_.size(); i++) { output.writeMessage(2, requests_.get(i)); } unknownFields.writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(parent_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, parent_); } for (int i = 0; i < requests_.size(); i++) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(2, requests_.get(i)); } size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.cloud.aiplatform.v1beta1.BatchCreateTensorboardRunsRequest)) { return super.equals(obj); } com.google.cloud.aiplatform.v1beta1.BatchCreateTensorboardRunsRequest other = (com.google.cloud.aiplatform.v1beta1.BatchCreateTensorboardRunsRequest) obj; if (!getParent().equals(other.getParent())) return false; if (!getRequestsList().equals(other.getRequestsList())) return false; if (!unknownFields.equals(other.unknownFields)) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + PARENT_FIELD_NUMBER; hash = (53 * hash) + getParent().hashCode(); if (getRequestsCount() > 0) { hash = (37 * hash) + REQUESTS_FIELD_NUMBER; hash = (53 * hash) + getRequestsList().hashCode(); } hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.aiplatform.v1beta1.BatchCreateTensorboardRunsRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.aiplatform.v1beta1.BatchCreateTensorboardRunsRequest parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.aiplatform.v1beta1.BatchCreateTensorboardRunsRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.aiplatform.v1beta1.BatchCreateTensorboardRunsRequest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.aiplatform.v1beta1.BatchCreateTensorboardRunsRequest parseFrom( byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.aiplatform.v1beta1.BatchCreateTensorboardRunsRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.aiplatform.v1beta1.BatchCreateTensorboardRunsRequest parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.aiplatform.v1beta1.BatchCreateTensorboardRunsRequest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.aiplatform.v1beta1.BatchCreateTensorboardRunsRequest parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.aiplatform.v1beta1.BatchCreateTensorboardRunsRequest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.aiplatform.v1beta1.BatchCreateTensorboardRunsRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.aiplatform.v1beta1.BatchCreateTensorboardRunsRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder( com.google.cloud.aiplatform.v1beta1.BatchCreateTensorboardRunsRequest prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * Request message for [TensorboardService.BatchCreateTensorboardRuns][google.cloud.aiplatform.v1beta1.TensorboardService.BatchCreateTensorboardRuns]. * </pre> * * Protobuf type {@code google.cloud.aiplatform.v1beta1.BatchCreateTensorboardRunsRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.aiplatform.v1beta1.BatchCreateTensorboardRunsRequest) com.google.cloud.aiplatform.v1beta1.BatchCreateTensorboardRunsRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.aiplatform.v1beta1.TensorboardServiceProto .internal_static_google_cloud_aiplatform_v1beta1_BatchCreateTensorboardRunsRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.aiplatform.v1beta1.TensorboardServiceProto .internal_static_google_cloud_aiplatform_v1beta1_BatchCreateTensorboardRunsRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.aiplatform.v1beta1.BatchCreateTensorboardRunsRequest.class, com.google.cloud.aiplatform.v1beta1.BatchCreateTensorboardRunsRequest.Builder.class); } // Construct using // com.google.cloud.aiplatform.v1beta1.BatchCreateTensorboardRunsRequest.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) { getRequestsFieldBuilder(); } } @java.lang.Override public Builder clear() { super.clear(); parent_ = ""; if (requestsBuilder_ == null) { requests_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); } else { requestsBuilder_.clear(); } return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.aiplatform.v1beta1.TensorboardServiceProto .internal_static_google_cloud_aiplatform_v1beta1_BatchCreateTensorboardRunsRequest_descriptor; } @java.lang.Override public com.google.cloud.aiplatform.v1beta1.BatchCreateTensorboardRunsRequest getDefaultInstanceForType() { return com.google.cloud.aiplatform.v1beta1.BatchCreateTensorboardRunsRequest .getDefaultInstance(); } @java.lang.Override public com.google.cloud.aiplatform.v1beta1.BatchCreateTensorboardRunsRequest build() { com.google.cloud.aiplatform.v1beta1.BatchCreateTensorboardRunsRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.aiplatform.v1beta1.BatchCreateTensorboardRunsRequest buildPartial() { com.google.cloud.aiplatform.v1beta1.BatchCreateTensorboardRunsRequest result = new com.google.cloud.aiplatform.v1beta1.BatchCreateTensorboardRunsRequest(this); int from_bitField0_ = bitField0_; result.parent_ = parent_; if (requestsBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0)) { requests_ = java.util.Collections.unmodifiableList(requests_); bitField0_ = (bitField0_ & ~0x00000001); } result.requests_ = requests_; } else { result.requests_ = requestsBuilder_.build(); } onBuilt(); return result; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.cloud.aiplatform.v1beta1.BatchCreateTensorboardRunsRequest) { return mergeFrom( (com.google.cloud.aiplatform.v1beta1.BatchCreateTensorboardRunsRequest) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom( com.google.cloud.aiplatform.v1beta1.BatchCreateTensorboardRunsRequest other) { if (other == com.google.cloud.aiplatform.v1beta1.BatchCreateTensorboardRunsRequest .getDefaultInstance()) return this; if (!other.getParent().isEmpty()) { parent_ = other.parent_; onChanged(); } if (requestsBuilder_ == null) { if (!other.requests_.isEmpty()) { if (requests_.isEmpty()) { requests_ = other.requests_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensureRequestsIsMutable(); requests_.addAll(other.requests_); } onChanged(); } } else { if (!other.requests_.isEmpty()) { if (requestsBuilder_.isEmpty()) { requestsBuilder_.dispose(); requestsBuilder_ = null; requests_ = other.requests_; bitField0_ = (bitField0_ & ~0x00000001); requestsBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getRequestsFieldBuilder() : null; } else { requestsBuilder_.addAllMessages(other.requests_); } } } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.google.cloud.aiplatform.v1beta1.BatchCreateTensorboardRunsRequest parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (com.google.cloud.aiplatform.v1beta1.BatchCreateTensorboardRunsRequest) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int bitField0_; private java.lang.Object parent_ = ""; /** * * * <pre> * Required. The resource name of the TensorboardExperiment to create the * TensorboardRuns in. Format: * `projects/{project}/locations/{location}/tensorboards/{tensorboard}/experiments/{experiment}` * The parent field in the CreateTensorboardRunRequest messages must match * this field. * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The parent. */ public java.lang.String getParent() { java.lang.Object ref = parent_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); parent_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Required. The resource name of the TensorboardExperiment to create the * TensorboardRuns in. Format: * `projects/{project}/locations/{location}/tensorboards/{tensorboard}/experiments/{experiment}` * The parent field in the CreateTensorboardRunRequest messages must match * this field. * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The bytes for parent. */ public com.google.protobuf.ByteString getParentBytes() { java.lang.Object ref = parent_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); parent_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Required. The resource name of the TensorboardExperiment to create the * TensorboardRuns in. Format: * `projects/{project}/locations/{location}/tensorboards/{tensorboard}/experiments/{experiment}` * The parent field in the CreateTensorboardRunRequest messages must match * this field. * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @param value The parent to set. * @return This builder for chaining. */ public Builder setParent(java.lang.String value) { if (value == null) { throw new NullPointerException(); } parent_ = value; onChanged(); return this; } /** * * * <pre> * Required. The resource name of the TensorboardExperiment to create the * TensorboardRuns in. Format: * `projects/{project}/locations/{location}/tensorboards/{tensorboard}/experiments/{experiment}` * The parent field in the CreateTensorboardRunRequest messages must match * this field. * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return This builder for chaining. */ public Builder clearParent() { parent_ = getDefaultInstance().getParent(); onChanged(); return this; } /** * * * <pre> * Required. The resource name of the TensorboardExperiment to create the * TensorboardRuns in. Format: * `projects/{project}/locations/{location}/tensorboards/{tensorboard}/experiments/{experiment}` * The parent field in the CreateTensorboardRunRequest messages must match * this field. * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @param value The bytes for parent to set. * @return This builder for chaining. */ public Builder setParentBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); parent_ = value; onChanged(); return this; } private java.util.List<com.google.cloud.aiplatform.v1beta1.CreateTensorboardRunRequest> requests_ = java.util.Collections.emptyList(); private void ensureRequestsIsMutable() { if (!((bitField0_ & 0x00000001) != 0)) { requests_ = new java.util.ArrayList< com.google.cloud.aiplatform.v1beta1.CreateTensorboardRunRequest>(requests_); bitField0_ |= 0x00000001; } } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.aiplatform.v1beta1.CreateTensorboardRunRequest, com.google.cloud.aiplatform.v1beta1.CreateTensorboardRunRequest.Builder, com.google.cloud.aiplatform.v1beta1.CreateTensorboardRunRequestOrBuilder> requestsBuilder_; /** * * * <pre> * Required. The request message specifying the TensorboardRuns to create. * A maximum of 1000 TensorboardRuns can be created in a batch. * </pre> * * <code> * repeated .google.cloud.aiplatform.v1beta1.CreateTensorboardRunRequest requests = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public java.util.List<com.google.cloud.aiplatform.v1beta1.CreateTensorboardRunRequest> getRequestsList() { if (requestsBuilder_ == null) { return java.util.Collections.unmodifiableList(requests_); } else { return requestsBuilder_.getMessageList(); } } /** * * * <pre> * Required. The request message specifying the TensorboardRuns to create. * A maximum of 1000 TensorboardRuns can be created in a batch. * </pre> * * <code> * repeated .google.cloud.aiplatform.v1beta1.CreateTensorboardRunRequest requests = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public int getRequestsCount() { if (requestsBuilder_ == null) { return requests_.size(); } else { return requestsBuilder_.getCount(); } } /** * * * <pre> * Required. The request message specifying the TensorboardRuns to create. * A maximum of 1000 TensorboardRuns can be created in a batch. * </pre> * * <code> * repeated .google.cloud.aiplatform.v1beta1.CreateTensorboardRunRequest requests = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.cloud.aiplatform.v1beta1.CreateTensorboardRunRequest getRequests(int index) { if (requestsBuilder_ == null) { return requests_.get(index); } else { return requestsBuilder_.getMessage(index); } } /** * * * <pre> * Required. The request message specifying the TensorboardRuns to create. * A maximum of 1000 TensorboardRuns can be created in a batch. * </pre> * * <code> * repeated .google.cloud.aiplatform.v1beta1.CreateTensorboardRunRequest requests = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setRequests( int index, com.google.cloud.aiplatform.v1beta1.CreateTensorboardRunRequest value) { if (requestsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureRequestsIsMutable(); requests_.set(index, value); onChanged(); } else { requestsBuilder_.setMessage(index, value); } return this; } /** * * * <pre> * Required. The request message specifying the TensorboardRuns to create. * A maximum of 1000 TensorboardRuns can be created in a batch. * </pre> * * <code> * repeated .google.cloud.aiplatform.v1beta1.CreateTensorboardRunRequest requests = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setRequests( int index, com.google.cloud.aiplatform.v1beta1.CreateTensorboardRunRequest.Builder builderForValue) { if (requestsBuilder_ == null) { ensureRequestsIsMutable(); requests_.set(index, builderForValue.build()); onChanged(); } else { requestsBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * Required. The request message specifying the TensorboardRuns to create. * A maximum of 1000 TensorboardRuns can be created in a batch. * </pre> * * <code> * repeated .google.cloud.aiplatform.v1beta1.CreateTensorboardRunRequest requests = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder addRequests( com.google.cloud.aiplatform.v1beta1.CreateTensorboardRunRequest value) { if (requestsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureRequestsIsMutable(); requests_.add(value); onChanged(); } else { requestsBuilder_.addMessage(value); } return this; } /** * * * <pre> * Required. The request message specifying the TensorboardRuns to create. * A maximum of 1000 TensorboardRuns can be created in a batch. * </pre> * * <code> * repeated .google.cloud.aiplatform.v1beta1.CreateTensorboardRunRequest requests = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder addRequests( int index, com.google.cloud.aiplatform.v1beta1.CreateTensorboardRunRequest value) { if (requestsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureRequestsIsMutable(); requests_.add(index, value); onChanged(); } else { requestsBuilder_.addMessage(index, value); } return this; } /** * * * <pre> * Required. The request message specifying the TensorboardRuns to create. * A maximum of 1000 TensorboardRuns can be created in a batch. * </pre> * * <code> * repeated .google.cloud.aiplatform.v1beta1.CreateTensorboardRunRequest requests = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder addRequests( com.google.cloud.aiplatform.v1beta1.CreateTensorboardRunRequest.Builder builderForValue) { if (requestsBuilder_ == null) { ensureRequestsIsMutable(); requests_.add(builderForValue.build()); onChanged(); } else { requestsBuilder_.addMessage(builderForValue.build()); } return this; } /** * * * <pre> * Required. The request message specifying the TensorboardRuns to create. * A maximum of 1000 TensorboardRuns can be created in a batch. * </pre> * * <code> * repeated .google.cloud.aiplatform.v1beta1.CreateTensorboardRunRequest requests = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder addRequests( int index, com.google.cloud.aiplatform.v1beta1.CreateTensorboardRunRequest.Builder builderForValue) { if (requestsBuilder_ == null) { ensureRequestsIsMutable(); requests_.add(index, builderForValue.build()); onChanged(); } else { requestsBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * Required. The request message specifying the TensorboardRuns to create. * A maximum of 1000 TensorboardRuns can be created in a batch. * </pre> * * <code> * repeated .google.cloud.aiplatform.v1beta1.CreateTensorboardRunRequest requests = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder addAllRequests( java.lang.Iterable< ? extends com.google.cloud.aiplatform.v1beta1.CreateTensorboardRunRequest> values) { if (requestsBuilder_ == null) { ensureRequestsIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll(values, requests_); onChanged(); } else { requestsBuilder_.addAllMessages(values); } return this; } /** * * * <pre> * Required. The request message specifying the TensorboardRuns to create. * A maximum of 1000 TensorboardRuns can be created in a batch. * </pre> * * <code> * repeated .google.cloud.aiplatform.v1beta1.CreateTensorboardRunRequest requests = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder clearRequests() { if (requestsBuilder_ == null) { requests_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); } else { requestsBuilder_.clear(); } return this; } /** * * * <pre> * Required. The request message specifying the TensorboardRuns to create. * A maximum of 1000 TensorboardRuns can be created in a batch. * </pre> * * <code> * repeated .google.cloud.aiplatform.v1beta1.CreateTensorboardRunRequest requests = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder removeRequests(int index) { if (requestsBuilder_ == null) { ensureRequestsIsMutable(); requests_.remove(index); onChanged(); } else { requestsBuilder_.remove(index); } return this; } /** * * * <pre> * Required. The request message specifying the TensorboardRuns to create. * A maximum of 1000 TensorboardRuns can be created in a batch. * </pre> * * <code> * repeated .google.cloud.aiplatform.v1beta1.CreateTensorboardRunRequest requests = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.cloud.aiplatform.v1beta1.CreateTensorboardRunRequest.Builder getRequestsBuilder(int index) { return getRequestsFieldBuilder().getBuilder(index); } /** * * * <pre> * Required. The request message specifying the TensorboardRuns to create. * A maximum of 1000 TensorboardRuns can be created in a batch. * </pre> * * <code> * repeated .google.cloud.aiplatform.v1beta1.CreateTensorboardRunRequest requests = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.cloud.aiplatform.v1beta1.CreateTensorboardRunRequestOrBuilder getRequestsOrBuilder(int index) { if (requestsBuilder_ == null) { return requests_.get(index); } else { return requestsBuilder_.getMessageOrBuilder(index); } } /** * * * <pre> * Required. The request message specifying the TensorboardRuns to create. * A maximum of 1000 TensorboardRuns can be created in a batch. * </pre> * * <code> * repeated .google.cloud.aiplatform.v1beta1.CreateTensorboardRunRequest requests = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public java.util.List< ? extends com.google.cloud.aiplatform.v1beta1.CreateTensorboardRunRequestOrBuilder> getRequestsOrBuilderList() { if (requestsBuilder_ != null) { return requestsBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(requests_); } } /** * * * <pre> * Required. The request message specifying the TensorboardRuns to create. * A maximum of 1000 TensorboardRuns can be created in a batch. * </pre> * * <code> * repeated .google.cloud.aiplatform.v1beta1.CreateTensorboardRunRequest requests = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.cloud.aiplatform.v1beta1.CreateTensorboardRunRequest.Builder addRequestsBuilder() { return getRequestsFieldBuilder() .addBuilder( com.google.cloud.aiplatform.v1beta1.CreateTensorboardRunRequest.getDefaultInstance()); } /** * * * <pre> * Required. The request message specifying the TensorboardRuns to create. * A maximum of 1000 TensorboardRuns can be created in a batch. * </pre> * * <code> * repeated .google.cloud.aiplatform.v1beta1.CreateTensorboardRunRequest requests = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.cloud.aiplatform.v1beta1.CreateTensorboardRunRequest.Builder addRequestsBuilder(int index) { return getRequestsFieldBuilder() .addBuilder( index, com.google.cloud.aiplatform.v1beta1.CreateTensorboardRunRequest.getDefaultInstance()); } /** * * * <pre> * Required. The request message specifying the TensorboardRuns to create. * A maximum of 1000 TensorboardRuns can be created in a batch. * </pre> * * <code> * repeated .google.cloud.aiplatform.v1beta1.CreateTensorboardRunRequest requests = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public java.util.List<com.google.cloud.aiplatform.v1beta1.CreateTensorboardRunRequest.Builder> getRequestsBuilderList() { return getRequestsFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.aiplatform.v1beta1.CreateTensorboardRunRequest, com.google.cloud.aiplatform.v1beta1.CreateTensorboardRunRequest.Builder, com.google.cloud.aiplatform.v1beta1.CreateTensorboardRunRequestOrBuilder> getRequestsFieldBuilder() { if (requestsBuilder_ == null) { requestsBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.aiplatform.v1beta1.CreateTensorboardRunRequest, com.google.cloud.aiplatform.v1beta1.CreateTensorboardRunRequest.Builder, com.google.cloud.aiplatform.v1beta1.CreateTensorboardRunRequestOrBuilder>( requests_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean()); requests_ = null; } return requestsBuilder_; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.aiplatform.v1beta1.BatchCreateTensorboardRunsRequest) } // @@protoc_insertion_point(class_scope:google.cloud.aiplatform.v1beta1.BatchCreateTensorboardRunsRequest) private static final com.google.cloud.aiplatform.v1beta1.BatchCreateTensorboardRunsRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.aiplatform.v1beta1.BatchCreateTensorboardRunsRequest(); } public static com.google.cloud.aiplatform.v1beta1.BatchCreateTensorboardRunsRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<BatchCreateTensorboardRunsRequest> PARSER = new com.google.protobuf.AbstractParser<BatchCreateTensorboardRunsRequest>() { @java.lang.Override public BatchCreateTensorboardRunsRequest parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new BatchCreateTensorboardRunsRequest(input, extensionRegistry); } }; public static com.google.protobuf.Parser<BatchCreateTensorboardRunsRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<BatchCreateTensorboardRunsRequest> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.aiplatform.v1beta1.BatchCreateTensorboardRunsRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
apache-2.0
opentelecoms-org/jsmpp
jsmpp-examples/src/main/java/org/jsmpp/examples/SubmitMultiExample.java
4869
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jsmpp.examples; import java.io.IOException; import java.util.Date; import org.jsmpp.InvalidResponseException; import org.jsmpp.PDUException; import org.jsmpp.bean.Address; import org.jsmpp.bean.Alphabet; import org.jsmpp.bean.BindType; import org.jsmpp.bean.ESMClass; import org.jsmpp.bean.GeneralDataCoding; import org.jsmpp.bean.MessageClass; import org.jsmpp.bean.NumberingPlanIndicator; import org.jsmpp.bean.RegisteredDelivery; import org.jsmpp.bean.ReplaceIfPresentFlag; import org.jsmpp.bean.SMSCDeliveryReceipt; import org.jsmpp.bean.SubmitMultiResult; import org.jsmpp.bean.TypeOfNumber; import org.jsmpp.bean.UnsuccessDelivery; import org.jsmpp.extra.NegativeResponseException; import org.jsmpp.extra.ResponseTimeoutException; import org.jsmpp.session.BindParameter; import org.jsmpp.session.SMPPSession; import org.jsmpp.util.AbsoluteTimeFormatter; import org.jsmpp.util.TimeFormatter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * Example for Submit Multi SMS * */ public class SubmitMultiExample { private static final Logger LOGGER = LoggerFactory.getLogger(SubmitMultiExample.class); private static final TimeFormatter TIME_FORMATTER = new AbsoluteTimeFormatter(); public static void main(String[] args) { // Create a new SMPP Session SMPPSession session = new SMPPSession(); try { session.setMessageReceiverListener(new MessageReceiverListenerImpl()); // Bind to the Server String systemId = session.connectAndBind("localhost", 8056, new BindParameter(BindType.BIND_TRX, "test", "test", "cp", TypeOfNumber.UNKNOWN, NumberingPlanIndicator.UNKNOWN, null)); LOGGER.info("Connected with SMSC with system id {}", systemId); try { Address address1 = new Address(TypeOfNumber.INTERNATIONAL, NumberingPlanIndicator.UNKNOWN, "628176504657"); Address address2 = new Address(TypeOfNumber.INTERNATIONAL, NumberingPlanIndicator.UNKNOWN, "628176504658"); Address[] addresses = new Address[] {address1, address2}; SubmitMultiResult result = session.submitMultiple("CMT", TypeOfNumber.INTERNATIONAL, NumberingPlanIndicator.UNKNOWN, "1616", addresses, new ESMClass(), (byte)0, (byte)1, TIME_FORMATTER.format(new Date()), null, new RegisteredDelivery(SMSCDeliveryReceipt.FAILURE), ReplaceIfPresentFlag.REPLACE, new GeneralDataCoding(Alphabet.ALPHA_DEFAULT, MessageClass.CLASS1, false), (byte)0, "jSMPP simplifies SMPP on Java platform".getBytes()); LOGGER.info("{} messages submitted, result message id {}", addresses.length, result.getMessageId()); for (UnsuccessDelivery unsuccessDelivery: result.getUnsuccessDeliveries()){ LOGGER.info("Unsuccessful delivery to {}: {}", unsuccessDelivery.getDestinationAddress(), unsuccessDelivery.getErrorStatusCode()); } Thread.sleep(2000); } catch (PDUException e) { // Invalid PDU parameter LOGGER.error("Invalid PDU parameter", e); } catch (ResponseTimeoutException e) { // Response timeout LOGGER.error("Response timeout", e); } catch (InvalidResponseException e) { // Invalid response LOGGER.error("Receive invalid response", e); } catch (NegativeResponseException e) { // Receiving negative response (non-zero command_status) LOGGER.error("Receive negative response", e); } catch (IOException e) { LOGGER.error("I/O error occurred", e); } catch (InterruptedException e) { LOGGER.error("Thread interrupted", e); } session.unbindAndClose(); } catch (IOException e) { LOGGER.error("Failed connect and bind to host", e); } } }
apache-2.0
hortonworks/cloudbreak
cloud-aws-common/src/main/java/com/sequenceiq/cloudbreak/cloud/aws/common/AwsNoSqlConnector.java
5256
package com.sequenceiq.cloudbreak.cloud.aws.common; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; import com.amazonaws.services.dynamodbv2.model.AmazonDynamoDBException; import com.amazonaws.services.dynamodbv2.model.DeleteTableResult; import com.amazonaws.services.dynamodbv2.model.DescribeTableResult; import com.amazonaws.services.dynamodbv2.model.ResourceNotFoundException; import com.amazonaws.services.dynamodbv2.model.TableDescription; import com.sequenceiq.cloudbreak.cloud.NoSqlConnector; import com.sequenceiq.cloudbreak.cloud.RegionAware; import com.sequenceiq.cloudbreak.cloud.aws.common.client.AmazonDynamoDBClient; import com.sequenceiq.cloudbreak.cloud.aws.common.view.AwsCredentialView; import com.sequenceiq.cloudbreak.cloud.exception.CloudConnectorException; import com.sequenceiq.cloudbreak.cloud.model.Platform; import com.sequenceiq.cloudbreak.cloud.model.Variant; import com.sequenceiq.cloudbreak.cloud.model.base.RegionAndCredentialAwareRequestBase; import com.sequenceiq.cloudbreak.cloud.model.base.ResponseStatus; import com.sequenceiq.cloudbreak.cloud.model.nosql.NoSqlTableDeleteRequest; import com.sequenceiq.cloudbreak.cloud.model.nosql.NoSqlTableDeleteResponse; import com.sequenceiq.cloudbreak.cloud.model.nosql.NoSqlTableMetadataRequest; import com.sequenceiq.cloudbreak.cloud.model.nosql.NoSqlTableMetadataResponse; @Service public class AwsNoSqlConnector implements NoSqlConnector { private static final Logger LOGGER = LoggerFactory.getLogger(AwsNoSqlConnector.class); private final CommonAwsClient awsClient; public AwsNoSqlConnector(CommonAwsClient awsClient) { this.awsClient = awsClient; } @Override public NoSqlTableMetadataResponse getNoSqlTableMetaData(NoSqlTableMetadataRequest request) { try { LOGGER.debug("Calling DynamoDB.describeTable('{}')", request.getTableName()); AmazonDynamoDBClient dynamoDbClient = getAmazonDynamoDB(request); DescribeTableResult describeTableResult = dynamoDbClient.describeTable(request.getTableName()); LOGGER.debug("Successfully called DynamoDB.describeTable('{}')", request.getTableName()); return NoSqlTableMetadataResponse.builder() .withStatus(ResponseStatus.OK) .withId(describeTableResult.getTable().getTableArn()) .withTableStatus(describeTableResult.getTable().getTableStatus()) .build(); } catch (ResourceNotFoundException e) { LOGGER.info("DynamoDB table not found '{}'", request.getTableName()); return NoSqlTableMetadataResponse.builder() .withStatus(ResponseStatus.RESOURCE_NOT_FOUND) .build(); } catch (AmazonDynamoDBException e) { LOGGER.error(String.format("DynamoDB exception on describeTAble '%s'", request.getTableName()), e); throw new CloudConnectorException(String.format("Cannot get metadata for NoSQL table %s. " + "Provider error message: %s", request.getTableName(), e.getErrorMessage()), e); } } @Override public NoSqlTableDeleteResponse deleteNoSqlTable(NoSqlTableDeleteRequest request) { try { LOGGER.debug("Calling DynamoDB.deleteTable('{}')", request.getTableName()); AmazonDynamoDBClient dynamoDbClient = getAmazonDynamoDB(request); DeleteTableResult deleteTableResult = dynamoDbClient.deleteTable(request.getTableName()); LOGGER.debug("Successfully called DynamoDB.deleteTable('{}')", request.getTableName()); TableDescription tableDescription = deleteTableResult.getTableDescription(); return NoSqlTableDeleteResponse.builder() .withStatus(ResponseStatus.OK) .withId(tableDescription.getTableArn()) .withTableStatus(tableDescription.getTableStatus()) .build(); } catch (ResourceNotFoundException e) { LOGGER.info("DynamoDB table not found '{}'", request.getTableName()); return NoSqlTableDeleteResponse.builder() .withStatus(ResponseStatus.RESOURCE_NOT_FOUND) .build(); } catch (AmazonDynamoDBException e) { LOGGER.error(String.format("DynamoDB exception on deleteTable '%s'", request.getTableName()), e); throw new CloudConnectorException(String.format("Cannot delete NoSQL table %s. " + "Provider error message: %s", request.getTableName(), e.getErrorMessage()), e); } } @Override public Platform platform() { return AwsConstants.AWS_PLATFORM; } @Override public Variant variant() { return AwsConstants.AWS_DEFAULT_VARIANT; } private AmazonDynamoDBClient getAmazonDynamoDB(RegionAndCredentialAwareRequestBase request) { AwsCredentialView awsCredentialView = new AwsCredentialView(request.getCredential()); return awsClient.createDynamoDbClient(awsCredentialView, getRegion(request)); } private String getRegion(RegionAware regionAware) { return regionAware.getRegion(); } }
apache-2.0
kenwenzel/leveldb
leveldb/src/main/java/org/iq80/leveldb/util/ByteBufferSupport.java
2010
/* * Copyright (C) 2011 the original author or authors. * See the notice.md file distributed with this work for additional * information regarding copyright ownership. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.iq80.leveldb.util; import com.google.common.base.Throwables; import java.lang.reflect.Method; import java.nio.MappedByteBuffer; public final class ByteBufferSupport { private static final Method getCleaner; private static final Method clean; static { try { getCleaner = Class.forName("java.nio.DirectByteBuffer").getDeclaredMethod("cleaner"); getCleaner.setAccessible(true); } catch (ReflectiveOperationException e) { throw new AssertionError(e); } try { Class<?> returnType = getCleaner.getReturnType(); if (Runnable.class.isAssignableFrom(returnType)) { clean = Runnable.class.getMethod("run"); } else { clean = returnType.getMethod("clean"); } } catch (NoSuchMethodException e) { throw new AssertionError(e); } } private ByteBufferSupport() { } public static void unmap(MappedByteBuffer buffer) { try { Object cleaner = getCleaner.invoke(buffer); clean.invoke(cleaner); } catch (Exception ignored) { throw Throwables.propagate(ignored); } } }
apache-2.0
MotionArduino/JavaControl
src/KLog.java
660
/** * Log Utils * @author caisenchuan */ public class KLog { private static final boolean DEBUG = true; public static void d(String tag, String format, Object... args) { if (DEBUG) { String str = String.format(format, args); String ret = String.format("%s(D) : %s", tag, str); System.out.println(ret); } } public static void e(String tag, String format, Object... args) { String str = String.format(format, args); String ret = String.format("%s(E) : %s", tag, str); System.out.println(ret); } public static void e(String tag, Throwable tr, String format, Object... args) { e(tag, format, args); tr.printStackTrace(); } }
apache-2.0
starksm64/pi4j
pi4j-core/src/main/java/com/pi4j/io/gpio/exception/GpioPinExistsException.java
1625
package com.pi4j.io.gpio.exception; /* * #%L * ********************************************************************** * ORGANIZATION : Pi4J * PROJECT : Pi4J :: Java Library (Core) * FILENAME : GpioPinExistsException.java * * This file is part of the Pi4J project. More information about * this project can be found here: http://www.pi4j.com/ * ********************************************************************** * %% * Copyright (C) 2012 - 2013 Pi4J * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ import com.pi4j.io.gpio.Pin; /** * GPIO pin already exists exception. * * @author Robert Savage (<a * href="http://www.savagehomeautomation.com">http://www.savagehomeautomation.com</a>) */ public class GpioPinExistsException extends RuntimeException { private static final long serialVersionUID = 1171484082578232353L; private final Pin pin; public GpioPinExistsException(Pin pin) { super("This GPIO pin already exists: " + pin.toString()); this.pin = pin; } public Pin getPin() { return pin; } }
apache-2.0
OpenHFT/Chronicle-Map
src/main/java/net/openhft/chronicle/hash/serialization/impl/SizedMarshallableDataAccess.java
5229
/* * Copyright 2012-2018 Chronicle Map Contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.openhft.chronicle.hash.serialization.impl; import net.openhft.chronicle.bytes.*; import net.openhft.chronicle.hash.Data; import net.openhft.chronicle.hash.serialization.DataAccess; import net.openhft.chronicle.hash.serialization.SizedReader; import net.openhft.chronicle.hash.serialization.SizedWriter; import net.openhft.chronicle.wire.WireIn; import net.openhft.chronicle.wire.WireOut; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.lang.reflect.Type; import static net.openhft.chronicle.hash.serialization.StatefulCopyable.copyIfNeeded; import static net.openhft.chronicle.hash.serialization.impl.DefaultElasticBytes.DEFAULT_BYTES_CAPACITY; public class SizedMarshallableDataAccess<T> extends InstanceCreatingMarshaller<T> implements DataAccess<T>, Data<T> { // Config fields private SizedReader<T> sizedReader; private SizedWriter<? super T> sizedWriter; // Cache fields private transient boolean bytesInit; private transient Bytes bytes; private transient long size; private transient VanillaBytes targetBytes; /** * State field */ private transient T instance; public SizedMarshallableDataAccess( Class<T> tClass, SizedReader<T> sizedReader, SizedWriter<? super T> sizedWriter) { this(tClass, sizedReader, sizedWriter, DEFAULT_BYTES_CAPACITY); } protected SizedMarshallableDataAccess( Type tClass, SizedReader<T> sizedReader, SizedWriter<? super T> sizedWriter, long bytesCapacity) { super(tClass); this.sizedWriter = sizedWriter; this.sizedReader = sizedReader; initTransients(bytesCapacity); } SizedReader<T> sizedReader() { return sizedReader; } SizedWriter<? super T> sizedWriter() { return sizedWriter; } private void initTransients(long bytesCapacity) { bytes = DefaultElasticBytes.allocateDefaultElasticBytes(bytesCapacity); targetBytes = VanillaBytes.vanillaBytes(); } @Override public RandomDataInput bytes() { if (!bytesInit) { bytes.clear(); sizedWriter.write(bytes, size, instance); bytesInit = true; } return bytes.bytesStore(); } @Override public long offset() { return 0; } @Override public long size() { return size; } @Override public void writeTo(RandomDataOutput target, long targetOffset) { if (bytesInit || !(target instanceof BytesStore)) { target.write(targetOffset, bytes(), offset(), size); } else { targetBytes.bytesStore((BytesStore) target, targetOffset, size); targetBytes.writePosition(targetOffset); sizedWriter.write(targetBytes, size, instance); targetBytes.bytesStore(NoBytesStore.NO_BYTES_STORE, 0, 0); } } @Override public T get() { return instance; } @Override public T getUsing(@Nullable T using) { if (using == null) using = createInstance(); T result = sizedReader.read(bytes, size(), using); bytes.readPosition(0); return result; } @Override public int hashCode() { return dataHashCode(); } @Override public boolean equals(Object obj) { return dataEquals(obj); } @Override public String toString() { return get().toString(); } @Override public Data<T> getData(@NotNull T instance) { this.instance = instance; this.size = sizedWriter.size(instance); bytesInit = false; return this; } @Override public void uninit() { instance = null; } @Override public DataAccess<T> copy() { return new SizedMarshallableDataAccess<>( tType(), copyIfNeeded(sizedReader), copyIfNeeded(sizedWriter), bytes.realCapacity()); } @Override public void readMarshallable(@NotNull WireIn wireIn) { super.readMarshallable(wireIn); sizedReader = wireIn.read(() -> "sizedReader").object(SizedReader.class); sizedWriter = wireIn.read(() -> "sizedWriter").object(SizedWriter.class); initTransients(DEFAULT_BYTES_CAPACITY); } @Override public void writeMarshallable(@NotNull WireOut wireOut) { super.writeMarshallable(wireOut); wireOut.write(() -> "sizedReader").typedMarshallable(sizedReader); wireOut.write(() -> "sizedWriter").typedMarshallable(sizedWriter); } }
apache-2.0
ZhangPeng1990/crm
gdsap-framework/src/main/java/uk/co/quidos/gdsap/framework/authority/exeception/AuthorityException.java
291
/** * */ package uk.co.quidos.gdsap.framework.authority.exeception; import uk.co.quidos.common.util.exception.ASException; /** * @author peng.shi */ public class AuthorityException extends ASException { private static final long serialVersionUID = -2804585582393923554L; }
apache-2.0
thymeleaf/thymeleaf
src/main/java/org/thymeleaf/engine/IterationStatusVar.java
2194
/* * ============================================================================= * * Copyright (c) 2011-2018, The THYMELEAF team (http://www.thymeleaf.org) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * ============================================================================= */ package org.thymeleaf.engine; /** * * @author Daniel Fern&aacute;ndez * * @since 3.0.0 (equivalent to the one existing since 1.0) * */ public final class IterationStatusVar { int index; Integer size; // it can be null if we don't know the size of the iterated object beforehand! Object current; IterationStatusVar() { super(); } public int getIndex() { return this.index; } public int getCount() { return this.index + 1; } public boolean hasSize() { return this.size != null; } public Integer getSize() { return this.size; } public Object getCurrent() { return this.current; } public boolean isEven() { // We start counting in 1 in order to be consistent with :nth-child(odd) and :nth-child(even) CSS selectors return ((this.index + 1) % 2 == 0); } public boolean isOdd() { return !isEven(); } public boolean isFirst() { return (this.index == 0); } public boolean isLast() { return (this.index == this.size - 1); } @Override public String toString() { return "{index = " + this.index + ", count = " + (this.index + 1) + ", size = " + this.size + ", current = " + (this.current == null? "null" : this.current.toString()) + "}"; } }
apache-2.0
archear/Test1
dubbo.interface/src/main/java/cn/arch/iinterface/OnePlues.java
140
package cn.arch.iinterface; /** * Created by archer on 2017/3/29. */ public interface OnePlues { Integer addOne(Integer integer); }
apache-2.0
qobel/esoguproject
spring-framework/spring-test/src/test/java/org/springframework/test/context/testng/transaction/ejb/RollbackForRequiredEjbTxDaoTestNGTests.java
2447
/* * Copyright 2002-2014 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.test.context.testng.transaction.ejb; import org.testng.annotations.Test; import org.springframework.test.context.transaction.TransactionConfiguration; import org.springframework.test.context.transaction.TransactionalTestExecutionListener; import static org.testng.AssertJUnit.*; /** * Extension of {@link CommitForRequiredEjbTxDaoTestNGTests} which sets the default * rollback semantics for the {@link TransactionalTestExecutionListener} to * {@code true}. The transaction managed by the TestContext framework will be * rolled back after each test method. Consequently, any work performed in * transactional methods that participate in the test-managed transaction will * be rolled back automatically. * * @author Sam Brannen * @since 4.0.1 */ @Test(suiteName = "Rollback for REQUIRED") @TransactionConfiguration(defaultRollback = true) public class RollbackForRequiredEjbTxDaoTestNGTests extends CommitForRequiredEjbTxDaoTestNGTests { /** * Overrides parent implementation in order to change expectations to align with * behavior associated with "required" transactions on repositories/DAOs and * default rollback semantics for transactions managed by the TestContext * framework. */ @Test(dependsOnMethods = "test2IncrementCount1") @Override public void test3IncrementCount2() { int count = dao.getCount(TEST_NAME); // Expecting count=0 after test2IncrementCount1() since REQUIRED transactions // participate in the existing transaction (if present), which in this case is the // transaction managed by the TestContext framework which will be rolled back // after each test method. assertEquals("Expected count=0 after test2IncrementCount1().", 0, count); count = dao.incrementCount(TEST_NAME); assertEquals("Expected count=1 now.", 1, count); } }
apache-2.0
openengsb/openengsb
components/workflow/src/test/java/org/openengsb/core/workflow/drools/DummyNotificationDomain.java
1014
/** * Licensed to the Austrian Association for Software Tool Integration (AASTI) * under one or more contributor license agreements. See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. The AASTI licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.openengsb.core.workflow.drools; import org.openengsb.core.api.Domain; public interface DummyNotificationDomain extends Domain { void notify(String notification); }
apache-2.0
OpenVidu/openvidu
openvidu-test-browsers/src/main/java/io/openvidu/test/browsers/utils/RecordingUtils.java
10817
package io.openvidu.test.browsers.utils; import java.awt.Color; import java.awt.image.BufferedImage; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.math.RoundingMode; import java.text.DecimalFormat; import java.util.Arrays; import java.util.Base64; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.function.Function; import javax.imageio.ImageIO; import org.jcodec.api.FrameGrab; import org.jcodec.api.JCodecException; import org.jcodec.common.model.Picture; import org.jcodec.scale.AWTUtil; import org.junit.Assert; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.gson.Gson; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import com.google.gson.stream.JsonReader; import io.openvidu.java.client.Recording; public class RecordingUtils { protected static final Logger log = LoggerFactory.getLogger(RecordingUtils.class); public boolean recordedGreenFileFine(File file, Recording recording) throws IOException { return this.recordedFileFine(file, recording, RecordingUtils::checkVideoAverageRgbGreen); } public boolean recordedRedFileFine(File file, Recording recording) throws IOException { return this.recordedFileFine(file, recording, RecordingUtils::checkVideoAverageRgbRed); } private boolean recordedFileFine(File file, Recording recording, Function<Map<String, Long>, Boolean> colorCheckFunction) throws IOException { this.checkMultimediaFile(file, recording.hasAudio(), recording.hasVideo(), recording.getDuration(), recording.getResolution(), recording.getFrameRate(), "aac", "h264", true); boolean isFine = false; Picture frame; try { // Get a frame at 75% duration and check that it has the expected color frame = FrameGrab.getFrameAtSec(file, (double) (recording.getDuration() * 0.75)); BufferedImage image = AWTUtil.toBufferedImage(frame); Map<String, Long> colorMap = this.averageColor(image); String realResolution = image.getWidth() + "x" + image.getHeight(); Assert.assertEquals( "Resolution (" + recording.getResolution() + ") of recording entity is not equal to real video resolution (" + realResolution + ")", recording.getResolution(), realResolution); log.info("Recording map color: {}", colorMap.toString()); log.info("Recording frame below"); System.out.println(bufferedImageToBase64PngString(image)); isFine = colorCheckFunction.apply(colorMap); } catch (IOException | JCodecException e) { log.warn("Error getting frame from video recording: {}", e.getMessage()); isFine = false; } return isFine; } public static boolean checkVideoAverageRgbGreen(Map<String, Long> rgb) { // GREEN color: {r < 15, g > 130, b <15} return (rgb.get("r") < 15) && (rgb.get("g") > 130) && (rgb.get("b") < 15); } public static boolean checkVideoAverageRgbGray(Map<String, Long> rgb) { // GRAY color: {r < 50, g < 50, b < 50} and the absolute difference between them // not greater than 2 return (rgb.get("r") < 50) && (rgb.get("g") < 50) && (rgb.get("b") < 50) && (Math.abs(rgb.get("r") - rgb.get("g")) <= 2) && (Math.abs(rgb.get("r") - rgb.get("b")) <= 2) && (Math.abs(rgb.get("b") - rgb.get("g")) <= 2); } public static boolean checkVideoAverageRgbRed(Map<String, Long> rgb) { // RED color: {r > 240, g < 15, b <15} return (rgb.get("r") > 240) && (rgb.get("g") < 15) && (rgb.get("b") < 15); } private String bufferedImageToBase64PngString(BufferedImage image) { ByteArrayOutputStream bos = new ByteArrayOutputStream(); String imageString = null; try { ImageIO.write(image, "png", bos); byte[] imageBytes = bos.toByteArray(); imageString = "data:image/png;base64," + Base64.getEncoder().encodeToString(imageBytes); bos.close(); } catch (IOException e) { e.printStackTrace(); } return imageString; } public void checkIndividualRecording(String recPath, Recording recording, int numberOfVideoFiles, String audioDecoder, String videoDecoder, boolean checkAudio) throws IOException { // Should be only 2 files: zip and metadata File folder = new File(recPath); Assert.assertEquals("There are more than 2 files (ZIP and metadata) inside individual recording folder " + recPath + ": " + Arrays.toString(folder.listFiles()), 2, folder.listFiles().length); File file1 = new File(recPath + recording.getName() + ".zip"); File file2 = new File(recPath + ".recording." + recording.getId()); Assert.assertTrue("File " + file1.getAbsolutePath() + " does not exist or is empty", file1.exists() && file1.length() > 0); Assert.assertTrue("File " + file2.getAbsolutePath() + " does not exist or is empty", file2.exists() && file2.length() > 0); List<File> unzippedWebmFiles = new Unzipper().unzipFile(recPath, recording.getName() + ".zip"); Assert.assertEquals("Expecting " + numberOfVideoFiles + " videos inside ZIP file but " + unzippedWebmFiles.size() + " found: " + unzippedWebmFiles.toString(), numberOfVideoFiles, unzippedWebmFiles.size()); File jsonSyncFile = new File(recPath + recording.getName() + ".json"); Assert.assertTrue("JSON sync file " + jsonSyncFile.getAbsolutePath() + "does not exist or is empty", jsonSyncFile.exists() && jsonSyncFile.length() > 0); JsonObject jsonSyncMetadata; try { Gson gson = new Gson(); JsonReader reader = new JsonReader(new FileReader(jsonSyncFile)); jsonSyncMetadata = gson.fromJson(reader, JsonObject.class); } catch (Exception e) { log.error("Cannot read JSON sync metadata file from {}. Error: {}", jsonSyncFile.getAbsolutePath(), e.getMessage()); Assert.fail("Cannot read JSON sync metadata file from " + jsonSyncFile.getAbsolutePath()); return; } long totalFileSize = 0; JsonArray syncArray = jsonSyncMetadata.get("files").getAsJsonArray(); for (File webmFile : unzippedWebmFiles) { totalFileSize += webmFile.length(); Assert.assertTrue("WEBM file " + webmFile.getAbsolutePath() + " does not exist or is empty", webmFile.exists() && webmFile.length() > 0); double durationInSeconds = 0; boolean found = false; for (int i = 0; i < syncArray.size(); i++) { JsonObject j = syncArray.get(i).getAsJsonObject(); if (webmFile.getName().contains(j.get("streamId").getAsString())) { durationInSeconds = (double) (j.get("endTimeOffset").getAsDouble() - j.get("startTimeOffset").getAsDouble()) / 1000; found = true; break; } } Assert.assertTrue("Couldn't find in JSON sync object information for webm file " + webmFile.getName(), found); log.info("Duration of {} according to sync metadata json file: {} s", webmFile.getName(), durationInSeconds); this.checkMultimediaFile(webmFile, recording.hasAudio(), recording.hasVideo(), durationInSeconds, recording.getResolution(), recording.getFrameRate(), audioDecoder, videoDecoder, checkAudio); webmFile.delete(); } Assert.assertEquals("Size of recording entity (" + recording.getSessionId() + ") is not equal to real file size (" + totalFileSize + ")", recording.getSize(), totalFileSize); jsonSyncFile.delete(); } public void checkMultimediaFile(File file, boolean hasAudio, boolean hasVideo, double duration, String resolution, Integer frameRate, String audioDecoder, String videoDecoder, boolean checkAudio) throws IOException { // Check tracks, duration, resolution, framerate and decoders MultimediaFileMetadata metadata = new MultimediaFileMetadata(file.getAbsolutePath()); if (hasVideo) { if (checkAudio) { if (hasAudio) { Assert.assertTrue("Media file " + file.getAbsolutePath() + " should have audio", metadata.hasAudio() && metadata.hasVideo()); Assert.assertTrue(metadata.getAudioDecoder().toLowerCase().contains(audioDecoder)); } else { Assert.assertTrue("Media file " + file.getAbsolutePath() + " should have video", metadata.hasVideo()); Assert.assertFalse(metadata.hasAudio()); } } if (resolution != null) { Assert.assertEquals(resolution, metadata.getVideoWidth() + "x" + metadata.getVideoHeight()); } if (frameRate != null) { Assert.assertEquals(frameRate.intValue(), metadata.getFrameRate()); } Assert.assertTrue(metadata.getVideoDecoder().toLowerCase().contains(videoDecoder)); } else if (hasAudio && checkAudio) { Assert.assertTrue(metadata.hasAudio()); Assert.assertFalse(metadata.hasVideo()); Assert.assertTrue(metadata.getAudioDecoder().toLowerCase().contains(audioDecoder)); } else { Assert.fail("Cannot check a file witho no audio and no video"); } // Check duration with 1 decimal precision DecimalFormat df = new DecimalFormat("#0.0"); df.setRoundingMode(RoundingMode.UP); log.info("Duration of {} according to ffmpeg: {} s", file.getName(), metadata.getDuration()); log.info("Duration of {} according to 'duration' property: {} s", file.getName(), duration); log.info("Difference in s duration: {}", Math.abs(metadata.getDuration() - duration)); final double difference = 10; Assert.assertTrue( "Difference between recording entity duration (" + duration + ") and real video duration (" + metadata.getDuration() + ") is greater than " + difference + " in file " + file.getName(), Math.abs((metadata.getDuration() - duration)) < difference); } public boolean thumbnailIsFine(File file, Function<Map<String, Long>, Boolean> colorCheckFunction) { boolean isFine = false; BufferedImage image = null; try { image = ImageIO.read(file); } catch (IOException e) { log.error(e.getMessage()); return false; } log.info("Recording thumbnail dimensions: {}x{}", image.getWidth(), image.getHeight()); Map<String, Long> colorMap = this.averageColor(image); log.info("Thumbnail map color: {}", colorMap.toString()); isFine = colorCheckFunction.apply(colorMap); if (!isFine) { try { log.error("Thumbnail is not fine. Printed below"); System.out.println(bufferedImageToBase64PngString(ImageIO.read(file))); } catch (IOException e) { e.printStackTrace(); } } return isFine; } private Map<String, Long> averageColor(BufferedImage bi) { int x0 = 0; int y0 = 0; int w = bi.getWidth(); int h = bi.getHeight(); int x1 = x0 + w; int y1 = y0 + h; long sumr = 0, sumg = 0, sumb = 0; for (int x = x0; x < x1; x++) { for (int y = y0; y < y1; y++) { Color pixel = new Color(bi.getRGB(x, y)); sumr += pixel.getRed(); sumg += pixel.getGreen(); sumb += pixel.getBlue(); } } int num = w * h; Map<String, Long> colorMap = new HashMap<>(); colorMap.put("r", (long) (sumr / num)); colorMap.put("g", (long) (sumg / num)); colorMap.put("b", (long) (sumb / num)); return colorMap; } }
apache-2.0
SHAF-WORK/shaf
core/src/test/java/org/shaf/core/content/GroupOptionInfoTest.java
3614
/** * Copyright 2014-2015 SHAF-WORK * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.shaf.core.content; import static org.junit.Assert.*; import org.junit.Test; import org.shaf.core.content.GroupOptionInfo; import org.shaf.core.content.SingleOptionInfo; import org.shaf.core.util.XmlUtils; /** * The class {@code GroupOptionInfoTest} contains tests for the class * {@link GroupOptionInfo}. * * @author Mykola Galushka */ public class GroupOptionInfoTest { /** * Run the [constructor] tests. * * @throws Exception * if the test fails for some reason. */ @Test public void testConstructor() throws Exception { GroupOptionInfo g = null; // Constructor #1 g = new GroupOptionInfo(true); assertTrue(g.isRequired()); // Constructor #2 g = new GroupOptionInfo(); assertFalse(g.isRequired()); } /** * Run [add] method test. * * @throws Exception * if the test fails for some reason. */ @Test public void testAdd() throws Exception { GroupOptionInfo g = new GroupOptionInfo(); g.addOptionInfo(new SingleOptionInfo("a", "descr a")); g.addOptionInfo(new SingleOptionInfo("b", "descr b")); g.addOptionInfo(new SingleOptionInfo("c", "descr c")); boolean a = false; boolean b = false; boolean c = false; for (SingleOptionInfo o : g) { if (o.getName().equals("a")){ a = true; } if (o.getName().equals("b")){ b = true; } if (o.getName().equals("c")){ c = true; } } assertTrue(a); assertTrue(b); assertTrue(c); assertFalse(g.isRequired()); g.setRequired(true); assertTrue(g.isRequired()); } /** * Run [hashCode/equals/toString] method test. * * @throws Exception * if the test fails for some reason. */ @Test public void testHashEqualsString() throws Exception { GroupOptionInfo ga = new GroupOptionInfo(true); ga.addOptionInfo(new SingleOptionInfo("a", "b")); ga.addOptionInfo(new SingleOptionInfo("c", "d")); GroupOptionInfo gb = new GroupOptionInfo(true); gb.addOptionInfo(new SingleOptionInfo("a", "b")); gb.addOptionInfo(new SingleOptionInfo("c", "d")); GroupOptionInfo gc = new GroupOptionInfo(true); gc.addOptionInfo(new SingleOptionInfo("e", "f")); gc.addOptionInfo(new SingleOptionInfo("g", "i")); assertEquals(ga.hashCode(), gb.hashCode()); assertNotEquals(ga.hashCode(), gc.hashCode()); assertTrue(ga.equals(gb)); assertFalse(ga.equals(gc)); assertTrue(ga.toString().startsWith(ga.getClass().getSimpleName())); } /** * Run XML binding tests. * * @throws Exception * if the test fails for some reason. */ @Test public void testXmlBinding() throws Exception { GroupOptionInfo out = new GroupOptionInfo(true); out.addOptionInfo(new SingleOptionInfo("a", "b")); out.addOptionInfo(new SingleOptionInfo("c", "d")); GroupOptionInfo in = (GroupOptionInfo) XmlUtils.xml2obj( GroupOptionInfo.class, XmlUtils.obj2xml(out)); assertTrue(out.equals(in)); } }
apache-2.0
phax/ph-oton
ph-oton-html/src/main/java/com/helger/html/hc/html/textlevel/AbstractHCA.java
5121
/* * Copyright (C) 2014-2022 Philip Helger (www.helger.com) * philip[at]helger[dot]com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.helger.html.hc.html.textlevel; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.annotation.OverridingMethodsMustInvokeSuper; import com.helger.commons.ValueEnforcer; import com.helger.commons.mime.IMimeType; import com.helger.commons.string.StringHelper; import com.helger.commons.string.ToStringGenerator; import com.helger.commons.url.ISimpleURL; import com.helger.html.CHTMLAttributes; import com.helger.html.EHTMLElement; import com.helger.html.hc.IHCConversionSettingsToNode; import com.helger.html.hc.config.HCConsistencyChecker; import com.helger.html.hc.html.AbstractHCElementWithChildren; import com.helger.html.hc.html.HCHTMLHelper; import com.helger.html.hc.html.HC_Target; import com.helger.xml.microdom.IMicroElement; /** * Represents an HTML &lt;a&gt; element * * @author Philip Helger * @param <IMPLTYPE> * Implementation type */ public abstract class AbstractHCA <IMPLTYPE extends AbstractHCA <IMPLTYPE>> extends AbstractHCElementWithChildren <IMPLTYPE> implements IHCA <IMPLTYPE> { private ISimpleURL m_aHref; private HC_Target m_aTarget; private String m_sName; private IMimeType m_aType; private String m_sMediaQuery; public AbstractHCA () { super (EHTMLElement.A); } public AbstractHCA (@Nonnull final ISimpleURL aHref) { this (); setHref (aHref); } @Nullable public final ISimpleURL getHref () { return m_aHref; } @Nonnull public final IMPLTYPE setHref (@Nonnull final ISimpleURL aHref) { ValueEnforcer.notNull (aHref, "href"); m_aHref = aHref; return thisAsT (); } @Nullable public final HC_Target getTarget () { return m_aTarget; } @Nonnull public final IMPLTYPE setTarget (@Nullable final HC_Target aTarget) { m_aTarget = aTarget; return thisAsT (); } @Nullable public final String getName () { return m_sName; } @Nonnull public final IMPLTYPE setName (@Nullable final String sName) { m_sName = sName; return thisAsT (); } @Nullable public final IMimeType getType () { return m_aType; } @Nonnull public final IMPLTYPE setType (@Nullable final IMimeType aType) { m_aType = aType; return thisAsT (); } @Nullable public final String getMedia () { return m_sMediaQuery; } @Nonnull public final IMPLTYPE setMedia (@Nullable final String sMediaQuery) { m_sMediaQuery = sMediaQuery; return thisAsT (); } @Override protected void onConsistencyCheck (@Nonnull final IHCConversionSettingsToNode aConversionSettings) { super.onConsistencyCheck (aConversionSettings); if (HCHTMLHelper.recursiveContainsChildWithTagName (this, EHTMLElement.A)) HCConsistencyChecker.consistencyError ("<A> may never contain other links!"); if (HCHTMLHelper.recursiveContainsChildWithTagName (this, EHTMLElement.SELECT)) HCConsistencyChecker.consistencyError ("<A> contains invalid child element!"); } @Override @OverridingMethodsMustInvokeSuper protected void fillMicroElement (final IMicroElement aElement, final IHCConversionSettingsToNode aConversionSettings) { super.fillMicroElement (aElement, aConversionSettings); if (m_aHref != null) { final String sHref = m_aHref.getAsStringWithEncodedParameters (aConversionSettings.getCharset ()); aElement.setAttribute (CHTMLAttributes.HREF, sHref); } if (m_aTarget != null) { // Note: attribute "target" is not allowed in XHTML 1.0 strict (but in // 1.1) aElement.setAttribute (CHTMLAttributes.TARGET, m_aTarget); } if (StringHelper.hasText (m_sName)) aElement.setAttribute (CHTMLAttributes.NAME, m_sName); if (m_aType != null) aElement.setAttribute (CHTMLAttributes.TYPE, m_aType.getAsString ()); // HTML5 only: if (StringHelper.hasText (m_sMediaQuery)) aElement.setAttribute (CHTMLAttributes.MEDIA, m_sMediaQuery); } @Override public String toString () { return ToStringGenerator.getDerived (super.toString ()) .appendIfNotNull ("href", m_aHref) .appendIfNotNull ("target", m_aTarget) .appendIfNotNull ("name", m_sName) .appendIfNotNull ("type", m_aType) .appendIfNotNull ("mediaQuery", m_sMediaQuery) .getToString (); } }
apache-2.0
jentfoo/aws-sdk-java
aws-java-sdk-sqs/src/main/java/com/amazonaws/services/sqs/model/ChangeMessageVisibilityBatchResult.java
8917
/* * Copyright 2014-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.sqs.model; import java.io.Serializable; import javax.annotation.Generated; /** * <p> * For each message in the batch, the response contains a <code> <a>ChangeMessageVisibilityBatchResultEntry</a> </code> * tag if the message succeeds or a <code> <a>BatchResultErrorEntry</a> </code> tag if the message fails. * </p> * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/sqs-2012-11-05/ChangeMessageVisibilityBatch" target="_top">AWS * API Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class ChangeMessageVisibilityBatchResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable { /** * <p> * A list of <code> <a>ChangeMessageVisibilityBatchResultEntry</a> </code> items. * </p> */ private com.amazonaws.internal.SdkInternalList<ChangeMessageVisibilityBatchResultEntry> successful; /** * <p> * A list of <code> <a>BatchResultErrorEntry</a> </code> items. * </p> */ private com.amazonaws.internal.SdkInternalList<BatchResultErrorEntry> failed; /** * <p> * A list of <code> <a>ChangeMessageVisibilityBatchResultEntry</a> </code> items. * </p> * * @return A list of <code> <a>ChangeMessageVisibilityBatchResultEntry</a> </code> items. */ public java.util.List<ChangeMessageVisibilityBatchResultEntry> getSuccessful() { if (successful == null) { successful = new com.amazonaws.internal.SdkInternalList<ChangeMessageVisibilityBatchResultEntry>(); } return successful; } /** * <p> * A list of <code> <a>ChangeMessageVisibilityBatchResultEntry</a> </code> items. * </p> * * @param successful * A list of <code> <a>ChangeMessageVisibilityBatchResultEntry</a> </code> items. */ public void setSuccessful(java.util.Collection<ChangeMessageVisibilityBatchResultEntry> successful) { if (successful == null) { this.successful = null; return; } this.successful = new com.amazonaws.internal.SdkInternalList<ChangeMessageVisibilityBatchResultEntry>(successful); } /** * <p> * A list of <code> <a>ChangeMessageVisibilityBatchResultEntry</a> </code> items. * </p> * <p> * <b>NOTE:</b> This method appends the values to the existing list (if any). Use * {@link #setSuccessful(java.util.Collection)} or {@link #withSuccessful(java.util.Collection)} if you want to * override the existing values. * </p> * * @param successful * A list of <code> <a>ChangeMessageVisibilityBatchResultEntry</a> </code> items. * @return Returns a reference to this object so that method calls can be chained together. */ public ChangeMessageVisibilityBatchResult withSuccessful(ChangeMessageVisibilityBatchResultEntry... successful) { if (this.successful == null) { setSuccessful(new com.amazonaws.internal.SdkInternalList<ChangeMessageVisibilityBatchResultEntry>(successful.length)); } for (ChangeMessageVisibilityBatchResultEntry ele : successful) { this.successful.add(ele); } return this; } /** * <p> * A list of <code> <a>ChangeMessageVisibilityBatchResultEntry</a> </code> items. * </p> * * @param successful * A list of <code> <a>ChangeMessageVisibilityBatchResultEntry</a> </code> items. * @return Returns a reference to this object so that method calls can be chained together. */ public ChangeMessageVisibilityBatchResult withSuccessful(java.util.Collection<ChangeMessageVisibilityBatchResultEntry> successful) { setSuccessful(successful); return this; } /** * <p> * A list of <code> <a>BatchResultErrorEntry</a> </code> items. * </p> * * @return A list of <code> <a>BatchResultErrorEntry</a> </code> items. */ public java.util.List<BatchResultErrorEntry> getFailed() { if (failed == null) { failed = new com.amazonaws.internal.SdkInternalList<BatchResultErrorEntry>(); } return failed; } /** * <p> * A list of <code> <a>BatchResultErrorEntry</a> </code> items. * </p> * * @param failed * A list of <code> <a>BatchResultErrorEntry</a> </code> items. */ public void setFailed(java.util.Collection<BatchResultErrorEntry> failed) { if (failed == null) { this.failed = null; return; } this.failed = new com.amazonaws.internal.SdkInternalList<BatchResultErrorEntry>(failed); } /** * <p> * A list of <code> <a>BatchResultErrorEntry</a> </code> items. * </p> * <p> * <b>NOTE:</b> This method appends the values to the existing list (if any). Use * {@link #setFailed(java.util.Collection)} or {@link #withFailed(java.util.Collection)} if you want to override the * existing values. * </p> * * @param failed * A list of <code> <a>BatchResultErrorEntry</a> </code> items. * @return Returns a reference to this object so that method calls can be chained together. */ public ChangeMessageVisibilityBatchResult withFailed(BatchResultErrorEntry... failed) { if (this.failed == null) { setFailed(new com.amazonaws.internal.SdkInternalList<BatchResultErrorEntry>(failed.length)); } for (BatchResultErrorEntry ele : failed) { this.failed.add(ele); } return this; } /** * <p> * A list of <code> <a>BatchResultErrorEntry</a> </code> items. * </p> * * @param failed * A list of <code> <a>BatchResultErrorEntry</a> </code> items. * @return Returns a reference to this object so that method calls can be chained together. */ public ChangeMessageVisibilityBatchResult withFailed(java.util.Collection<BatchResultErrorEntry> failed) { setFailed(failed); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getSuccessful() != null) sb.append("Successful: ").append(getSuccessful()).append(","); if (getFailed() != null) sb.append("Failed: ").append(getFailed()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof ChangeMessageVisibilityBatchResult == false) return false; ChangeMessageVisibilityBatchResult other = (ChangeMessageVisibilityBatchResult) obj; if (other.getSuccessful() == null ^ this.getSuccessful() == null) return false; if (other.getSuccessful() != null && other.getSuccessful().equals(this.getSuccessful()) == false) return false; if (other.getFailed() == null ^ this.getFailed() == null) return false; if (other.getFailed() != null && other.getFailed().equals(this.getFailed()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getSuccessful() == null) ? 0 : getSuccessful().hashCode()); hashCode = prime * hashCode + ((getFailed() == null) ? 0 : getFailed().hashCode()); return hashCode; } @Override public ChangeMessageVisibilityBatchResult clone() { try { return (ChangeMessageVisibilityBatchResult) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } }
apache-2.0
thunderace/mpd-control
src/org/thunder/jmdns/impl/JmmDNSImpl.java
29934
/** * */ package org.thunder.jmdns.impl; import java.io.IOException; import java.net.InetAddress; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.Callable; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.logging.Level; import java.util.logging.Logger; import org.thunder.jmdns.JmDNS; import org.thunder.jmdns.JmmDNS; import org.thunder.jmdns.NetworkTopologyDiscovery; import org.thunder.jmdns.NetworkTopologyEvent; import org.thunder.jmdns.NetworkTopologyListener; import org.thunder.jmdns.ServiceInfo; import org.thunder.jmdns.ServiceListener; import org.thunder.jmdns.ServiceTypeListener; import org.thunder.jmdns.impl.constants.DNSConstants; import org.thunder.jmdns.impl.util.NamedThreadFactory; /** * This class enable multihoming mDNS. It will open a mDNS per IP address of the machine. * * @author C&eacute;drik Lime, Pierre Frisch */ public class JmmDNSImpl implements JmmDNS, NetworkTopologyListener, ServiceInfoImpl.Delegate { private static Logger logger = Logger.getLogger(JmmDNSImpl.class.getName()); private final Set<NetworkTopologyListener> _networkListeners; /** * Every JmDNS created. */ private final ConcurrentMap<InetAddress, JmDNS> _knownMDNS; /** * This enable the service info text update. */ private final ConcurrentMap<String, ServiceInfo> _services; /** * List of registered services */ private final Set<String> _serviceTypes; /** * Holds instances of ServiceListener's. Keys are Strings holding a fully qualified service type. Values are LinkedList's of ServiceListener's. */ private final ConcurrentMap<String, List<ServiceListener>> _serviceListeners; /** * Holds instances of ServiceTypeListener's. */ private final Set<ServiceTypeListener> _typeListeners; private final ExecutorService _listenerExecutor; private final ExecutorService _jmDNSExecutor; private final Timer _timer; private final AtomicBoolean _isClosing; private final AtomicBoolean _closed; /** * */ public JmmDNSImpl() { super(); _networkListeners = Collections.synchronizedSet(new HashSet<NetworkTopologyListener>()); _knownMDNS = new ConcurrentHashMap<InetAddress, JmDNS>(); _services = new ConcurrentHashMap<String, ServiceInfo>(20); _listenerExecutor = Executors.newSingleThreadExecutor(new NamedThreadFactory("JmmDNS Listeners")); _jmDNSExecutor = Executors.newCachedThreadPool(new NamedThreadFactory("JmmDNS")); _timer = new Timer("Multihomed mDNS.Timer", true); _serviceListeners = new ConcurrentHashMap<String, List<ServiceListener>>(); _typeListeners = Collections.synchronizedSet(new HashSet<ServiceTypeListener>()); _serviceTypes = Collections.synchronizedSet(new HashSet<String>()); (new NetworkChecker(this, NetworkTopologyDiscovery.Factory.getInstance())).start(_timer); _isClosing = new AtomicBoolean(false); _closed = new AtomicBoolean(false); } /* * (non-Javadoc) * @see java.io.Closeable#close() */ @Override public void close() throws IOException { if (_isClosing.compareAndSet(false, true)) { if (logger.isLoggable(Level.FINER)) { logger.finer("Cancelling JmmDNS: " + this); } _timer.cancel(); _listenerExecutor.shutdown(); _jmDNSExecutor.shutdown(); // We need to cancel all the DNS ExecutorService executor = Executors.newCachedThreadPool(new NamedThreadFactory("JmmDNS.close")); try { for (final JmDNS mDNS : this.getDNS()) { executor.submit(new Runnable() { /** * {@inheritDoc} */ @Override public void run() { try { mDNS.close(); } catch (IOException exception) { // JmDNS never throws this is only because of the closeable interface } } }); } } finally { executor.shutdown(); } try { executor.awaitTermination(DNSConstants.CLOSE_TIMEOUT, TimeUnit.MILLISECONDS); } catch (InterruptedException exception) { logger.log(Level.WARNING, "Exception ", exception); } _knownMDNS.clear(); _services.clear(); _serviceListeners.clear(); _typeListeners.clear(); _serviceTypes.clear(); _closed.set(true); JmmDNS.Factory.close(); } } /* * (non-Javadoc) * @see javax.jmdns.JmmDNS#getNames() */ @Override public String[] getNames() { Set<String> result = new HashSet<String>(); for (JmDNS mDNS : this.getDNS()) { result.add(mDNS.getName()); } return result.toArray(new String[result.size()]); } /* * (non-Javadoc) * @see javax.jmdns.JmmDNS#getHostNames() */ @Override public String[] getHostNames() { Set<String> result = new HashSet<String>(); for (JmDNS mDNS : this.getDNS()) { result.add(mDNS.getHostName()); } return result.toArray(new String[result.size()]); } /* * (non-Javadoc) * @see javax.jmdns.JmmDNS#getInetAddresses() */ @Override public InetAddress[] getInetAddresses() throws IOException { Set<InetAddress> result = new HashSet<InetAddress>(); for (JmDNS mDNS : this.getDNS()) { result.add(mDNS.getInetAddress()); } return result.toArray(new InetAddress[result.size()]); } /* * (non-Javadoc) * @see javax.jmdns.JmmDNS#getDNS() */ @Override public JmDNS[] getDNS() { synchronized (_knownMDNS) { return _knownMDNS.values().toArray(new JmDNS[_knownMDNS.size()]); } } /* * (non-Javadoc) * @see javax.jmdns.JmmDNS#getInterfaces() */ @Override @Deprecated public InetAddress[] getInterfaces() throws IOException { Set<InetAddress> result = new HashSet<InetAddress>(); for (JmDNS mDNS : this.getDNS()) { result.add(mDNS.getInterface()); } return result.toArray(new InetAddress[result.size()]); } /* * (non-Javadoc) * @see javax.jmdns.JmmDNS#getServiceInfos(java.lang.String, java.lang.String) */ @Override public ServiceInfo[] getServiceInfos(String type, String name) { return this.getServiceInfos(type, name, false, DNSConstants.SERVICE_INFO_TIMEOUT); } /* * (non-Javadoc) * @see javax.jmdns.JmmDNS#getServiceInfos(java.lang.String, java.lang.String, long) */ @Override public ServiceInfo[] getServiceInfos(String type, String name, long timeout) { return this.getServiceInfos(type, name, false, timeout); } /* * (non-Javadoc) * @see javax.jmdns.JmmDNS#getServiceInfos(java.lang.String, java.lang.String, boolean) */ @Override public ServiceInfo[] getServiceInfos(String type, String name, boolean persistent) { return this.getServiceInfos(type, name, persistent, DNSConstants.SERVICE_INFO_TIMEOUT); } /* * (non-Javadoc) * @see javax.jmdns.JmmDNS#getServiceInfos(java.lang.String, java.lang.String, boolean, long) */ @Override public ServiceInfo[] getServiceInfos(final String type, final String name, final boolean persistent, final long timeout) { // We need to run this in parallel to respect the timeout. final JmDNS[] dnsArray = this.getDNS(); final Set<ServiceInfo> result = new HashSet<ServiceInfo>(dnsArray.length); if (dnsArray.length > 0) { List<Callable<ServiceInfo>> tasks = new ArrayList<Callable<ServiceInfo>>(dnsArray.length); for (final JmDNS mDNS : dnsArray) { tasks.add(new Callable<ServiceInfo>() { @Override public ServiceInfo call() throws Exception { return mDNS.getServiceInfo(type, name, persistent, timeout); } }); } ExecutorService executor = Executors.newFixedThreadPool(tasks.size(), new NamedThreadFactory("JmmDNS.getServiceInfos")); try { List<Future<ServiceInfo>> results = Collections.emptyList(); try { results = executor.invokeAll(tasks, timeout + 100, TimeUnit.MILLISECONDS); } catch (InterruptedException exception) { logger.log(Level.FINE, "Interrupted ", exception); Thread.currentThread().interrupt(); // Will terminate next loop early. } for (Future<ServiceInfo> future : results) { if (future.isCancelled()) { continue; } try { ServiceInfo info = future.get(); if (info != null) { result.add(info); } } catch (InterruptedException exception) { logger.log(Level.FINE, "Interrupted ", exception); Thread.currentThread().interrupt(); } catch (ExecutionException exception) { logger.log(Level.WARNING, "Exception ", exception); } } } finally { executor.shutdown(); } } return result.toArray(new ServiceInfo[result.size()]); } /* * (non-Javadoc) * @see javax.jmdns.JmmDNS#requestServiceInfo(java.lang.String, java.lang.String) */ @Override public void requestServiceInfo(String type, String name) { this.requestServiceInfo(type, name, false, DNSConstants.SERVICE_INFO_TIMEOUT); } /* * (non-Javadoc) * @see javax.jmdns.JmmDNS#requestServiceInfo(java.lang.String, java.lang.String, boolean) */ @Override public void requestServiceInfo(String type, String name, boolean persistent) { this.requestServiceInfo(type, name, persistent, DNSConstants.SERVICE_INFO_TIMEOUT); } /* * (non-Javadoc) * @see javax.jmdns.JmmDNS#requestServiceInfo(java.lang.String, java.lang.String, long) */ @Override public void requestServiceInfo(String type, String name, long timeout) { this.requestServiceInfo(type, name, false, timeout); } /* * (non-Javadoc) * @see javax.jmdns.JmmDNS#requestServiceInfo(java.lang.String, java.lang.String, boolean, long) */ @Override public void requestServiceInfo(final String type, final String name, final boolean persistent, final long timeout) { // We need to run this in parallel to respect the timeout. for (final JmDNS mDNS : this.getDNS()) { _jmDNSExecutor.submit(new Runnable() { /** * {@inheritDoc} */ @Override public void run() { mDNS.requestServiceInfo(type, name, persistent, timeout); } }); } } /* * (non-Javadoc) * @see javax.jmdns.JmmDNS#addServiceTypeListener(javax.jmdns.ServiceTypeListener) */ @Override public void addServiceTypeListener(ServiceTypeListener listener) throws IOException { _typeListeners.add(listener); for (JmDNS mDNS : this.getDNS()) { mDNS.addServiceTypeListener(listener); } } /* * (non-Javadoc) * @see javax.jmdns.JmmDNS#removeServiceTypeListener(javax.jmdns.ServiceTypeListener) */ @Override public void removeServiceTypeListener(ServiceTypeListener listener) { _typeListeners.remove(listener); for (JmDNS mDNS : this.getDNS()) { mDNS.removeServiceTypeListener(listener); } } /* * (non-Javadoc) * @see javax.jmdns.JmmDNS#addServiceListener(java.lang.String, javax.jmdns.ServiceListener) */ @Override public void addServiceListener(String type, ServiceListener listener) { final String loType = type.toLowerCase(); List<ServiceListener> list = _serviceListeners.get(loType); if (list == null) { _serviceListeners.putIfAbsent(loType, new LinkedList<ServiceListener>()); list = _serviceListeners.get(loType); } if (list != null) { synchronized (list) { if (!list.contains(listener)) { list.add(listener); } } } for (JmDNS mDNS : this.getDNS()) { mDNS.addServiceListener(type, listener); } } /* * (non-Javadoc) * @see javax.jmdns.JmmDNS#removeServiceListener(java.lang.String, javax.jmdns.ServiceListener) */ @Override public void removeServiceListener(String type, ServiceListener listener) { String loType = type.toLowerCase(); List<ServiceListener> list = _serviceListeners.get(loType); if (list != null) { synchronized (list) { list.remove(listener); if (list.isEmpty()) { _serviceListeners.remove(loType, list); } } } for (JmDNS mDNS : this.getDNS()) { mDNS.removeServiceListener(type, listener); } } /* * (non-Javadoc) * @see javax.jmdns.impl.ServiceInfoImpl.Delegate#textValueUpdated(javax.jmdns.ServiceInfo, byte[]) */ @Override public void textValueUpdated(ServiceInfo target, byte[] value) { // We need to get the list out of the synchronized block to prevent dead locks final JmDNS[] dnsArray = this.getDNS(); synchronized (_services) { for (JmDNS mDNS : dnsArray) { ServiceInfo info = ((JmDNSImpl) mDNS).getServices().get(target.getQualifiedName()); if (info != null) { info.setText(value); } else { logger.warning("We have a mDNS that does not know about the service info being updated."); } } } } /* * (non-Javadoc) * @see javax.jmdns.JmmDNS#registerService(javax.jmdns.ServiceInfo) */ @Override public void registerService(ServiceInfo info) throws IOException { // We need to get the list out of the synchronized block to prevent dead locks final JmDNS[] dnsArray = this.getDNS(); // This is really complex. We need to clone the service info for each DNS but then we loose the ability to update it. synchronized (_services) { for (JmDNS mDNS : dnsArray) { mDNS.registerService(info.clone()); } ((ServiceInfoImpl) info).setDelegate(this); _services.put(info.getQualifiedName(), info); } } /* * (non-Javadoc) * @see javax.jmdns.JmmDNS#unregisterService(javax.jmdns.ServiceInfo) */ @Override public void unregisterService(ServiceInfo info) { // We need to get the list out of the synchronized block to prevent dead locks final JmDNS[] dnsArray = this.getDNS(); synchronized (_services) { _services.remove(info.getQualifiedName()); for (JmDNS mDNS : dnsArray) { mDNS.unregisterService(info); } ((ServiceInfoImpl) info).setDelegate(null); } } /* * (non-Javadoc) * @see javax.jmdns.JmmDNS#unregisterAllServices() */ @Override public void unregisterAllServices() { // We need to get the list out of the synchronized block to prevent dead locks final JmDNS[] dnsArray = this.getDNS(); synchronized (_services) { _services.clear(); for (JmDNS mDNS : dnsArray) { mDNS.unregisterAllServices(); } } } /* * (non-Javadoc) * @see javax.jmdns.JmmDNS#registerServiceType(java.lang.String) */ @Override public void registerServiceType(String type) { _serviceTypes.add(type); for (JmDNS mDNS : this.getDNS()) { mDNS.registerServiceType(type); } } /* * (non-Javadoc) * @see javax.jmdns.JmmDNS#list(java.lang.String) */ @Override public ServiceInfo[] list(String type) { return this.list(type, DNSConstants.SERVICE_INFO_TIMEOUT); } /* * (non-Javadoc) * @see javax.jmdns.JmmDNS#list(java.lang.String, long) */ @Override public ServiceInfo[] list(final String type, final long timeout) { final JmDNS[] dnsArray = this.getDNS(); // We need to run this in parallel to respect the timeout. final Set<ServiceInfo> result = new HashSet<ServiceInfo>(dnsArray.length * 5); if (dnsArray.length > 0) { List<Callable<List<ServiceInfo>>> tasks = new ArrayList<Callable<List<ServiceInfo>>>(dnsArray.length); for (final JmDNS mDNS : dnsArray) { tasks.add(new Callable<List<ServiceInfo>>() { @Override public List<ServiceInfo> call() throws Exception { return Arrays.asList(mDNS.list(type, timeout)); } }); } ExecutorService executor = Executors.newFixedThreadPool(tasks.size(), new NamedThreadFactory("JmmDNS.list")); try { List<Future<List<ServiceInfo>>> results = Collections.emptyList(); try { results = executor.invokeAll(tasks, timeout + 100, TimeUnit.MILLISECONDS); } catch (InterruptedException exception) { logger.log(Level.FINE, "Interrupted ", exception); Thread.currentThread().interrupt(); // Will terminate next loop early. } for (Future<List<ServiceInfo>> future : results) { if (future.isCancelled()) { continue; } try { result.addAll(future.get()); } catch (InterruptedException exception) { logger.log(Level.FINE, "Interrupted ", exception); Thread.currentThread().interrupt(); } catch (ExecutionException exception) { logger.log(Level.WARNING, "Exception ", exception); } } } finally { executor.shutdown(); } } return result.toArray(new ServiceInfo[result.size()]); } /* * (non-Javadoc) * @see javax.jmdns.JmmDNS#listBySubtype(java.lang.String) */ @Override public Map<String, ServiceInfo[]> listBySubtype(String type) { return this.listBySubtype(type, DNSConstants.SERVICE_INFO_TIMEOUT); } /* * (non-Javadoc) * @see javax.jmdns.JmmDNS#listBySubtype(java.lang.String, long) */ @Override public Map<String, ServiceInfo[]> listBySubtype(final String type, final long timeout) { Map<String, List<ServiceInfo>> map = new HashMap<String, List<ServiceInfo>>(5); for (ServiceInfo info : this.list(type, timeout)) { String subtype = info.getSubtype(); if (!map.containsKey(subtype)) { map.put(subtype, new ArrayList<ServiceInfo>(10)); } map.get(subtype).add(info); } Map<String, ServiceInfo[]> result = new HashMap<String, ServiceInfo[]>(map.size()); for (String subtype : map.keySet()) { List<ServiceInfo> infoForSubType = map.get(subtype); result.put(subtype, infoForSubType.toArray(new ServiceInfo[infoForSubType.size()])); } return result; } /* * (non-Javadoc) * @see javax.jmdns.JmmDNS#addNetworkTopologyListener(javax.jmdns.NetworkTopologyListener) */ @Override public void addNetworkTopologyListener(NetworkTopologyListener listener) { _networkListeners.add(listener); } /* * (non-Javadoc) * @see javax.jmdns.JmmDNS#removeNetworkTopologyListener(javax.jmdns.NetworkTopologyListener) */ @Override public void removeNetworkTopologyListener(NetworkTopologyListener listener) { _networkListeners.remove(listener); } /* * (non-Javadoc) * @see javax.jmdns.JmmDNS#networkListeners() */ @Override public NetworkTopologyListener[] networkListeners() { return _networkListeners.toArray(new NetworkTopologyListener[_networkListeners.size()]); } /* * (non-Javadoc) * @see javax.jmdns.NetworkTopologyListener#inetAddressAdded(javax.jmdns.NetworkTopologyEvent) */ @Override public void inetAddressAdded(NetworkTopologyEvent event) { InetAddress address = event.getInetAddress(); try { if (!_knownMDNS.containsKey(address)) { synchronized (_knownMDNS) { if (!_knownMDNS.containsKey(address)) { final JmDNS dns = JmDNS.create(address); if (_knownMDNS.putIfAbsent(address, dns) == null) { // We need to register the services and listeners with the new JmDNS final Collection<String> types = _serviceTypes; final Collection<ServiceInfo> infos = _services.values(); final Collection<ServiceTypeListener> typeListeners = _typeListeners; final Map<String, List<ServiceListener>> serviceListeners = _serviceListeners; _jmDNSExecutor.submit(new Runnable() { /** * {@inheritDoc} */ @Override public void run() { // Register Types for (String type : types) { dns.registerServiceType(type); } // Register services for (ServiceInfo info : infos) { try { dns.registerService(info.clone()); } catch (IOException exception) { // logger.warning("Unexpected unhandled exception: " + exception); } } // Add ServiceType Listeners for (ServiceTypeListener listener : typeListeners) { try { dns.addServiceTypeListener(listener); } catch (IOException exception) { // logger.warning("Unexpected unhandled exception: " + exception); } } // Add Service Listeners for (String type : serviceListeners.keySet()) { List<ServiceListener> listeners = serviceListeners.get(type); synchronized (listeners) { for (ServiceListener listener : listeners) { dns.addServiceListener(type, listener); } } } } }); final NetworkTopologyEvent jmdnsEvent = new NetworkTopologyEventImpl(dns, address); for (final NetworkTopologyListener listener : this.networkListeners()) { _listenerExecutor.submit(new Runnable() { /** * {@inheritDoc} */ @Override public void run() { listener.inetAddressAdded(jmdnsEvent); } }); } } else { dns.close(); } } } } } catch (Exception e) { logger.warning("Unexpected unhandled exception: " + e); } } /* * (non-Javadoc) * @see javax.jmdns.NetworkTopologyListener#inetAddressRemoved(javax.jmdns.NetworkTopologyEvent) */ @Override public void inetAddressRemoved(NetworkTopologyEvent event) { InetAddress address = event.getInetAddress(); try { if (_knownMDNS.containsKey(address)) { synchronized (_knownMDNS) { if (_knownMDNS.containsKey(address)) { JmDNS mDNS = _knownMDNS.remove(address); mDNS.close(); final NetworkTopologyEvent jmdnsEvent = new NetworkTopologyEventImpl(mDNS, address); for (final NetworkTopologyListener listener : this.networkListeners()) { _listenerExecutor.submit(new Runnable() { /** * {@inheritDoc} */ @Override public void run() { listener.inetAddressRemoved(jmdnsEvent); } }); } } } } } catch (Exception e) { logger.warning("Unexpected unhandled exception: " + e); } } /** * Checks the network state.<br/> * If the network change, this class will reconfigure the list of DNS do adapt to the new configuration. */ static class NetworkChecker extends TimerTask { private static Logger logger1 = Logger.getLogger(NetworkChecker.class.getName()); private final NetworkTopologyListener _mmDNS; private final NetworkTopologyDiscovery _topology; private Set<InetAddress> _knownAddresses; public NetworkChecker(NetworkTopologyListener mmDNS, NetworkTopologyDiscovery topology) { super(); this._mmDNS = mmDNS; this._topology = topology; _knownAddresses = Collections.synchronizedSet(new HashSet<InetAddress>()); } public void start(Timer timer) { // Run once up-front otherwise the list of servers will only appear after a delay. run(); timer.schedule(this, DNSConstants.NETWORK_CHECK_INTERVAL, DNSConstants.NETWORK_CHECK_INTERVAL); } /** * {@inheritDoc} */ @Override public void run() { try { InetAddress[] curentAddresses = _topology.getInetAddresses(); Set<InetAddress> current = new HashSet<InetAddress>(curentAddresses.length); for (InetAddress address : curentAddresses) { current.add(address); if (!_knownAddresses.contains(address)) { final NetworkTopologyEvent event = new NetworkTopologyEventImpl(_mmDNS, address); _mmDNS.inetAddressAdded(event); } } for (InetAddress address : _knownAddresses) { if (!current.contains(address)) { final NetworkTopologyEvent event = new NetworkTopologyEventImpl(_mmDNS, address); _mmDNS.inetAddressRemoved(event); } } _knownAddresses = current; } catch (Exception e) { logger1.warning("Unexpected unhandled exception: " + e); } } } }
apache-2.0
akira-baruah/bazel
src/main/java/com/google/devtools/build/lib/skylarkbuildapi/test/AnalysisFailureApi.java
2229
// Copyright 2018 The Bazel Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.devtools.build.lib.skylarkbuildapi.test; import com.google.devtools.build.lib.cmdline.Label; import com.google.devtools.build.lib.skylarkinterface.SkylarkCallable; import com.google.devtools.build.lib.skylarkinterface.StarlarkBuiltin; import com.google.devtools.build.lib.syntax.StarlarkValue; /** * Encapsulates information about an analysis-phase error which would have occurred during a build. */ @StarlarkBuiltin( name = "AnalysisFailure", doc = "Encapsulates information about an analysis-phase error which would have occurred during " + "a build. In most builds, an analysis-phase error would result in a build failure " + "and the error description would be output to the console. However, if " + "<code>--allow_analysis_failure</code> is set, targets which would otherwise fail in " + "analysis will instead propagate an <code>AnalysisFailureInfo</code> object " + "containing one or more instances of this object.", documented = false) public interface AnalysisFailureApi extends StarlarkValue { @SkylarkCallable( name = "label", doc = "The label of the target that exhibited an analysis-phase error. This is the label " + "of the target responsible for construction of this object.", documented = false, structField = true) Label getLabel(); @SkylarkCallable( name = "message", doc = "A string representation of the analysis-phase error which occurred.", documented = false, structField = true) String getMessage(); }
apache-2.0
fugeritaetas/morozko-lib
java14-morozko/org.morozko.java.mod.daogen/src/org/morozko/java/mod/daogen/gen/config/types/SQLType.java
5974
/***************************************************************** <copyright> Morozko Java Library org.morozko.java.mod.daogen Copyright (c) 2006 Morozko All rights reserved. This program and the accompanying materials are made available under the terms of the Apache License v2.0 which accompanies this distribution, and is available at http://www.apache.org/licenses/ (txt version : http://www.apache.org/licenses/LICENSE-2.0.txt html version : http://www.apache.org/licenses/LICENSE-2.0.html) This product includes software developed at The Apache Software Foundation (http://www.apache.org/). </copyright> *****************************************************************/ /* * @(#)SQLType.java * * @project : org.morozko.java.mod.daogen * @package : org.morozko.java.mod.daogen.gen.config.types * @creation : 13-apr-2006 */ package org.morozko.java.mod.daogen.gen.config.types; import java.sql.Types; import java.util.HashMap; import java.util.Map; /** * <p></p> * * @author mfranci * */ public class SQLType { public static final SQLType DAOID = new SQLType( "id", Integer.MIN_VALUE ); public static final SQLType DAOIDNULLZERO = new SQLType( "idnz", Integer.MIN_VALUE+1 ); public static final SQLType DAOIDAUTO = new SQLType( "idauto", Integer.MIN_VALUE+2 ); public static final SQLType BIGINTEGER = new SQLType( "biginteger", Integer.MIN_VALUE+3 ); public static final SQLType BIGDECIMAL = new SQLType( "bigdecimal", Integer.MIN_VALUE+4 ); public static final SQLType NUMERIC = new SQLType( "numeric", Types.NUMERIC ); public static final SQLType BIGINT = new SQLType( "bigint", Types.BIGINT ); public static final SQLType INTEGER = new SQLType( "integer", Types.INTEGER ); public static final SQLType SMALLINT = new SQLType( "smallint", Types.SMALLINT ); public static final SQLType TINYINT = new SQLType( "tinyint", Types.TINYINT ); public static final SQLType DOUBLE = new SQLType( "double", Types.DOUBLE ); public static final SQLType DECIMAL = new SQLType( "double", Types.DECIMAL ); public static final SQLType FLOAT = new SQLType( "float", Types.FLOAT ); public static final SQLType DATE = new SQLType( "date", Types.DATE ); public static final SQLType TIME = new SQLType( "time", Types.TIME ); public static final SQLType TIMESTAMP = new SQLType( "timestamp", Types.TIMESTAMP ); public static final SQLType VARCHAR = new SQLType( "varchar", Types.VARCHAR ); public static final SQLType LONGVARCHAR = new SQLType( "varchar", Types.LONGVARCHAR ); public static final SQLType CHAR = new SQLType( "char", Types.CHAR ); public static final SQLType BOOLEAN = new SQLType( "boolean", Types.BOOLEAN ); public static final SQLType BIT = new SQLType( "bit", Types.BIT ); public static final SQLType BLOB = new SQLType( "blob", Types.BLOB ); public static final SQLType CLOB = new SQLType( "clob", Types.CLOB ); public static final SQLType LONGVARBINARY = new SQLType( "blob", Types.LONGVARBINARY ); private static void add( SQLType type, Map map1, Map map2 ) { map1.put( type.getTypeName(), type ); map2.put( type.getSqlType(), type ); } public static final Map KNOWN_TYPES_NAME = new HashMap(); public static final Map KNOWN_TYPES_SQL = new HashMap(); static { add( DAOID, KNOWN_TYPES_NAME, KNOWN_TYPES_SQL ); add( DAOIDAUTO, KNOWN_TYPES_NAME, KNOWN_TYPES_SQL ); add( DAOIDNULLZERO, KNOWN_TYPES_NAME, KNOWN_TYPES_SQL ); add( BIGDECIMAL, KNOWN_TYPES_NAME, KNOWN_TYPES_SQL ); add( BIGINTEGER, KNOWN_TYPES_NAME, KNOWN_TYPES_SQL ); add( INTEGER, KNOWN_TYPES_NAME, KNOWN_TYPES_SQL ); add( BIGINT, KNOWN_TYPES_NAME, KNOWN_TYPES_SQL ); add( SMALLINT, KNOWN_TYPES_NAME, KNOWN_TYPES_SQL ); add( TINYINT, KNOWN_TYPES_NAME, KNOWN_TYPES_SQL ); add( DOUBLE, KNOWN_TYPES_NAME, KNOWN_TYPES_SQL ); add( DECIMAL, KNOWN_TYPES_NAME, KNOWN_TYPES_SQL ); add( FLOAT, KNOWN_TYPES_NAME, KNOWN_TYPES_SQL ); add( DATE, KNOWN_TYPES_NAME, KNOWN_TYPES_SQL ); add( TIME, KNOWN_TYPES_NAME, KNOWN_TYPES_SQL ); add( TIMESTAMP, KNOWN_TYPES_NAME, KNOWN_TYPES_SQL ); add( VARCHAR, KNOWN_TYPES_NAME, KNOWN_TYPES_SQL ); add( LONGVARCHAR, KNOWN_TYPES_NAME, KNOWN_TYPES_SQL ); add( BOOLEAN, KNOWN_TYPES_NAME, KNOWN_TYPES_SQL ); add( BIT, KNOWN_TYPES_NAME, KNOWN_TYPES_SQL ); add( CHAR, KNOWN_TYPES_NAME, KNOWN_TYPES_SQL ); add( NUMERIC, KNOWN_TYPES_NAME, KNOWN_TYPES_SQL ); add( BLOB, KNOWN_TYPES_NAME, KNOWN_TYPES_SQL ); add( LONGVARBINARY, KNOWN_TYPES_NAME, KNOWN_TYPES_SQL ); add( CLOB, KNOWN_TYPES_NAME, KNOWN_TYPES_SQL ); } private String typeName; private Integer sqlType; /** * @param typeName * @param sqlType */ public SQLType(String typeName, int sqlType) { super(); this.typeName = typeName; this.sqlType = new Integer( sqlType ); } /** * @return Restituisce il valore di sqlType. */ public Integer getSqlType() { return sqlType; } /** * @param sqlType il valore di sqlType da impostare. */ public void setSqlType(Integer sqlType) { this.sqlType = sqlType; } /** * @return Restituisce il valore di typeName. */ public String getTypeName() { return typeName; } /** * @param typeName il valore di typeName da impostare. */ public void setTypeName(String typeName) { this.typeName = typeName; } /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ public boolean equals(Object obj) { boolean eq = false; if (obj != null && obj instanceof SQLType) { SQLType s = (SQLType)obj; eq = s.getTypeName().equals( this.getTypeName() ) && s.getSqlType().equals( this.getSqlType() ); } return eq; } /* (non-Javadoc) * @see java.lang.Object#hashCode() */ public int hashCode() { return this.sqlType.intValue(); } public String toString() { return this.getClass().getName()+"["+this.getSqlType()+"]"; } }
apache-2.0
FINRAOS/herd
herd-code/herd-model-api/src/test/java/org/finra/herd/model/api/adapters/RegistrationDateAdapterTest.java
4753
/* * Copyright 2015 herd contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.finra.herd.model.api.adapters; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import javax.xml.datatype.DatatypeFactory; import javax.xml.datatype.XMLGregorianCalendar; import org.junit.Test; public class RegistrationDateAdapterTest { @Test public void unmarshalAllAllowedFormatsTest() throws Exception { RegistrationDateAdapter adapter = new RegistrationDateAdapter(); // test for pattern: "yyyy-MM-dd" XMLGregorianCalendar calendar = adapter.unmarshal("2020-02-02"); compareCalendarWithExpectedValues(calendar, 2020, 2, 2, 0, 0, 0); // test for pattern: "yyyy-MM-dd'T'HH:mm" calendar = adapter.unmarshal("2015-12-25T00:01"); compareCalendarWithExpectedValues(calendar, 2015, 12, 25, 0, 1, 0); // test for pattern: "yyyy-MM-dd'T'HH:mmZ" calendar = adapter.unmarshal("2015-12-25T00:01+04:00"); compareCalendarWithExpectedValues(calendar, 2015, 12, 24, 20, 1, 0); // test for pattern: "yyyy-MM-dd'T'HH:mm:ss" calendar = adapter.unmarshal("2018-02-03T10:00:02"); compareCalendarWithExpectedValues(calendar, 2018, 2, 3, 10, 0, 2); // test for pattern: "yyyy-MM-dd'T'HH:mm:ssZ" calendar = adapter.unmarshal("2018-02-03T10:00:02+04:00"); compareCalendarWithExpectedValues(calendar, 2018, 2, 3, 6, 0, 2); // test for pattern: "yyyy-MM-dd HH:mm:ssZ" calendar = adapter.unmarshal("2018-02-03 10:00:02+05:30"); compareCalendarWithExpectedValues(calendar, 2018, 2, 3, 4, 30, 2); // test for pattern: "yyyy-MM-dd HH:mm:ss" calendar = adapter.unmarshal("2018-03-03 00:20:02"); compareCalendarWithExpectedValues(calendar, 2018, 3, 3, 0, 20, 2); } private void compareCalendarWithExpectedValues(XMLGregorianCalendar calendar, int year, int month, int day, int hour, int minute, int second) { assertEquals(calendar.getYear(), year); assertEquals(calendar.getMonth(), month); assertEquals(calendar.getDay(), day); assertEquals(calendar.getHour(), hour); assertEquals(calendar.getMinute(), minute); assertEquals(calendar.getSecond(), second); // timezone is internally set to UTC in the unmarshaller assertEquals(calendar.getTimezone(), 0); } @Test public void unmarshalIllegalFormatTest() { RegistrationDateAdapter adapter = new RegistrationDateAdapter(); try { adapter.unmarshal("2020-02"); } catch (Exception e) { assertTrue(e instanceof IllegalArgumentException); assertTrue(e.getMessage().contains("Valid date or date and time format must be used when specifying values for start/end registration dates.")); } try { adapter.unmarshal("2020-02-02T12:02AM"); } catch (Exception e) { assertTrue(e instanceof IllegalArgumentException); assertTrue(e.getMessage().contains("Valid date or date and time format must be used when specifying values for start/end registration dates.")); } } /** * An already initialized {@link XMLGregorianCalendar} instance is used by the marshaller so a lot of testing is not needed. */ @Test public void marshalTest() throws Exception { // Generate a new XMLGregorianCalendar instance initialized at current time XMLGregorianCalendar calendar = DatatypeFactory.newInstance().newXMLGregorianCalendar(); calendar.setYear(2020); calendar.setMonth(2); calendar.setDay(1); calendar.setHour(2); calendar.setMinute(59); calendar.setSecond(0); // Get its string representation String calendarStringRepresentation = calendar.toGregorianCalendar().toInstant().toString(); // Initialize the object under test RegistrationDateAdapter adapter = new RegistrationDateAdapter(); // marshal and compare assertEquals(calendarStringRepresentation, adapter.marshal(calendar)); } }
apache-2.0
Abner3/java
Semester I/Satpix/src/Satpix.java
1930
import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.Scanner; /** * */ /** * @author AStout * */ public class Satpix { static int sizeOfLargestPasture = 0; static int length, width; public static void main (String[] args) throws IOException { boolean[][] booleanArr = fileToBoolArray(); //Stuff for you to code! PrintWriter out = new PrintWriter("satpix.out"); out.println(sizeOfLargestPasture); out.close(); } //buffered reader for char and scanner for strings //file reader if using buffered reader fileReader(inFile) private static boolean[][] fileToBoolArray() throws FileNotFoundException { // Helper method which converts the file into a 2D // array of booleans //scan in the ints for length and width Scanner textReader = new Scanner(new File("satpix.in")); //where's file? length = textReader.nextInt(); width = textReader.nextInt(); //buffer read in satpix char map } //base case is then there is false boolea ns around the true booleans (pasture) //or if false boolean is where method is called private static int recursivelyMeasureAndMarkPasture(int row, int col, boolean[][] arr) { // Recursive method which uses the flood-fill algorithm to // count the size of a single pasture and "mark" it so it is not double-counted if(arr[row-1][col]) { recursivelyMeasureAndMarkPasture(row-1, col, arr); } if(arr[row+1][col]) { recursivelyMeasureAndMarkPasture(row+1, col, arr); } if(arr[row][col-1]) { recursivelyMeasureAndMarkPasture(row, col-1, arr); } if(arr[row][col+1]) { recursivelyMeasureAndMarkPasture(row, col+1, arr); } //base cases if(arr[row][col]) { return sizeOfLargestPasture++; } if(!arr[row][col]) { return sizeOfLargestPasture; } } }
apache-2.0
bmelnychuk/outlay
outlay/app/src/main/java/app/outlay/mvp/view/EnterExpenseView.java
498
package app.outlay.mvp.view; import com.hannesdorfmann.mosby.mvp.MvpView; import app.outlay.domain.model.Category; import app.outlay.domain.model.Expense; import java.math.BigDecimal; import java.util.List; /** * Created by bmelnychuk on 10/25/16. */ public interface EnterExpenseView extends MvpView { void showCategories(List<Category> categoryList); void showTimeline(List<Expense> expenses); void setAmount(BigDecimal amount); void alertExpenseSuccess(Expense expense); }
apache-2.0
neykov/incubator-brooklyn
software/base/src/main/java/brooklyn/entity/java/JmxmpSslSupport.java
5408
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package brooklyn.entity.java; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.security.KeyPair; import java.security.KeyStore; import java.security.PrivateKey; import java.security.cert.Certificate; import java.security.cert.X509Certificate; import brooklyn.util.collections.MutableMap.Builder; import brooklyn.util.crypto.FluentKeySigner; import brooklyn.util.crypto.SecureKeys; import brooklyn.util.exceptions.Exceptions; import brooklyn.util.jmx.jmxmp.JmxmpAgent; import brooklyn.util.net.Urls; import com.google.common.base.Preconditions; public class JmxmpSslSupport { final static String BROOKLYN_VERSION = "0.7.0-SNAPSHOT"; // BROOKLYN_VERSION (updated by script) private final JmxSupport jmxSupport; private KeyStore agentTrustStore; private KeyStore agentKeyStore; public JmxmpSslSupport(JmxSupport jmxSupport) { this.jmxSupport = Preconditions.checkNotNull(jmxSupport); } public String getJmxSslKeyStoreFilePath() { return Urls.mergePaths(jmxSupport.getRunDir(), "jmx-keystore"); } public String getJmxSslTrustStoreFilePath() { return Urls.mergePaths(jmxSupport.getRunDir(), "jmx-truststore"); } public void applyAgentJmxJavaSystemProperties(Builder<String, Object> result) { result. put(JmxmpAgent.USE_SSL_PROPERTY, true). put(JmxmpAgent.AUTHENTICATE_CLIENTS_PROPERTY, true). // the option below wants a jmxremote.password file; we use certs (above) to authenticate put("com.sun.management.jmxremote.authenticate", false); result. put(JmxmpAgent.JMXMP_KEYSTORE_FILE_PROPERTY, getJmxSslKeyStoreFilePath()). put(JmxmpAgent.JMXMP_TRUSTSTORE_FILE_PROPERTY, getJmxSslTrustStoreFilePath()); } public FluentKeySigner getBrooklynRootSigner() { // TODO use brooklyn root CA keys etc return new FluentKeySigner("brooklyn-root"); } /** builds remote keystores, stores config keys/certs, and copies necessary files across */ public void install() { try { // build truststore and keystore FluentKeySigner signer = getBrooklynRootSigner(); KeyPair jmxAgentKey = SecureKeys.newKeyPair(); X509Certificate jmxAgentCert = signer.newCertificateFor("jmxmp-agent", jmxAgentKey); agentKeyStore = SecureKeys.newKeyStore(); agentKeyStore.setKeyEntry("jmxmp-agent", jmxAgentKey.getPrivate(), // TODO jmx.ssl.agent.keyPassword "".toCharArray(), new Certificate[] { jmxAgentCert }); ByteArrayOutputStream agentKeyStoreBytes = new ByteArrayOutputStream(); agentKeyStore.store(agentKeyStoreBytes, // TODO jmx.ssl.agent.keyStorePassword "".toCharArray()); agentTrustStore = SecureKeys.newKeyStore(); agentTrustStore.setCertificateEntry("brooklyn", getJmxAccessCert()); ByteArrayOutputStream agentTrustStoreBytes = new ByteArrayOutputStream(); agentTrustStore.store(agentTrustStoreBytes, "".toCharArray()); // install the truststore and keystore jmxSupport.getMachine().get().copyTo(new ByteArrayInputStream(agentKeyStoreBytes.toByteArray()), getJmxSslKeyStoreFilePath()); jmxSupport.getMachine().get().copyTo(new ByteArrayInputStream(agentTrustStoreBytes.toByteArray()), getJmxSslTrustStoreFilePath()); // and rely on JmxSupport to install the agent } catch (Exception e) { throw Exceptions.propagate(e); } } public synchronized Certificate getJmxAccessCert() { Certificate cert = jmxSupport.getConfig(UsesJmx.JMX_SSL_ACCESS_CERT); if (cert!=null) return cert; // TODO load from keyStoreUrl KeyPair jmxAccessKey = SecureKeys.newKeyPair(); X509Certificate jmxAccessCert = getBrooklynRootSigner().newCertificateFor("brooklyn-jmx-access", jmxAccessKey); jmxSupport.setConfig(UsesJmx.JMX_SSL_ACCESS_CERT, jmxAccessCert); jmxSupport.setConfig(UsesJmx.JMX_SSL_ACCESS_KEY, jmxAccessKey.getPrivate()); return jmxAccessCert; } public synchronized PrivateKey getJmxAccessKey() { PrivateKey key = jmxSupport.getConfig(UsesJmx.JMX_SSL_ACCESS_KEY); if (key!=null) return key; getJmxAccessCert(); return jmxSupport.getConfig(UsesJmx.JMX_SSL_ACCESS_KEY); } }
apache-2.0
dasomel/egovframework
common-component/v3.8.0/src/main/java/egovframework/com/sym/log/plg/service/EgovPrivacyLogAspect.java
5150
package egovframework.com.sym.log.plg.service; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import java.util.Map; import egovframework.com.cmm.LoginVO; import egovframework.com.cmm.util.EgovHttpRequestHelper; import egovframework.com.cmm.util.EgovUserDetailsHelper; import javax.annotation.Resource; import org.aspectj.lang.JoinPoint; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @Class Name : EgovPrivacyLogAspect.java * @Description : ๊ฐœ์ธ์ •๋ณด ์กฐํšŒ ์ด๋ ฅ ๊ด€๋ฆฌ๋ฅผ ์œ„ํ•œ Advice * @Modification Information * * ์ˆ˜์ •์ผ ์ˆ˜์ •์ž ์ˆ˜์ •๋‚ด์šฉ * ------- ------- ------------------- * 2014.09.11 ํ‘œ์ค€ํ”„๋ ˆ์ž„์›Œํฌ ์ตœ์ดˆ์ƒ์„ฑ * @author Vincent Han * @since 2014.09.11 * @version 3.5 */ public class EgovPrivacyLogAspect { private static final Logger LOGGER = LoggerFactory.getLogger(EgovPrivacyLogAspect.class); /** List ๊ธฐ๋ก ์‹œ ์ตœ๋Œ€ ๊ธฐ๋ก ์ˆ˜ */ private int maxListCount = 10; // defalut : 10 /** ๊ธฐ๋ก ๋Œ€์ƒ ๊ฐœ์ธ์ •๋ณด ํ•ญ๋ชฉ */ private Map<String, String> target = null; public void setMaxListCount(int maxListCount) { this.maxListCount = maxListCount; } public void setTarget(Map<String, String> target) { this.target = target; } @Resource(name="egovPrivacyLogService") private EgovPrivacyLogService privacyLogService; public void insertLog(JoinPoint joinPoint, Object returnVal) throws Throwable { String className = joinPoint.getTarget().getClass().getCanonicalName(); String methodName = joinPoint.getSignature().getName(); String serviceName = className + "." + methodName; if (!EgovHttpRequestHelper.isInHttpRequest()) { LOGGER.info("{} service called, but it isn't in HTTP request...", serviceName); return; } if (returnVal instanceof List) { // List์ด๋ฉฐ ๊ฐœ๋ณ„ ๊ธฐ๋ก int count = 0; for (Object item : (List<?>)returnVal) { List<String> list = null; if (item instanceof Map) { list = getItemValues((Map<?,?>)item, serviceName); } else { // general VO list = getItemValues(item, serviceName); } if (list.size() > 0) { privacyLogService.innerInsertPrivacyLog(getPrivacyLogFromItemList(list, serviceName)); if (++count >= maxListCount) { // ์ตœ๋Œ€ ๊ธฐ๋ก ์ˆ˜ ์ฒ˜๋ฆฌ LOGGER.info("Max List count reached (skip next list) : maxListCount = {}, target = {}", maxListCount, serviceName); break; } } } } else if (returnVal instanceof Map) { List<String> list = getItemValues((Map<?,?>)returnVal, serviceName); if (list.size() > 0) { privacyLogService.innerInsertPrivacyLog(getPrivacyLogFromItemList(list, serviceName)); } } else { // general VO List<String> list = getItemValues(returnVal, serviceName); if (list.size() > 0) { privacyLogService.innerInsertPrivacyLog(getPrivacyLogFromItemList(list, serviceName)); } } } protected List<String> getItemValues(Map<?,?> data, String serviceName) { List<String> list = new ArrayList<String>(); for (String key : target.keySet()) { if (data.containsKey(key) && data.get(key) != null && ! data.get(key).toString().trim().equals("")) { // ์กฐํšŒ๋œ ๋ฐ์ดํ„ฐ๊ฐ€ ์—†์œผ๋ฉด ์ƒ๋žต list.add(target.get(key)); LOGGER.debug("Service ('{}') : inquired data = {}", serviceName, key); } } return list; } protected List<String> getItemValues(Object data, String serviceName) { List<String> list = new ArrayList<String>(); for (String key : target.keySet()) { try { Method method = data.getClass().getMethod("get" + key.substring(0, 1).toUpperCase() + key.substring(1)); Object returned = method.invoke(data); if (returned != null && ! returned.toString().trim().equals("")) { list.add(target.get(key)); } } catch (SecurityException ignore) {//KISA ๋ณด์•ˆ์•ฝ์  ์กฐ์น˜ (2018-10-29, ์œค์ฐฝ์›) continue; } catch (Exception ignore) { continue; } LOGGER.debug("Service ('{}') : inquired data = {}", serviceName, key); } return list; } private PrivacyLog getPrivacyLogFromItemList(List<String> list, String serviceName) { PrivacyLog log = new PrivacyLog(); log.setServiceName(serviceName); log.setInquiryInfo(getStringFromItemList(list)); /* Authenticated */ Boolean isAuthenticated = EgovUserDetailsHelper.isAuthenticated(); if (isAuthenticated.booleanValue()) { LoginVO user = (LoginVO)EgovUserDetailsHelper.getAuthenticatedUser(); log.setRequesterId(user.getUniqId()); } log.setRequesterIp(EgovHttpRequestHelper.getRequestIp()); return log; } private String getStringFromItemList(List<String> list) { StringBuffer buffer = new StringBuffer(); for (String item : list) { if (buffer.length() != 0) { buffer.append(",").append(item); } else { buffer.append(item); } } return buffer.toString(); } }
apache-2.0
hortonworks/cloudbreak
integration-test/src/main/java/com/sequenceiq/it/cloudbreak/dto/util/SdxEventTestDto.java
2125
package com.sequenceiq.it.cloudbreak.dto.util; import java.util.List; import java.util.Optional; import javax.ws.rs.core.Response; import com.sequenceiq.cloudbreak.structuredevent.event.StructuredEventType; import com.sequenceiq.it.cloudbreak.Prototype; import com.sequenceiq.it.cloudbreak.context.TestContext; import com.sequenceiq.it.cloudbreak.dto.AbstractSdxTestDto; @Prototype public class SdxEventTestDto extends AbstractSdxTestDto<Object, Response, SdxEventTestDto> { private String environmentCrn; private List<StructuredEventType> types; private Integer page; private Integer size; private Optional<Integer> zippedResponseStatus; protected SdxEventTestDto(TestContext testContext) { super(null, testContext); } @Override public SdxEventTestDto valid() { setZippedResponseStatus(Optional.empty()); return this; } public SdxEventTestDto withEnvironmentCrn(String environmentCrn) { this.environmentCrn = environmentCrn; return this; } public SdxEventTestDto withTypes(List<StructuredEventType> types) { this.types = types; return this; } public SdxEventTestDto withPage(Integer page) { this.page = page; return this; } public SdxEventTestDto withSize(Integer size) { this.size = size; return this; } public String getEnvironmentCrn() { return environmentCrn; } public List<StructuredEventType> getTypes() { return types; } public Integer getPage() { return page; } public Integer getSize() { return size; } public Optional<Integer> getZippedResponseStatus() { return zippedResponseStatus; } public void setZippedResponseStatus(Optional<Integer> zippedResponseStatus) { this.zippedResponseStatus = zippedResponseStatus; } public String argsToString() { return String.format( "{EnvironmentCrn: \"%s\", Types: \"%s\", Page: \"%s\", Size: \"%s\"}", environmentCrn, types, page, size ); } }
apache-2.0
ConSol/sakuli
src/core/src/test/java/org/sakuli/services/forwarder/icinga2/Icinga2RestCientTest.java
2510
/* * Sakuli - Testing and Monitoring-Tool for Websites and common UIs. * * Copyright 2013 - 2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.sakuli.services.forwarder.icinga2; import org.glassfish.jersey.client.authentication.HttpAuthenticationFeature; import org.sakuli.loader.BeanLoader; import org.springframework.test.util.ReflectionTestUtils; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import javax.ws.rs.client.Client; import java.util.Set; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull; /** * @author tschneck * Date: 2/23/16 */ public class Icinga2RestCientTest extends AbstractIcinga2ForwarderBaseTest { private Icinga2RestCient testling; @BeforeMethod public void setUp() throws Exception { testling = BeanLoader.loadBean(Icinga2RestCient.class); } @Test public void testInitIcingaClient() throws Exception { // testling.initIcingaClient() will be called on context startup Set<Object> registeredObjects = ((Client) ReflectionTestUtils.getField(testling, "icingaClient")).getConfiguration().getInstances(); assertEquals(registeredObjects.size(), 2); registeredObjects.forEach(e -> { if (e instanceof HttpAuthenticationFeature) { assertNotNull(ReflectionTestUtils.getField(e, "basicCredentials")); return; } if (e instanceof Icinga2RestCient.ErrorResponseFilter) { return; } throw new RuntimeException("not epected class of registered Object of 'icingaClient'"); }); } @Test public void testGetTargetCheckResult() throws Exception { assertEquals(testling.getTargetCheckResult().getUri().toString(), "https://my-icinga-host:5665/v1/actions/process-check-result?service=sakuli-icinga-test!incinga-test-suite"); } }
apache-2.0
aws/aws-sdk-java
aws-java-sdk-logs/src/main/java/com/amazonaws/services/logs/model/transform/DescribeExportTasksRequestMarshaller.java
2984
/* * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.logs.model.transform; import javax.annotation.Generated; import com.amazonaws.SdkClientException; import com.amazonaws.services.logs.model.*; import com.amazonaws.protocol.*; import com.amazonaws.annotation.SdkInternalApi; /** * DescribeExportTasksRequestMarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") @SdkInternalApi public class DescribeExportTasksRequestMarshaller { private static final MarshallingInfo<String> TASKID_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("taskId").build(); private static final MarshallingInfo<String> STATUSCODE_BINDING = MarshallingInfo.builder(MarshallingType.STRING) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("statusCode").build(); private static final MarshallingInfo<String> NEXTTOKEN_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("nextToken").build(); private static final MarshallingInfo<Integer> LIMIT_BINDING = MarshallingInfo.builder(MarshallingType.INTEGER).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("limit").build(); private static final DescribeExportTasksRequestMarshaller instance = new DescribeExportTasksRequestMarshaller(); public static DescribeExportTasksRequestMarshaller getInstance() { return instance; } /** * Marshall the given parameter object. */ public void marshall(DescribeExportTasksRequest describeExportTasksRequest, ProtocolMarshaller protocolMarshaller) { if (describeExportTasksRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(describeExportTasksRequest.getTaskId(), TASKID_BINDING); protocolMarshaller.marshall(describeExportTasksRequest.getStatusCode(), STATUSCODE_BINDING); protocolMarshaller.marshall(describeExportTasksRequest.getNextToken(), NEXTTOKEN_BINDING); protocolMarshaller.marshall(describeExportTasksRequest.getLimit(), LIMIT_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
apache-2.0
Zixradoom/Spirit
src/main/java/com/s2d/spirit/SpiritFlag.java
297
package com.s2d.spirit; public enum SpiritFlag { STRING ( ( short ) 0x2 ), PING ( ( short ) 0x4 ), PONG ( ( short ) 0x8 ); private final int flagValue; private SpiritFlag ( short flag ) { flagValue = 0x0000FFFF & flag; } public int getFlagValue () { return flagValue; } }
apache-2.0