protected final void fastPathOrderedEmit(U value, boolean delayError, Disposable disposable) {
        final Observer<? super V> observer = downstream;
        final SimplePlainQueue<U> q = queue;

        if (wip.get() == 0 && wip.compareAndSet(0, 1)) {
            if (q.isEmpty()) {
                accept(observer, value);
                if (leave(-1) == 0) {
                    return;
                }
            } else {
                q.offer(value);
            }
        } else {
            q.offer(value);
            if (!enter()) {
                return;
            }
        }
        QueueDrainHelper.drainLoop(q, observer, delayError, disposable, this);
    }

protected final void fastPathOrderedEmit ( U value , boolean delayError , Disposable disposable ) { final Observer < ? super V > observer = downstream ; final SimplePlainQueue < U > q = queue ; if ( wip . get ( ) == 0 && wip . compareAndSet ( 0 , 1 ) ) { if ( q . isEmpty ( ) ) { accept ( observer , value ) ; if ( leave ( - 1 ) == 0 ) { return ; } } else { q . offer ( value ) ; } } else { q . offer ( value ) ; if ( ! enter ( ) ) { return ; } } QueueDrainHelper . drainLoop ( q , observer , delayError , disposable , this ) ; }

Makes sure the fast-path emits in order.
@param value the value to emit or queue up
@param delayError if true, errors are delayed until the source has terminated
@param disposable the resource to dispose if the drain terminates

Makes sure the fast - path emits in order .


@CheckReturnValue
    @SchedulerSupport(SchedulerSupport.NONE)
    public static <T> Observable<T> wrap(ObservableSource<T> source) {
        ObjectHelper.requireNonNull(source, "source is null");
        if (source instanceof Observable) {
            return RxJavaPlugins.onAssembly((Observable<T>)source);
        }
        return RxJavaPlugins.onAssembly(new ObservableFromUnsafeSource<T>(source));
    }

@
CheckReturnValue
@
SchedulerSupport
(
SchedulerSupport
.
)
public
static
<
T
>
Observable
<
T
>
wrap
(
ObservableSource
<
T
>
source
)
{
ObjectHelper
.
requireNonNull
(
source
,
"source is null"
)
;
if
(
source
instanceof
Observable
)
{
return
RxJavaPlugins
.
onAssembly
(
(
Observable
<
T
>
)
source
)
;
}
return
RxJavaPlugins
.
onAssembly
(
new
ObservableFromUnsafeSource
<
T
>
(
source
)
)
;
}

Wraps an ObservableSource into an Observable if not already an Observable.

Scheduler:

{@code wrap} does not operate by default on a particular {@link Scheduler}.

@param <T> the value type
@param source the source ObservableSource instance
@return the new Observable instance or the same as the source
@throws NullPointerException if source is null

Wraps an ObservableSource into an Observable if not already an Observable .


@CheckReturnValue
    @SchedulerSupport(SchedulerSupport.NONE)
    public final Observable<T> sorted(Comparator<? super T> sortFunction) {
        ObjectHelper.requireNonNull(sortFunction, "sortFunction is null");
        return toList().toObservable().map(Functions.listSorter(sortFunction)).flatMapIterable(Functions.<List<T>>identity());
    }

@
CheckReturnValue
@
SchedulerSupport
(
SchedulerSupport
.
)
public
final
Observable
<
T
>
sorted
(
Comparator
<
super
T
>
sortFunction
)
{
ObjectHelper
.
requireNonNull
(
sortFunction
,
"sortFunction is null"
)
;
return
toList
(
)
.
toObservable
(
)
.
map
(
Functions
.
listSorter
(
sortFunction
)
)
.
flatMapIterable
(
Functions
.
<
List
<
T
>
>
identity
(
)
)
;
}

Returns an Observable that emits the events emitted by source ObservableSource, in a
sorted order based on a specified comparison function.

Note that calling {@code sorted} with long, non-terminating or infinite sources
might cause {@link OutOfMemoryError}

Scheduler:

{@code sorted} does not operate by default on a particular {@link Scheduler}.

@param sortFunction
a function that compares two items emitted by the source ObservableSource and returns an Integer
that indicates their sort order
@return an Observable that emits the items emitted by the source ObservableSource in sorted order

Returns an Observable that emits the events emitted by source ObservableSource in a sorted order based on a specified comparison function .


public static <T> ConnectableObservable<T> observeOn(final ConnectableObservable<T> co, final Scheduler scheduler) {
        final Observable<T> observable = co.observeOn(scheduler);
        return RxJavaPlugins.onAssembly(new Replay<T>(co, observable));
    }

public static < T > ConnectableObservable < T > observeOn ( final ConnectableObservable < T > co , final Scheduler scheduler ) { final Observable < T > observable = co . observeOn ( scheduler ) ; return RxJavaPlugins . onAssembly ( new Replay < T > ( co , observable ) ) ; }

Child Observers will observe the events of the ConnectableObservable on the
specified scheduler.
@param <T> the value type
@param co the connectable observable instance
@param scheduler the target scheduler
@return the new ConnectableObservable instance

Child Observers will observe the events of the ConnectableObservable on the specified scheduler .


@CheckReturnValue
    @NonNull
    public static <T> UnicastProcessor<T> create(int capacityHint) {
        return new UnicastProcessor<T>(capacityHint);
    }

@ CheckReturnValue @ NonNull public static < T > UnicastProcessor < T > create ( int capacityHint ) { return new UnicastProcessor < T > ( capacityHint ) ; }

Creates an UnicastProcessor with the given internal buffer capacity hint.
@param <T> the value type
@param capacityHint the hint to size the internal unbounded buffer
@return an UnicastProcessor instance

Creates an UnicastProcessor with the given internal buffer capacity hint .


@CheckReturnValue
    @NonNull
    public static <T> UnicastProcessor<T> create(int capacityHint, Runnable onCancelled) {
        ObjectHelper.requireNonNull(onCancelled, "onTerminate");
        return new UnicastProcessor<T>(capacityHint, onCancelled);
    }

@ CheckReturnValue @ NonNull public static < T > UnicastProcessor < T > create ( int capacityHint , Runnable onCancelled ) { ObjectHelper . requireNonNull ( onCancelled , "onTerminate" ) ; return new UnicastProcessor < T > ( capacityHint , onCancelled ) ; }

Creates an UnicastProcessor with the given internal buffer capacity hint and a callback for
the case when the single Subscriber cancels its subscription.

<p>The callback, if not null, is called exactly once and
non-overlapped with any active replay.

@param <T> the value type
@param capacityHint the hint to size the internal unbounded buffer
@param onCancelled the non null callback
@return an UnicastProcessor instance

Creates an UnicastProcessor with the given internal buffer capacity hint and a callback for the case when the single Subscriber cancels its subscription .


@SuppressWarnings("unchecked")
    public static <T, R> boolean tryScalarXMapSubscribe(Publisher<T> source,
            Subscriber<? super R> subscriber,
            Function<? super T, ? extends Publisher<? extends R>> mapper) {
        if (source instanceof Callable) {
            T t;

            try {
                t = ((Callable<T>)source).call();
            } catch (Throwable ex) {
                Exceptions.throwIfFatal(ex);
                EmptySubscription.error(ex, subscriber);
                return true;
            }

            if (t == null) {
                EmptySubscription.complete(subscriber);
                return true;
            }

            Publisher<? extends R> r;

            try {
                r = ObjectHelper.requireNonNull(mapper.apply(t), "The mapper returned a null Publisher");
            } catch (Throwable ex) {
                Exceptions.throwIfFatal(ex);
                EmptySubscription.error(ex, subscriber);
                return true;
            }

            if (r instanceof Callable) {
                R u;

                try {
                    u = ((Callable<R>)r).call();
                } catch (Throwable ex) {
                    Exceptions.throwIfFatal(ex);
                    EmptySubscription.error(ex, subscriber);
                    return true;
                }

                if (u == null) {
                    EmptySubscription.complete(subscriber);
                    return true;
                }
                subscriber.onSubscribe(new ScalarSubscription<R>(subscriber, u));
            } else {
                r.subscribe(subscriber);
            }

            return true;
        }
        return false;
    }

@
SuppressWarnings
(
"unchecked"
)
public
static
<
T
,
R
>
boolean
tryScalarXMapSubscribe
(
Publisher
<
T
>
source
,
Subscriber
<
super
R
>
subscriber
,
Function
<
super
T
,
extends
Publisher
<
extends
R
>
>
mapper
)
{
if
(
source
instanceof
Callable
)
{
T
t
;
try
{
t
=
(
(
Callable
<
T
>
)
source
)
.
call
(
)
;
}
catch
(
Throwable
ex
)
{
Exceptions
.
throwIfFatal
(
ex
)
;
EmptySubscription
.
error
(
ex
,
subscriber
)
;
return
true
;
}
if
(
t
==
)
{
EmptySubscription
.
complete
(
subscriber
)
;
return
true
;
}
Publisher
<
extends
R
>
r
;
try
{
r
=
ObjectHelper
.
requireNonNull
(
mapper
.
apply
(
t
)
,
"The mapper returned a null Publisher"
)
;
}
catch
(
Throwable
ex
)
{
Exceptions
.
throwIfFatal
(
ex
)
;
EmptySubscription
.
error
(
ex
,
subscriber
)
;
return
true
;
}
if
(
r
instanceof
Callable
)
{
R
u
;
try
{
u
=
(
(
Callable
<
R
>
)
r
)
.
call
(
)
;
}
catch
(
Throwable
ex
)
{
Exceptions
.
throwIfFatal
(
ex
)
;
EmptySubscription
.
error
(
ex
,
subscriber
)
;
return
true
;
}
if
(
u
==
)
{
EmptySubscription
.
complete
(
subscriber
)
;
return
true
;
}
subscriber
.
onSubscribe
(
new
ScalarSubscription
<
R
>
(
subscriber
,
u
)
)
;
}
else
{
r
.
subscribe
(
subscriber
)
;
}
return
true
;
}
return
false
;
}

Tries to subscribe to a possibly Callable source's mapped Publisher.
@param <T> the input value type
@param <R> the output value type
@param source the source Publisher
@param subscriber the subscriber
@param mapper the function mapping a scalar value into a Publisher
@return true if successful, false if the caller should continue with the regular path.

Tries to subscribe to a possibly Callable source s mapped Publisher .


public static <T, U> Flowable<U> scalarXMap(final T value, final Function<? super T, ? extends Publisher<? extends U>> mapper) {
        return RxJavaPlugins.onAssembly(new ScalarXMapFlowable<T, U>(value, mapper));
    }

public static < T , U > Flowable < U > scalarXMap ( final T value , final Function < ? super T , ? extends Publisher < ? extends U > > mapper ) { return RxJavaPlugins . onAssembly ( new ScalarXMapFlowable < T , U > ( value , mapper ) ) ; }

Maps a scalar value into a Publisher and emits its values.

@param <T> the scalar value type
@param <U> the output value type
@param value the scalar value to map
@param mapper the function that gets the scalar value and should return
a Publisher that gets streamed
@return the new Flowable instance

Maps a scalar value into a Publisher and emits its values .


public static void reset() {
        setErrorHandler(null);
        setScheduleHandler(null);

        setComputationSchedulerHandler(null);
        setInitComputationSchedulerHandler(null);

        setIoSchedulerHandler(null);
        setInitIoSchedulerHandler(null);

        setSingleSchedulerHandler(null);
        setInitSingleSchedulerHandler(null);

        setNewThreadSchedulerHandler(null);
        setInitNewThreadSchedulerHandler(null);

        setOnFlowableAssembly(null);
        setOnFlowableSubscribe(null);

        setOnObservableAssembly(null);
        setOnObservableSubscribe(null);

        setOnSingleAssembly(null);
        setOnSingleSubscribe(null);

        setOnCompletableAssembly(null);
        setOnCompletableSubscribe(null);

        setOnConnectableFlowableAssembly(null);
        setOnConnectableObservableAssembly(null);

        setOnMaybeAssembly(null);
        setOnMaybeSubscribe(null);

        setOnParallelAssembly(null);

        setFailOnNonBlockingScheduler(false);
        setOnBeforeBlocking(null);
    }

public static void reset ( ) { setErrorHandler ( null ) ; setScheduleHandler ( null ) ; setComputationSchedulerHandler ( null ) ; setInitComputationSchedulerHandler ( null ) ; setIoSchedulerHandler ( null ) ; setInitIoSchedulerHandler ( null ) ; setSingleSchedulerHandler ( null ) ; setInitSingleSchedulerHandler ( null ) ; setNewThreadSchedulerHandler ( null ) ; setInitNewThreadSchedulerHandler ( null ) ; setOnFlowableAssembly ( null ) ; setOnFlowableSubscribe ( null ) ; setOnObservableAssembly ( null ) ; setOnObservableSubscribe ( null ) ; setOnSingleAssembly ( null ) ; setOnSingleSubscribe ( null ) ; setOnCompletableAssembly ( null ) ; setOnCompletableSubscribe ( null ) ; setOnConnectableFlowableAssembly ( null ) ; setOnConnectableObservableAssembly ( null ) ; setOnMaybeAssembly ( null ) ; setOnMaybeSubscribe ( null ) ; setOnParallelAssembly ( null ) ; setFailOnNonBlockingScheduler ( false ) ; setOnBeforeBlocking ( null ) ; }

Removes all handlers and resets to default behavior.

Removes all handlers and resets to default behavior .


@CheckReturnValue
    @NonNull
    @SchedulerSupport(SchedulerSupport.NONE)
    public static <T> Maybe<T> fromCompletable(CompletableSource completableSource) {
        ObjectHelper.requireNonNull(completableSource, "completableSource is null");
        return RxJavaPlugins.onAssembly(new MaybeFromCompletable<T>(completableSource));
    }

@
CheckReturnValue
@
NonNull
@
SchedulerSupport
(
SchedulerSupport
.
)
public
static
<
T
>
Maybe
<
T
>
fromCompletable
(
CompletableSource
completableSource
)
{
ObjectHelper
.
requireNonNull
(
completableSource
,
"completableSource is null"
)
;
return
RxJavaPlugins
.
onAssembly
(
new
MaybeFromCompletable
<
T
>
(
completableSource
)
)
;
}

Wraps a CompletableSource into a Maybe.

Scheduler:

{@code fromCompletable} does not operate by default on a particular {@link Scheduler}.

@param <T> the target type
@param completableSource the CompletableSource to convert from
@return the new Maybe instance
@throws NullPointerException if completable is null

Wraps a CompletableSource into a Maybe .


@CheckReturnValue
    @NonNull
    @SchedulerSupport(SchedulerSupport.NONE)
    public static <T> Maybe<T> fromSingle(SingleSource<T> singleSource) {
        ObjectHelper.requireNonNull(singleSource, "singleSource is null");
        return RxJavaPlugins.onAssembly(new MaybeFromSingle<T>(singleSource));
    }

@
CheckReturnValue
@
NonNull
@
SchedulerSupport
(
SchedulerSupport
.
)
public
static
<
T
>
Maybe
<
T
>
fromSingle
(
SingleSource
<
T
>
singleSource
)
{
ObjectHelper
.
requireNonNull
(
singleSource
,
"singleSource is null"
)
;
return
RxJavaPlugins
.
onAssembly
(
new
MaybeFromSingle
<
T
>
(
singleSource
)
)
;
}

Wraps a SingleSource into a Maybe.

Scheduler:

{@code fromSingle} does not operate by default on a particular {@link Scheduler}.

@param <T> the target type
@param singleSource the SingleSource to convert from
@return the new Maybe instance
@throws NullPointerException if single is null


@CheckReturnValue
    @SchedulerSupport(SchedulerSupport.NONE)
    public final Maybe<T> retry(long times, Predicate<? super Throwable> predicate) {
        return toFlowable().retry(times, predicate).singleElement();
    }

@ CheckReturnValue @ SchedulerSupport ( SchedulerSupport . NONE ) public final Maybe < T > retry ( long times , Predicate < ? super Throwable > predicate ) { return toFlowable ( ) . retry ( times , predicate ) . singleElement ( ) ; }

Retries at most times or until the predicate returns false, whichever happens first.

Scheduler:

{@code retry} does not operate by default on a particular {@link Scheduler}.

@param times the number of times to resubscribe if the current Maybe fails
@param predicate the predicate called with the failure Throwable and should return true to trigger a retry.
@return the new Maybe instance

Retries at most times or until the predicate returns false whichever happens first .


public static <T> T requireNonNull(T object, String message) {
        if (object == null) {
            throw new NullPointerException(message);
        }
        return object;
    }

public static < T > T requireNonNull ( T object , String message ) { if ( object == null ) { throw new NullPointerException ( message ) ; } return object ; }

Verifies if the object is not null and returns it or throws a NullPointerException
with the given message.
@param <T> the value type
@param object the object to verify
@param message the message to use with the NullPointerException
@return the object itself
@throws NullPointerException if object is null

Verifies if the object is not null and returns it or throws a NullPointerException with the given message .


@SuppressWarnings("unchecked")
    public static <T> Function<T, T> identity() {
        return (Function<T, T>)IDENTITY;
    }

@ SuppressWarnings ( "unchecked" ) public static < T > Function < T , T > identity ( ) { return ( Function < T , T > ) IDENTITY ; }

Returns an identity function that simply returns its argument.
@param <T> the input and output value type
@return the identity function

Returns an identity function that simply returns its argument .


public static <T> Callable<T> justCallable(T value) {
        return new JustValue<Object, T>(value);
    }

public static < T > Callable < T > justCallable ( T value ) { return new JustValue < Object , T > ( value ) ; }

Returns a Callable that returns the given value.
@param <T> the value type
@param value the value to return
@return the new Callable instance

Returns a Callable that returns the given value .


public static <T, U> Function<T, U> justFunction(U value) {
        return new JustValue<T, U>(value);
    }

public static < T , U > Function < T , U > justFunction ( U value ) { return new JustValue < T , U > ( value ) ; }

Returns a Function that ignores its parameter and returns the given value.
@param <T> the function's input type
@param <U> the value and return type of the function
@param value the value to return
@return the new Function instance

Returns a Function that ignores its parameter and returns the given value .


public static <T, U> Function<T, U> castFunction(Class<U> target) {
        return new CastToClass<T, U>(target);
    }

public static < T , U > Function < T , U > castFunction ( Class < U > target ) { return new CastToClass < T , U > ( target ) ; }

Returns a function that cast the incoming values via a Class object.
@param <T> the input value type
@param <U> the output and target type
@param target the target class
@return the new Function instance

Returns a function that cast the incoming values via a Class object .


@CheckReturnValue
    @NonNull
    public static <T> UnicastSubject<T> create() {
        return new UnicastSubject<T>(bufferSize(), true);
    }

@ CheckReturnValue @ NonNull public static < T > UnicastSubject < T > create ( ) { return new UnicastSubject < T > ( bufferSize ( ) , true ) ; }

Creates an UnicastSubject with an internal buffer capacity hint 16.
@param <T> the value type
@return an UnicastSubject instance

Creates an UnicastSubject with an internal buffer capacity hint 16 .


@CheckReturnValue
    @NonNull
    public static <T> UnicastSubject<T> create(int capacityHint) {
        return new UnicastSubject<T>(capacityHint, true);
    }

@ CheckReturnValue @ NonNull public static < T > UnicastSubject < T > create ( int capacityHint ) { return new UnicastSubject < T > ( capacityHint , true ) ; }

Creates an UnicastSubject with the given internal buffer capacity hint.
@param <T> the value type
@param capacityHint the hint to size the internal unbounded buffer
@return an UnicastSubject instance

Creates an UnicastSubject with the given internal buffer capacity hint .


@CheckReturnValue
    @NonNull
    public static <T> UnicastSubject<T> create(int capacityHint, Runnable onTerminate) {
        return new UnicastSubject<T>(capacityHint, onTerminate, true);
    }

@ CheckReturnValue @ NonNull public static < T > UnicastSubject < T > create ( int capacityHint , Runnable onTerminate ) { return new UnicastSubject < T > ( capacityHint , onTerminate , true ) ; }

Creates an UnicastSubject with the given internal buffer capacity hint and a callback for
the case when the single Subscriber cancels its subscription.

<p>The callback, if not null, is called exactly once and
non-overlapped with any active replay.

@param <T> the value type
@param capacityHint the hint to size the internal unbounded buffer
@param onTerminate the callback to run when the Subject is terminated or cancelled, null not allowed
@return an UnicastSubject instance

Creates an UnicastSubject with the given internal buffer capacity hint and a callback for the case when the single Subscriber cancels its subscription .


@CheckReturnValue
    @NonNull
    public static <T> UnicastSubject<T> create(boolean delayError) {
        return new UnicastSubject<T>(bufferSize(), delayError);
    }

@ CheckReturnValue @ NonNull public static < T > UnicastSubject < T > create ( boolean delayError ) { return new UnicastSubject < T > ( bufferSize ( ) , delayError ) ; }

Creates an UnicastSubject with an internal buffer capacity hint 16 and given delay error flag.

The callback, if not null, is called exactly once and
non-overlapped with any active replay.

History: 2.0.8 - experimental
@param <T> the value type
@param delayError deliver pending onNext events before onError
@return an UnicastSubject instance
@since 2.2

Creates an UnicastSubject with an internal buffer capacity hint 16 and given delay error flag .


public Throwable blockingGetError() {
        if (getCount() != 0) {
            try {
                BlockingHelper.verifyNonBlocking();
                await();
            } catch (InterruptedException ex) {
                dispose();
                return ex;
            }
        }
        return error;
    }

public Throwable blockingGetError ( ) { if ( getCount ( ) != 0 ) { try { BlockingHelper . verifyNonBlocking ( ) ; await ( ) ; } catch ( InterruptedException ex ) { dispose ( ) ; return ex ; } } return error ; }

Block until the latch is counted down and return the error received or null if no
error happened.
@return the error received or null

Block until the latch is counted down and return the error received or null if no error happened .


public Throwable blockingGetError(long timeout, TimeUnit unit) {
        if (getCount() != 0) {
            try {
                BlockingHelper.verifyNonBlocking();
                if (!await(timeout, unit)) {
                    dispose();
                    throw ExceptionHelper.wrapOrThrow(new TimeoutException(timeoutMessage(timeout, unit)));
                }
            } catch (InterruptedException ex) {
                dispose();
                throw ExceptionHelper.wrapOrThrow(ex);
            }
        }
        return error;
    }

public Throwable blockingGetError ( long timeout , TimeUnit unit ) { if ( getCount ( ) != 0 ) { try { BlockingHelper . verifyNonBlocking ( ) ; if ( ! await ( timeout , unit ) ) { dispose ( ) ; throw ExceptionHelper . wrapOrThrow ( new TimeoutException ( timeoutMessage ( timeout , unit ) ) ) ; } } catch ( InterruptedException ex ) { dispose ( ) ; throw ExceptionHelper . wrapOrThrow ( ex ) ; } } return error ; }

Block until the latch is counted down and return the error received or
when the wait is interrupted or times out, null otherwise.
@param timeout the timeout value
@param unit the time unit
@return the error received or null

Block until the latch is counted down and return the error received or when the wait is interrupted or times out null otherwise .


public boolean blockingAwait(long timeout, TimeUnit unit) {
        if (getCount() != 0) {
            try {
                BlockingHelper.verifyNonBlocking();
                if (!await(timeout, unit)) {
                    dispose();
                    return false;
                }
            } catch (InterruptedException ex) {
                dispose();
                throw ExceptionHelper.wrapOrThrow(ex);
            }
        }
        Throwable ex = error;
        if (ex != null) {
            throw ExceptionHelper.wrapOrThrow(ex);
        }
        return true;
    }

public boolean blockingAwait ( long timeout , TimeUnit unit ) { if ( getCount ( ) != 0 ) { try { BlockingHelper . verifyNonBlocking ( ) ; if ( ! await ( timeout , unit ) ) { dispose ( ) ; return false ; } } catch ( InterruptedException ex ) { dispose ( ) ; throw ExceptionHelper . wrapOrThrow ( ex ) ; } } Throwable ex = error ; if ( ex != null ) { throw ExceptionHelper . wrapOrThrow ( ex ) ; } return true ; }

Block until the observer terminates and return true; return false if
the wait times out.
@param timeout the timeout value
@param unit the time unit
@return true if the observer terminated in time, false otherwise

Block until the observer terminates and return true ; return false if the wait times out .


public static <T, U> void drainMaxLoop(SimplePlainQueue<T> q, Subscriber<? super U> a, boolean delayError,
            Disposable dispose, QueueDrain<T, U> qd) {
        int missed = 1;

        for (;;) {
            for (;;) {
                boolean d = qd.done();

                T v = q.poll();

                boolean empty = v == null;

                if (checkTerminated(d, empty, a, delayError, q, qd)) {
                    if (dispose != null) {
                        dispose.dispose();
                    }
                    return;
                }

                if (empty) {
                    break;
                }

                long r = qd.requested();
                if (r != 0L) {
                    if (qd.accept(a, v)) {
                        if (r != Long.MAX_VALUE) {
                            qd.produced(1);
                        }
                    }
                } else {
                    q.clear();
                    if (dispose != null) {
                        dispose.dispose();
                    }
                    a.onError(new MissingBackpressureException("Could not emit value due to lack of requests."));
                    return;
                }
            }

            missed = qd.leave(-missed);
            if (missed == 0) {
                break;
            }
        }
    }

Drain the queue but give up with an error if there aren't enough requests.
@param <T> the queue value type
@param <U> the emission value type
@param q the queue
@param a the subscriber
@param delayError true if errors should be delayed after all normal items
@param dispose the disposable to call when termination happens and cleanup is necessary
@param qd the QueueDrain instance that gives status information to the drain logic

Drain the queue but give up with an error if there aren t enough requests .


public static void request(Subscription s, int prefetch) {
        s.request(prefetch < 0 ? Long.MAX_VALUE : prefetch);
    }

public static void request ( Subscription s , int prefetch ) { s . request ( prefetch < 0 ? Long . MAX_VALUE : prefetch ) ; }

Requests Long.MAX_VALUE if prefetch is negative or the exact
amount if prefetch is positive.
@param s the Subscription to request from
@param prefetch the prefetch value

Requests Long . MAX_VALUE if prefetch is negative or the exact amount if prefetch is positive .


public static <T> void postComplete(Subscriber<? super T> actual,
                                        Queue<T> queue,
                                        AtomicLong state,
                                        BooleanSupplier isCancelled) {

        if (queue.isEmpty()) {
            actual.onComplete();
            return;
        }

        if (postCompleteDrain(state.get(), actual, queue, state, isCancelled)) {
            return;
        }

        for (; ; ) {
            long r = state.get();

            if ((r & COMPLETED_MASK) != 0L) {
                return;
            }

            long u = r | COMPLETED_MASK;
            // (active, r) -> (complete, r) transition
            if (state.compareAndSet(r, u)) {
                // if the requested amount was non-zero, drain the queue
                if (r != 0L) {
                    postCompleteDrain(u, actual, queue, state, isCancelled);
                }

                return;
            }
        }

    }

Signals the completion of the main sequence and switches to post-completion replay mode.

Don't modify the queue after calling this method!

Post-completion backpressure handles the case when a source produces values based on
requests when it is active but more values are available even after its completion.
In this case, the onComplete() can't just emit the contents of the queue but has to
coordinate with the requested amounts. This requires two distinct modes: active and
completed. In active mode, requests flow through and the queue is not accessed but
in completed mode, requests no-longer reach the upstream but help in draining the queue.

The algorithm utilizes the most significant bit (bit 63) of a long value (AtomicLong) since
request amount only goes up to Long.MAX_VALUE (bits 0-62) and negative values aren't
allowed.

@param <T> the value type emitted
@param actual the target Subscriber to send events to
@param queue the queue to drain if in the post-complete state
@param state holds the request amount and the post-completed flag
@param isCancelled a supplier that returns true if the drain has been cancelled

Signals the completion of the main sequence and switches to post - completion replay mode .


protected final void complete(R n) {
        long p = produced;
        if (p != 0) {
            BackpressureHelper.produced(this, p);
        }

        for (;;) {
            long r = get();
            if ((r & COMPLETE_MASK) != 0) {
                onDrop(n);
                return;
            }
            if ((r & REQUEST_MASK) != 0) {
                lazySet(COMPLETE_MASK + 1);
                downstream.onNext(n);
                downstream.onComplete();
                return;
            }
            value = n;
            if (compareAndSet(0, COMPLETE_MASK)) {
                return;
            }
            value = null;
        }
    }

protected final void complete ( R n ) { long p = produced ; if ( p != 0 ) { BackpressureHelper . produced ( this , p ) ; } for ( ; ; ) { long r = get ( ) ; if ( ( r & COMPLETE_MASK ) != 0 ) { onDrop ( n ) ; return ; } if ( ( r & REQUEST_MASK ) != 0 ) { lazySet ( COMPLETE_MASK + 1 ) ; downstream . onNext ( n ) ; downstream . onComplete ( ) ; return ; } value = n ; if ( compareAndSet ( 0 , COMPLETE_MASK ) ) { return ; } value = null ; } }

Signals the given value and an onComplete if the downstream is ready to receive the final value.
@param n the value to emit

Signals the given value and an onComplete if the downstream is ready to receive the final value .


@SuppressWarnings("unchecked")
    @Nullable
    public T getValue() {
        Object o = value;
        if (o != null && !NotificationLite.isError(o)) {
            return (T)value;
        }
        return null;
    }

@ SuppressWarnings ( "unchecked" ) @ Nullable public T getValue ( ) { Object o = value ; if ( o != null && ! NotificationLite . isError ( o ) ) { return ( T ) value ; } return null ; }

Returns the contained value if this notification is an onNext
signal, null otherwise.
@return the value contained or null
@see #isOnNext()

Returns the contained value if this notification is an onNext signal null otherwise .


@Nullable
    public Throwable getError() {
        Object o = value;
        if (NotificationLite.isError(o)) {
            return NotificationLite.getError(o);
        }
        return null;
    }

@ Nullable public Throwable getError ( ) { Object o = value ; if ( NotificationLite . isError ( o ) ) { return NotificationLite . getError ( o ) ; } return null ; }

Returns the container Throwable error if this notification is an onError
signal, null otherwise.
@return the Throwable error contained or null
@see #isOnError()

Returns the container Throwable error if this notification is an onError signal null otherwise .


public static boolean validate(Disposable upstream, Disposable next, Class<?> observer) {
        ObjectHelper.requireNonNull(next, "next is null");
        if (upstream != null) {
            next.dispose();
            if (upstream != DisposableHelper.DISPOSED) {
                reportDoubleSubscription(observer);
            }
            return false;
        }
        return true;
    }

public
static
boolean
validate
(
Disposable
upstream
,
Disposable
next
,
Class
<
>
observer
)
{
ObjectHelper
.
requireNonNull
(
next
,
"next is null"
)
;
if
(
upstream
!=
)
{
next
.
dispose
(
)
;
if
(
upstream
!=
DisposableHelper
.
DISPOSED
)
{
reportDoubleSubscription
(
observer
)
;
}
return
false
;
}
return
true
;
}

Ensures that the upstream Disposable is null and returns true, otherwise
disposes the next Disposable and if the upstream is not the shared
disposed instance, reports a ProtocolViolationException due to
multiple subscribe attempts.
@param upstream the upstream current value
@param next the Disposable to check for nullness and dispose if necessary
@param observer the class of the consumer to have a personalized
error message if the upstream already contains a non-cancelled Disposable.
@return true if successful, false if the upstream was non null

Ensures that the upstream Disposable is null and returns true otherwise disposes the next Disposable and if the upstream is not the shared disposed instance reports a ProtocolViolationException due to multiple subscribe attempts .


public static boolean setOnce(AtomicReference<Disposable> upstream, Disposable next, Class<?> observer) {
        ObjectHelper.requireNonNull(next, "next is null");
        if (!upstream.compareAndSet(null, next)) {
            next.dispose();
            if (upstream.get() != DisposableHelper.DISPOSED) {
                reportDoubleSubscription(observer);
            }
            return false;
        }
        return true;
    }

public
static
boolean
setOnce
(
AtomicReference
<
Disposable
>
upstream
,
Disposable
next
,
Class
<
>
observer
)
{
ObjectHelper
.
requireNonNull
(
next
,
"next is null"
)
;
if
(
!
upstream
.
compareAndSet
(
,
next
)
)
{
next
.
dispose
(
)
;
if
(
upstream
.
get
(
)
!=
DisposableHelper
.
DISPOSED
)
{
reportDoubleSubscription
(
observer
)
;
}
return
false
;
}
return
true
;
}

Atomically updates the target upstream AtomicReference from null to the non-null
next Disposable, otherwise disposes next and reports a ProtocolViolationException
if the AtomicReference doesn't contain the shared disposed indicator.
@param upstream the target AtomicReference to update
@param next the Disposable to set on it atomically
@param observer the class of the consumer to have a personalized
error message if the upstream already contains a non-cancelled Disposable.
@return true if successful, false if the content of the AtomicReference was non null

Atomically updates the target upstream AtomicReference from null to the non - null next Disposable otherwise disposes next and reports a ProtocolViolationException if the AtomicReference doesn t contain the shared disposed indicator .


public static boolean validate(Subscription upstream, Subscription next, Class<?> subscriber) {
        ObjectHelper.requireNonNull(next, "next is null");
        if (upstream != null) {
            next.cancel();
            if (upstream != SubscriptionHelper.CANCELLED) {
                reportDoubleSubscription(subscriber);
            }
            return false;
        }
        return true;
    }

public
static
boolean
validate
(
Subscription
upstream
,
Subscription
next
,
Class
<
>
subscriber
)
{
ObjectHelper
.
requireNonNull
(
next
,
"next is null"
)
;
if
(
upstream
!=
)
{
next
.
cancel
(
)
;
if
(
upstream
!=
SubscriptionHelper
.
CANCELLED
)
{
reportDoubleSubscription
(
subscriber
)
;
}
return
false
;
}
return
true
;
}

Ensures that the upstream Subscription is null and returns true, otherwise
cancels the next Subscription and if the upstream is not the shared
cancelled instance, reports a ProtocolViolationException due to
multiple subscribe attempts.
@param upstream the upstream current value
@param next the Subscription to check for nullness and cancel if necessary
@param subscriber the class of the consumer to have a personalized
error message if the upstream already contains a non-cancelled Subscription.
@return true if successful, false if the upstream was non null

Ensures that the upstream Subscription is null and returns true otherwise cancels the next Subscription and if the upstream is not the shared cancelled instance reports a ProtocolViolationException due to multiple subscribe attempts .


public static boolean setOnce(AtomicReference<Subscription> upstream, Subscription next, Class<?> subscriber) {
        ObjectHelper.requireNonNull(next, "next is null");
        if (!upstream.compareAndSet(null, next)) {
            next.cancel();
            if (upstream.get() != SubscriptionHelper.CANCELLED) {
                reportDoubleSubscription(subscriber);
            }
            return false;
        }
        return true;
    }

public
static
boolean
setOnce
(
AtomicReference
<
Subscription
>
upstream
,
Subscription
next
,
Class
<
>
subscriber
)
{
ObjectHelper
.
requireNonNull
(
next
,
"next is null"
)
;
if
(
!
upstream
.
compareAndSet
(
,
next
)
)
{
next
.
cancel
(
)
;
if
(
upstream
.
get
(
)
!=
SubscriptionHelper
.
CANCELLED
)
{
reportDoubleSubscription
(
subscriber
)
;
}
return
false
;
}
return
true
;
}

Atomically updates the target upstream AtomicReference from null to the non-null
next Subscription, otherwise cancels next and reports a ProtocolViolationException
if the AtomicReference doesn't contain the shared cancelled indicator.
@param upstream the target AtomicReference to update
@param next the Subscription to set on it atomically
@param subscriber the class of the consumer to have a personalized
error message if the upstream already contains a non-cancelled Subscription.
@return true if successful, false if the content of the AtomicReference was non null

Atomically updates the target upstream AtomicReference from null to the non - null next Subscription otherwise cancels next and reports a ProtocolViolationException if the AtomicReference doesn t contain the shared cancelled indicator .


public static long addCap(long a, long b) {
        long u = a + b;
        if (u < 0L) {
            return Long.MAX_VALUE;
        }
        return u;
    }

public static long addCap ( long a , long b ) { long u = a + b ; if ( u < 0L ) { return Long . MAX_VALUE ; } return u ; }

Adds two long values and caps the sum at Long.MAX_VALUE.
@param a the first value
@param b the second value
@return the sum capped at Long.MAX_VALUE

Adds two long values and caps the sum at Long . MAX_VALUE .


public static long multiplyCap(long a, long b) {
        long u = a * b;
        if (((a | b) >>> 31) != 0) {
            if (u / a != b) {
                return Long.MAX_VALUE;
            }
        }
        return u;
    }

public static long multiplyCap ( long a , long b ) { long u = a * b ; if ( ( ( a | b ) >>> 31 ) != 0 ) { if ( u / a != b ) { return Long . MAX_VALUE ; } } return u ; }

Multiplies two long values and caps the product at Long.MAX_VALUE.
@param a the first value
@param b the second value
@return the product capped at Long.MAX_VALUE

Multiplies two long values and caps the product at Long . MAX_VALUE .


public static long add(AtomicLong requested, long n) {
        for (;;) {
            long r = requested.get();
            if (r == Long.MAX_VALUE) {
                return Long.MAX_VALUE;
            }
            long u = addCap(r, n);
            if (requested.compareAndSet(r, u)) {
                return r;
            }
        }
    }

public static long add ( AtomicLong requested , long n ) { for ( ; ; ) { long r = requested . get ( ) ; if ( r == Long . MAX_VALUE ) { return Long . MAX_VALUE ; } long u = addCap ( r , n ) ; if ( requested . compareAndSet ( r , u ) ) { return r ; } } }

Atomically adds the positive value n to the requested value in the AtomicLong and
caps the result at Long.MAX_VALUE and returns the previous value.
@param requested the AtomicLong holding the current requested value
@param n the value to add, must be positive (not verified)
@return the original value before the add

Atomically adds the positive value n to the requested value in the AtomicLong and caps the result at Long . MAX_VALUE and returns the previous value .


private static NullPointerException toNpe(Throwable ex) {
        NullPointerException npe = new NullPointerException("Actually not, but can't pass out an exception otherwise...");
        npe.initCause(ex);
        return npe;
    }

Creates a NullPointerException instance and sets the given Throwable as its initial cause.
@param ex the Throwable instance to use as cause, not null (not verified)
@return the created NullPointerException

Creates a NullPointerException instance and sets the given Throwable as its initial cause .


public void add(Object o) {
        // if no value yet, create the first array
        if (size == 0) {
            head = new Object[capacityHint + 1];
            tail = head;
            head[0] = o;
            indexInTail = 1;
            size = 1;
        } else
        // if the tail is full, create a new tail and link
        if (indexInTail == capacityHint) {
            Object[] t = new Object[capacityHint + 1];
            t[0] = o;
            tail[capacityHint] = t;
            tail = t;
            indexInTail = 1;
            size++;
        } else {
            tail[indexInTail] = o;
            indexInTail++;
            size++;
        }
    }

Adds a new element to this list.
@param o the object to add, nulls are accepted


public static void shutdown() {
        ScheduledExecutorService exec = PURGE_THREAD.getAndSet(null);
        if (exec != null) {
            exec.shutdownNow();
        }
        POOLS.clear();
    }

public static void shutdown ( ) { ScheduledExecutorService exec = PURGE_THREAD . getAndSet ( null ) ; if ( exec != null ) { exec . shutdownNow ( ) ; } POOLS . clear ( ) ; }


public static ScheduledExecutorService create(ThreadFactory factory) {
        final ScheduledExecutorService exec = Executors.newScheduledThreadPool(1, factory);
        tryPutIntoPool(PURGE_ENABLED, exec);
        return exec;
    }

public static ScheduledExecutorService create ( ThreadFactory factory ) { final ScheduledExecutorService exec = Executors . newScheduledThreadPool ( 1 , factory ) ; tryPutIntoPool ( PURGE_ENABLED , exec ) ; return exec ; }

Creates a ScheduledExecutorService with the given factory.
@param factory the thread factory
@return the ScheduledExecutorService

Creates a ScheduledExecutorService with the given factory .


public final void setSubscription(Subscription s) {
        if (cancelled) {
            s.cancel();
            return;
        }

        ObjectHelper.requireNonNull(s, "s is null");

        if (get() == 0 && compareAndSet(0, 1)) {
            Subscription a = actual;

            if (a != null && cancelOnReplace) {
                a.cancel();
            }

            actual = s;

            long r = requested;

            if (decrementAndGet() != 0) {
                drainLoop();
            }

            if (r != 0L) {
                s.request(r);
            }

            return;
        }

        Subscription a = missedSubscription.getAndSet(s);
        if (a != null && cancelOnReplace) {
            a.cancel();
        }
        drain();
    }

public
final
void
setSubscription
(
Subscription
s
)
{
if
(
cancelled
)
{
s
.
cancel
(
)
;
return
;
}
ObjectHelper
.
requireNonNull
(
s
,
"s is null"
)
;
if
(
get
(
)
==
0
&&
compareAndSet
(
0
,
1
)
)
{
Subscription
a
=
actual
;
if
(
a
!=
&&
cancelOnReplace
)
{
a
.
cancel
(
)
;
}
actual
=
s
;
long
r
=
requested
;
if
(
decrementAndGet
(
)
!=
0
)
{
drainLoop
(
)
;
}
if
(
r
!=
0L
)
{
s
.
request
(
r
)
;
}
return
;
}
Subscription
a
=
missedSubscription
.
getAndSet
(
s
)
;
if
(
a
!=
&&
cancelOnReplace
)
{
a
.
cancel
(
)
;
}
drain
(
)
;
}

Atomically sets a new subscription.
@param s the subscription to set, not null (verified)


void emitLoop() {
        for (;;) {
            AppendOnlyLinkedArrayList<Object> q;
            synchronized (this) {
                q = queue;
                if (q == null) {
                    emitting = false;
                    return;
                }
                queue = null;
            }
            q.forEachWhile(this);
        }
    }

void emitLoop ( ) { for ( ; ; ) { AppendOnlyLinkedArrayList < Object > q ; synchronized ( this ) { q = queue ; if ( q == null ) { emitting = false ; return ; } queue = null ; } q . forEachWhile ( this ) ; } }

Loops until all notifications in the queue has been processed.

Loops until all notifications in the queue has been processed .


public static RuntimeException wrapOrThrow(Throwable error) {
        if (error instanceof Error) {
            throw (Error)error;
        }
        if (error instanceof RuntimeException) {
            return (RuntimeException)error;
        }
        return new RuntimeException(error);
    }

public static RuntimeException wrapOrThrow ( Throwable error ) { if ( error instanceof Error ) { throw ( Error ) error ; } if ( error instanceof RuntimeException ) { return ( RuntimeException ) error ; } return new RuntimeException ( error ) ; }

If the provided Throwable is an Error this method
throws it, otherwise returns a RuntimeException wrapping the error
if that error is a checked exception.
@param error the error to wrap or throw
@return the (wrapped) error

If the provided Throwable is an Error this method throws it otherwise returns a RuntimeException wrapping the error if that error is a checked exception .


public static List<Throwable> flatten(Throwable t) {
        List<Throwable> list = new ArrayList<Throwable>();
        ArrayDeque<Throwable> deque = new ArrayDeque<Throwable>();
        deque.offer(t);

        while (!deque.isEmpty()) {
            Throwable e = deque.removeFirst();
            if (e instanceof CompositeException) {
                CompositeException ce = (CompositeException) e;
                List<Throwable> exceptions = ce.getExceptions();
                for (int i = exceptions.size() - 1; i >= 0; i--) {
                    deque.offerFirst(exceptions.get(i));
                }
            } else {
                list.add(e);
            }
        }

        return list;
    }

public static List < Throwable > flatten ( Throwable t ) { List < Throwable > list = new ArrayList < Throwable > ( ) ; ArrayDeque < Throwable > deque = new ArrayDeque < Throwable > ( ) ; deque . offer ( t ) ; while ( ! deque . isEmpty ( ) ) { Throwable e = deque . removeFirst ( ) ; if ( e instanceof CompositeException ) { CompositeException ce = ( CompositeException ) e ; List < Throwable > exceptions = ce . getExceptions ( ) ; for ( int i = exceptions . size ( ) - 1 ; i >= 0 ; i -- ) { deque . offerFirst ( exceptions . get ( i ) ) ; } } else { list . add ( e ) ; } } return list ; }

Returns a flattened list of Throwables from tree-like CompositeException chain.
@param t the starting throwable
@return the list of Throwables flattened in a depth-first manner

Returns a flattened list of Throwables from tree - like CompositeException chain .


@SuppressWarnings("unchecked")
    public static <E extends Throwable> Exception throwIfThrowable(Throwable e) throws E {
        if (e instanceof Exception) {
            return (Exception)e;
        }
        throw (E)e;
    }

@ SuppressWarnings ( "unchecked" ) public static < E extends Throwable > Exception throwIfThrowable ( Throwable e ) throws E { if ( e instanceof Exception ) { return ( Exception ) e ; } throw ( E ) e ; }

Workaround for Java 6 not supporting throwing a final Throwable from a catch block.
@param <E> the generic exception type
@param e the Throwable error to return or throw
@return the Throwable e if it is a subclass of Exception
@throws E the generic exception thrown

Workaround for Java 6 not supporting throwing a final Throwable from a catch block .


public void clear() {
        if (disposed) {
            return;
        }
        OpenHashSet<Disposable> set;
        synchronized (this) {
            if (disposed) {
                return;
            }

            set = resources;
            resources = null;
        }

        dispose(set);
    }

public void clear ( ) { if ( disposed ) { return ; } OpenHashSet < Disposable > set ; synchronized ( this ) { if ( disposed ) { return ; } set = resources ; resources = null ; } dispose ( set ) ; }

Atomically clears the container, then disposes all the previously contained Disposables.

Atomically clears the container then disposes all the previously contained Disposables .


public int size() {
        if (disposed) {
            return 0;
        }
        synchronized (this) {
            if (disposed) {
                return 0;
            }
            OpenHashSet<Disposable> set = resources;
            return set != null ? set.size() : 0;
        }
    }

public int size ( ) { if ( disposed ) { return 0 ; } synchronized ( this ) { if ( disposed ) { return 0 ; } OpenHashSet < Disposable > set = resources ; return set != null ? set . size ( ) : 0 ; } }

Returns the number of currently held Disposables.
@return the number of currently held Disposables

Returns the number of currently held Disposables .


@SuppressWarnings("unchecked")
    public static <T, R> boolean tryScalarXMapSubscribe(ObservableSource<T> source,
            Observer<? super R> observer,
            Function<? super T, ? extends ObservableSource<? extends R>> mapper) {
        if (source instanceof Callable) {
            T t;

            try {
                t = ((Callable<T>)source).call();
            } catch (Throwable ex) {
                Exceptions.throwIfFatal(ex);
                EmptyDisposable.error(ex, observer);
                return true;
            }

            if (t == null) {
                EmptyDisposable.complete(observer);
                return true;
            }

            ObservableSource<? extends R> r;

            try {
                r = ObjectHelper.requireNonNull(mapper.apply(t), "The mapper returned a null ObservableSource");
            } catch (Throwable ex) {
                Exceptions.throwIfFatal(ex);
                EmptyDisposable.error(ex, observer);
                return true;
            }

            if (r instanceof Callable) {
                R u;

                try {
                    u = ((Callable<R>)r).call();
                } catch (Throwable ex) {
                    Exceptions.throwIfFatal(ex);
                    EmptyDisposable.error(ex, observer);
                    return true;
                }

                if (u == null) {
                    EmptyDisposable.complete(observer);
                    return true;
                }
                ScalarDisposable<R> sd = new ScalarDisposable<R>(observer, u);
                observer.onSubscribe(sd);
                sd.run();
            } else {
                r.subscribe(observer);
            }

            return true;
        }
        return false;
    }

Tries to subscribe to a possibly Callable source's mapped ObservableSource.
@param <T> the input value type
@param <R> the output value type
@param source the source ObservableSource
@param observer the subscriber
@param mapper the function mapping a scalar value into an ObservableSource
@return true if successful, false if the caller should continue with the regular path.

Tries to subscribe to a possibly Callable source s mapped ObservableSource .


public static <T, U> Observable<U> scalarXMap(T value,
            Function<? super T, ? extends ObservableSource<? extends U>> mapper) {
        return RxJavaPlugins.onAssembly(new ScalarXMapObservable<T, U>(value, mapper));
    }

public static < T , U > Observable < U > scalarXMap ( T value , Function < ? super T , ? extends ObservableSource < ? extends U > > mapper ) { return RxJavaPlugins . onAssembly ( new ScalarXMapObservable < T , U > ( value , mapper ) ) ; }

Maps a scalar value into an Observable and emits its values.

@param <T> the scalar value type
@param <U> the output value type
@param value the scalar value to map
@param mapper the function that gets the scalar value and should return
an ObservableSource that gets streamed
@return the new Observable instance

Maps a scalar value into an Observable and emits its values .


public <U> boolean accept(Subscriber<? super U> subscriber) {
        Object[] a = head;
        final int c = capacity;
        while (a != null) {
            for (int i = 0; i < c; i++) {
                Object o = a[i];
                if (o == null) {
                    break;
                }

                if (NotificationLite.acceptFull(o, subscriber)) {
                    return true;
                }
            }
            a = (Object[])a[c];
        }
        return false;
    }

public < U > boolean accept ( Subscriber < ? super U > subscriber ) { Object [ ] a = head ; final int c = capacity ; while ( a != null ) { for ( int i = 0 ; i < c ; i ++ ) { Object o = a [ i ] ; if ( o == null ) { break ; } if ( NotificationLite . acceptFull ( o , subscriber ) ) { return true ; } } a = ( Object [ ] ) a [ c ] ; } return false ; }

Interprets the contents as NotificationLite objects and calls
the appropriate Subscriber method.

@param <U> the target type
@param subscriber the subscriber to emit the events to
@return true if a terminal event has been reached

Interprets the contents as NotificationLite objects and calls the appropriate Subscriber method .


public <U> boolean accept(Observer<? super U> observer) {
        Object[] a = head;
        final int c = capacity;
        while (a != null) {
            for (int i = 0; i < c; i++) {
                Object o = a[i];
                if (o == null) {
                    break;
                }

                if (NotificationLite.acceptFull(o, observer)) {
                    return true;
                }
            }
            a = (Object[])a[c];
        }
        return false;
    }

public < U > boolean accept ( Observer < ? super U > observer ) { Object [ ] a = head ; final int c = capacity ; while ( a != null ) { for ( int i = 0 ; i < c ; i ++ ) { Object o = a [ i ] ; if ( o == null ) { break ; } if ( NotificationLite . acceptFull ( o , observer ) ) { return true ; } } a = ( Object [ ] ) a [ c ] ; } return false ; }

Interprets the contents as NotificationLite objects and calls
the appropriate Observer method.

@param <U> the target type
@param observer the observer to emit the events to
@return true if a terminal event has been reached

Interprets the contents as NotificationLite objects and calls the appropriate Observer method .


public void start() {
        if (SubscriptionHelper.setOnce(upstream, EmptySubscription.INSTANCE)) {
            queue = new SpscArrayQueue<T>(bufferSize);
        }
    }

public void start ( ) { if ( SubscriptionHelper . setOnce ( upstream , EmptySubscription . INSTANCE ) ) { queue = new SpscArrayQueue < T > ( bufferSize ) ; } }

Initializes this Processor by setting an upstream Subscription that
ignores request amounts, uses a fixed buffer
and allows using the onXXX and offer methods
afterwards.

Initializes this Processor by setting an upstream Subscription that ignores request amounts uses a fixed buffer and allows using the onXXX and offer methods afterwards .


public void startUnbounded() {
        if (SubscriptionHelper.setOnce(upstream, EmptySubscription.INSTANCE)) {
            queue = new SpscLinkedArrayQueue<T>(bufferSize);
        }
    }

public void startUnbounded ( ) { if ( SubscriptionHelper . setOnce ( upstream , EmptySubscription . INSTANCE ) ) { queue = new SpscLinkedArrayQueue < T > ( bufferSize ) ; } }

Initializes this Processor by setting an upstream Subscription that
ignores request amounts, uses an unbounded buffer
and allows using the onXXX and offer methods
afterwards.

Initializes this Processor by setting an upstream Subscription that ignores request amounts uses an unbounded buffer and allows using the onXXX and offer methods afterwards .


public boolean offer(T t) {
        if (once.get()) {
            return false;
        }
        ObjectHelper.requireNonNull(t, "offer called with null. Null values are generally not allowed in 2.x operators and sources.");
        if (fusionMode == QueueSubscription.NONE) {
            if (queue.offer(t)) {
                drain();
                return true;
            }
        }
        return false;
    }

Tries to offer an item into the internal queue and returns false
if the queue is full.
@param t the item to offer, not null
@return true if successful, false if the queue is full

Tries to offer an item into the internal queue and returns false if the queue is full .


@Nullable
    public Disposable get() {
        Disposable d = resource.get();
        if (d == DisposableHelper.DISPOSED) {
            return Disposables.disposed();
        }
        return d;
    }

@ Nullable public Disposable get ( ) { Disposable d = resource . get ( ) ; if ( d == DisposableHelper . DISPOSED ) { return Disposables . disposed ( ) ; } return d ; }

Returns the currently contained Disposable or null if this container is empty.
@return the current Disposable, may be null

Returns the currently contained Disposable or null if this container is empty .


public final void complete(T value) {
        int state = get();
        if ((state & (FUSED_READY | FUSED_CONSUMED | TERMINATED | DISPOSED)) != 0) {
            return;
        }
        Observer<? super T> a = downstream;
        if (state == FUSED_EMPTY) {
            this.value = value;
            lazySet(FUSED_READY);
            a.onNext(null);
        } else {
            lazySet(TERMINATED);
            a.onNext(value);
        }
        if (get() != DISPOSED) {
            a.onComplete();
        }
    }

public final void complete ( T value ) { int state = get ( ) ; if ( ( state & ( FUSED_READY | FUSED_CONSUMED | TERMINATED | DISPOSED ) ) != 0 ) { return ; } Observer < ? super T > a = downstream ; if ( state == FUSED_EMPTY ) { this . value = value ; lazySet ( FUSED_READY ) ; a . onNext ( null ) ; } else { lazySet ( TERMINATED ) ; a . onNext ( value ) ; } if ( get ( ) != DISPOSED ) { a . onComplete ( ) ; } }

Complete the target with a single value or indicate there is a value available in
fusion mode.
@param value the value to signal, not null (not verified)

Complete the target with a single value or indicate there is a value available in fusion mode .


public final void error(Throwable t) {
        int state = get();
        if ((state & (FUSED_READY | FUSED_CONSUMED | TERMINATED | DISPOSED)) != 0) {
            RxJavaPlugins.onError(t);
            return;
        }
        lazySet(TERMINATED);
        downstream.onError(t);
    }

public final void error ( Throwable t ) { int state = get ( ) ; if ( ( state & ( FUSED_READY | FUSED_CONSUMED | TERMINATED | DISPOSED ) ) != 0 ) { RxJavaPlugins . onError ( t ) ; return ; } lazySet ( TERMINATED ) ; downstream . onError ( t ) ; }

Complete the target with an error signal.
@param t the Throwable to signal, not null (not verified)

Complete the target with an error signal .


public final void complete() {
        int state = get();
        if ((state & (FUSED_READY | FUSED_CONSUMED | TERMINATED | DISPOSED)) != 0) {
            return;
        }
        lazySet(TERMINATED);
        downstream.onComplete();
    }

public final void complete ( ) { int state = get ( ) ; if ( ( state & ( FUSED_READY | FUSED_CONSUMED | TERMINATED | DISPOSED ) ) != 0 ) { return ; } lazySet ( TERMINATED ) ; downstream . onComplete ( ) ; }


@CheckReturnValue
    @BackpressureSupport(BackpressureKind.FULL)
    @SchedulerSupport(SchedulerSupport.NONE)
    public final <R> Flowable<R> concatMapDelayError(Function<? super T, ? extends Publisher<? extends R>> mapper) {
        return concatMapDelayError(mapper, 2, true);
    }

@ CheckReturnValue @ BackpressureSupport ( BackpressureKind . FULL ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final < R > Flowable < R > concatMapDelayError ( Function < ? super T , ? extends Publisher < ? extends R > > mapper ) { return concatMapDelayError ( mapper , 2 , true ) ; }

Maps each of the items into a Publisher, subscribes to them one after the other,
one at a time and emits their values in order
while delaying any error from either this or any of the inner Publishers
till all of them terminate.

Backpressure:

The operator honors backpressure from downstream. Both this and the inner {@code Publisher}s are
expected to honor backpressure as well. If the source {@code Publisher} violates the rule, the operator will
signal a {@code MissingBackpressureException}. If any of the inner {@code Publisher}s doesn't honor
backpressure, that may throw an {@code IllegalStateException} when that
{@code Publisher} completes.

Scheduler:

{@code concatMapDelayError} does not operate by default on a particular {@link Scheduler}.

@param <R> the result value type
@param mapper the function that maps the items of this Publisher into the inner Publishers.
@return the new Publisher instance with the concatenation behavior

Maps each of the items into a Publisher subscribes to them one after the other one at a time and emits their values in order while delaying any error from either this or any of the inner Publishers till all of them terminate .


@CheckReturnValue
    @BackpressureSupport(BackpressureKind.FULL)
    @SchedulerSupport(SchedulerSupport.NONE)
    public final <U> Flowable<U> concatMapIterable(Function<? super T, ? extends Iterable<? extends U>> mapper) {
        return concatMapIterable(mapper, 2);
    }

@ CheckReturnValue @ BackpressureSupport ( BackpressureKind . FULL ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final < U > Flowable < U > concatMapIterable ( Function < ? super T , ? extends Iterable < ? extends U > > mapper ) { return concatMapIterable ( mapper , 2 ) ; }

Returns a Flowable that concatenate each item emitted by the source Publisher with the values in an
Iterable corresponding to that item that is generated by a selector.

Backpressure:

The operator honors backpressure from downstream. The source {@code Publisher}s is
expected to honor backpressure as well. If the source {@code Publisher} violates the rule, the operator will
signal a {@code MissingBackpressureException}.

Scheduler:

{@code concatMapIterable} does not operate by default on a particular {@link Scheduler}.

@param
the type of item emitted by the resulting Publisher
@param mapper
a function that returns an Iterable sequence of values for when given an item emitted by the
source Publisher
@return a Flowable that emits the results of concatenating the items emitted by the source Publisher with
the values in the Iterables corresponding to those items, as generated by {@code collectionSelector}
@see ReactiveX operators documentation: FlatMap

Returns a Flowable that concatenate each item emitted by the source Publisher with the values in an Iterable corresponding to that item that is generated by a selector .


@CheckReturnValue
    @NonNull
    @BackpressureSupport(BackpressureKind.FULL)
    @SchedulerSupport(SchedulerSupport.NONE)
    public final Flowable<T> sorted(Comparator<? super T> sortFunction) {
        ObjectHelper.requireNonNull(sortFunction, "sortFunction");
        return toList().toFlowable().map(Functions.listSorter(sortFunction)).flatMapIterable(Functions.<List<T>>identity());
    }

@ CheckReturnValue @ NonNull @ BackpressureSupport ( BackpressureKind . FULL ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final Flowable < T > sorted ( Comparator < ? super T > sortFunction ) { ObjectHelper . requireNonNull ( sortFunction , "sortFunction" ) ; return toList ( ) . toFlowable ( ) . map ( Functions . listSorter ( sortFunction ) ) . flatMapIterable ( Functions . < List < T > > identity ( ) ) ; }

Returns a Flowable that emits the events emitted by source Publisher, in a
sorted order based on a specified comparison function.

Note that calling {@code sorted} with long, non-terminating or infinite sources
might cause {@link OutOfMemoryError}

Backpressure:

The operator honors backpressure from downstream and consumes the source {@code Publisher} in an
unbounded manner (i.e., without applying backpressure to it).

Scheduler:

{@code sorted} does not operate by default on a particular {@link Scheduler}.

@param sortFunction
a function that compares two items emitted by the source Publisher and returns an Integer
that indicates their sort order
@return a Flowable that emits the items emitted by the source Publisher in sorted order

Returns a Flowable that emits the events emitted by source Publisher in a sorted order based on a specified comparison function .


public PerfAsyncConsumer await(int count) {
        if (count <= 1000) {
            while (getCount() != 0) { }
        } else {
            try {
                await();
            } catch (InterruptedException ex) {
                throw new RuntimeException(ex);
            }
        }
        return this;
    }

public PerfAsyncConsumer await ( int count ) { if ( count <= 1000 ) { while ( getCount ( ) != 0 ) { } } else { try { await ( ) ; } catch ( InterruptedException ex ) { throw new RuntimeException ( ex ) ; } } return this ; }

Wait for the terminal signal.
@param count if less than 1001, a spin-wait is used
@return this


protected final void request(long n) {
        Subscription s = this.upstream;
        if (s != null) {
            s.request(n);
        }
    }

protected final void request ( long n ) { Subscription s = this . upstream ; if ( s != null ) { s . request ( n ) ; } }

Requests from the upstream Subscription.
@param n the request amount, positive

Requests from the upstream Subscription .


boolean add(PublishDisposable<T> ps) {
        for (;;) {
            PublishDisposable<T>[] a = subscribers.get();
            if (a == TERMINATED) {
                return false;
            }

            int n = a.length;
            @SuppressWarnings("unchecked")
            PublishDisposable<T>[] b = new PublishDisposable[n + 1];
            System.arraycopy(a, 0, b, 0, n);
            b[n] = ps;

            if (subscribers.compareAndSet(a, b)) {
                return true;
            }
        }
    }

boolean add ( PublishDisposable < T > ps ) { for ( ; ; ) { PublishDisposable < T > [ ] a = subscribers . get ( ) ; if ( a == TERMINATED ) { return false ; } int n = a . length ; @ SuppressWarnings ( "unchecked" ) PublishDisposable < T > [ ] b = new PublishDisposable [ n + 1 ] ; System . arraycopy ( a , 0 , b , 0 , n ) ; b [ n ] = ps ; if ( subscribers . compareAndSet ( a , b ) ) { return true ; } } }

Tries to add the given subscriber to the subscribers array atomically
or returns false if the subject has terminated.
@param ps the subscriber to add
@return true if successful, false if the subject has terminated

Tries to add the given subscriber to the subscribers array atomically or returns false if the subject has terminated .


@SuppressWarnings("unchecked")
    void remove(PublishDisposable<T> ps) {
        for (;;) {
            PublishDisposable<T>[] a = subscribers.get();
            if (a == TERMINATED || a == EMPTY) {
                return;
            }

            int n = a.length;
            int j = -1;
            for (int i = 0; i < n; i++) {
                if (a[i] == ps) {
                    j = i;
                    break;
                }
            }

            if (j < 0) {
                return;
            }

            PublishDisposable<T>[] b;

            if (n == 1) {
                b = EMPTY;
            } else {
                b = new PublishDisposable[n - 1];
                System.arraycopy(a, 0, b, 0, j);
                System.arraycopy(a, j + 1, b, j, n - j - 1);
            }
            if (subscribers.compareAndSet(a, b)) {
                return;
            }
        }
    }

@ SuppressWarnings ( "unchecked" ) void remove ( PublishDisposable < T > ps ) { for ( ; ; ) { PublishDisposable < T > [ ] a = subscribers . get ( ) ; if ( a == TERMINATED || a == EMPTY ) { return ; } int n = a . length ; int j = - 1 ; for ( int i = 0 ; i < n ; i ++ ) { if ( a [ i ] == ps ) { j = i ; break ; } } if ( j < 0 ) { return ; } PublishDisposable < T > [ ] b ; if ( n == 1 ) { b = EMPTY ; } else { b = new PublishDisposable [ n - 1 ] ; System . arraycopy ( a , 0 , b , 0 , j ) ; System . arraycopy ( a , j + 1 , b , j , n - j - 1 ) ; } if ( subscribers . compareAndSet ( a , b ) ) { return ; } } }

Atomically removes the given subscriber if it is subscribed to the subject.
@param ps the subject to remove

Atomically removes the given subscriber if it is subscribed to the subject .


public static <T> ConnectableFlowable<T> observeOn(final ConnectableFlowable<T> cf, final Scheduler scheduler) {
        final Flowable<T> flowable = cf.observeOn(scheduler);
        return RxJavaPlugins.onAssembly(new ConnectableFlowableReplay<T>(cf, flowable));
    }

public static < T > ConnectableFlowable < T > observeOn ( final ConnectableFlowable < T > cf , final Scheduler scheduler ) { final Flowable < T > flowable = cf . observeOn ( scheduler ) ; return RxJavaPlugins . onAssembly ( new ConnectableFlowableReplay < T > ( cf , flowable ) ) ; }

Child Subscribers will observe the events of the ConnectableObservable on the
specified scheduler.
@param <T> the value type
@param cf the ConnectableFlowable to wrap
@param scheduler the target scheduler
@return the new ConnectableObservable instance

Child Subscribers will observe the events of the ConnectableObservable on the specified scheduler .


static <ResponseT, ReturnT> HttpServiceMethod<ResponseT, ReturnT> parseAnnotations(
      Retrofit retrofit, Method method, RequestFactory requestFactory) {
    boolean isKotlinSuspendFunction = requestFactory.isKotlinSuspendFunction;
    boolean continuationWantsResponse = false;
    boolean continuationBodyNullable = false;

    Annotation[] annotations = method.getAnnotations();
    Type adapterType;
    if (isKotlinSuspendFunction) {
      Type[] parameterTypes = method.getGenericParameterTypes();
      Type responseType = Utils.getParameterLowerBound(0,
          (ParameterizedType) parameterTypes[parameterTypes.length - 1]);
      if (getRawType(responseType) == Response.class && responseType instanceof ParameterizedType) {
        // Unwrap the actual body type from Response<T>.
        responseType = Utils.getParameterUpperBound(0, (ParameterizedType) responseType);
        continuationWantsResponse = true;
      } else {
        // TODO figure out if type is nullable or not
        // Metadata metadata = method.getDeclaringClass().getAnnotation(Metadata.class)
        // Find the entry for method
        // Determine if return type is nullable or not
      }

      adapterType = new Utils.ParameterizedTypeImpl(null, Call.class, responseType);
      annotations = SkipCallbackExecutorImpl.ensurePresent(annotations);
    } else {
      adapterType = method.getGenericReturnType();
    }

    CallAdapter<ResponseT, ReturnT> callAdapter =
        createCallAdapter(retrofit, method, adapterType, annotations);
    Type responseType = callAdapter.responseType();
    if (responseType == okhttp3.Response.class) {
      throw methodError(method, "'"
          + getRawType(responseType).getName()
          + "' is not a valid response body type. Did you mean ResponseBody?");
    }
    if (responseType == Response.class) {
      throw methodError(method, "Response must include generic type (e.g., Response<String>)");
    }
    // TODO support Unit for Kotlin?
    if (requestFactory.httpMethod.equals("HEAD") && !Void.class.equals(responseType)) {
      throw methodError(method, "HEAD method must use Void as response type.");
    }

    Converter<ResponseBody, ResponseT> responseConverter =
        createResponseConverter(retrofit, method, responseType);

    okhttp3.Call.Factory callFactory = retrofit.callFactory;
    if (!isKotlinSuspendFunction) {
      return new CallAdapted<>(requestFactory, callFactory, responseConverter, callAdapter);
    } else if (continuationWantsResponse) {
      //noinspection unchecked Kotlin compiler guarantees ReturnT to be Object.
      return (HttpServiceMethod<ResponseT, ReturnT>) new SuspendForResponse<>(requestFactory,
          callFactory, responseConverter, (CallAdapter<ResponseT, Call<ResponseT>>) callAdapter);
    } else {
      //noinspection unchecked Kotlin compiler guarantees ReturnT to be Object.
      return (HttpServiceMethod<ResponseT, ReturnT>) new SuspendForBody<>(requestFactory,
          callFactory, responseConverter, (CallAdapter<ResponseT, Call<ResponseT>>) callAdapter,
          continuationBodyNullable);
    }
  }

Inspects the annotations on an interface method to construct a reusable service method that
speaks HTTP. This requires potentially-expensive reflection so it is best to build each service
method only once and reuse it.

Inspects the annotations on an interface method to construct a reusable service method that speaks HTTP . This requires potentially - expensive reflection so it is best to build each service method only once and reuse it .


public void setDelay(long amount, TimeUnit unit) {
    if (amount < 0) {
      throw new IllegalArgumentException("Amount must be positive value.");
    }
    this.delayMs = unit.toMillis(amount);
  }

public
void
setDelay
(
long
amount
,
TimeUnit
unit
)
{
if
(
amount
<
0
)
{
throw
new
IllegalArgumentException
(
"Amount must be positive value."
)
;
}
this
.
delayMs
=
unit
.
toMillis
(
amount
)
;
}


public Response<?> createErrorResponse() {
    Response<?> call;
    try {
      call = errorFactory.call();
    } catch (Exception e) {
      throw new IllegalStateException("Error factory threw an exception.", e);
    }
    if (call == null) {
      throw new IllegalStateException("Error factory returned null.");
    }
    if (call.isSuccessful()) {
      throw new IllegalStateException("Error factory returned successful response.");
    }
    return call;
  }

The HTTP error to be used when an error is triggered.

The HTTP error to be used when an error is triggered .


public long calculateDelay(TimeUnit unit) {
    float delta = variancePercent / 100f; // e.g., 20 / 100f == 0.2f
    float lowerBound = 1f - delta; // 0.2f --> 0.8f
    float upperBound = 1f + delta; // 0.2f --> 1.2f
    float bound = upperBound - lowerBound; // 1.2f - 0.8f == 0.4f
    float delayPercent = lowerBound + (random.nextFloat() * bound); // 0.8 + (rnd * 0.4)
    long callDelayMs = (long) (delayMs * delayPercent);
    return MILLISECONDS.convert(callDelayMs, unit);
  }

public
long
calculateDelay
(
TimeUnit
unit
)
{
float
delta
=
variancePercent
/
100f
;
// e.g., 20 / 100f == 0.2f
float
lowerBound
=
1f
delta
;
// 0.2f --> 0.8f
float
upperBound
=
1f
+
delta
;
// 0.2f --> 1.2f
float
bound
=
upperBound
lowerBound
;
// 1.2f - 0.8f == 0.4f
float
delayPercent
=
lowerBound
+
(
random
.
nextFloat
(
)
*
bound
)
;
// 0.8 + (rnd * 0.4)
long
callDelayMs
=
(
long
)
(
delayMs
*
delayPercent
)
;
return
MILLISECONDS
.
convert
(
callDelayMs
,
unit
)
;
}

Get the delay that should be used for delaying a response in accordance with configured
behavior.

Get the delay that should be used for delaying a response in accordance with configured behavior .


private void createSampleData(String username, String password) {
		Assert.notNull(documentDao, "DocumentDao required");
		Assert.hasText(username, "Username required");

		Authentication auth = new UsernamePasswordAuthenticationToken(username, password);

		try {
			// Set the SecurityContextHolder ThreadLocal so any subclasses
			// automatically know which user is operating
			SecurityContextHolder.getContext().setAuthentication(auth);

			// Create the home directory first
			Directory home = new Directory(username, Directory.ROOT_DIRECTORY);
			documentDao.create(home);
			addPermission(documentDao, home, username, LEVEL_GRANT_ADMIN);
			addPermission(documentDao, home, "ROLE_USER", LEVEL_GRANT_READ);
			createFiles(documentDao, home);

			// Now create the confidential directory
			Directory confid = new Directory("confidential", home);
			documentDao.create(confid);
			addPermission(documentDao, confid, "ROLE_USER", LEVEL_NEGATE_READ);
			createFiles(documentDao, confid);

			// Now create the shared directory
			Directory shared = new Directory("shared", home);
			documentDao.create(shared);
			addPermission(documentDao, shared, "ROLE_USER", LEVEL_GRANT_READ);
			addPermission(documentDao, shared, "ROLE_USER", LEVEL_GRANT_WRITE);
			createFiles(documentDao, shared);
		}
		finally {
			// Clear the SecurityContextHolder ThreadLocal so future calls are
			// guaranteed to be clean
			SecurityContextHolder.clearContext();
		}
	}

Creates a directory for the user, and a series of sub-directories. The root
directory is the parent for the user directory. The sub-directories are
"confidential" and "shared". The ROLE_USER will be given read and write access to
"shared".

Creates a directory for the user and a series of sub - directories . The root directory is the parent for the user directory . The sub - directories are confidential and shared . The ROLE_USER will be given read and write access to shared .


private static HttpMethod valueOf(String method) {
		try {
			return HttpMethod.valueOf(method);
		}
		catch (IllegalArgumentException e) {
		}

		return null;
	}

private static HttpMethod valueOf ( String method ) { try { return HttpMethod . valueOf ( method ) ; } catch ( IllegalArgumentException e ) { } return null ; }

Provides a save way of obtaining the HttpMethod from a String. If the method is
invalid, returns null.

@param method the HTTP method to use.

@return the HttpMethod or null if method is invalid.

Provides a save way of obtaining the HttpMethod from a String . If the method is invalid returns null .


@Override
	public DirContextOperations searchForUser(String username) {
		if (logger.isDebugEnabled()) {
			logger.debug("Searching for user '" + username + "', with user search "
					+ this);
		}

		SpringSecurityLdapTemplate template = new SpringSecurityLdapTemplate(
				contextSource);

		template.setSearchControls(searchControls);

		try {

			return template.searchForSingleEntry(searchBase, searchFilter,
					new String[] { username });

		}
		catch (IncorrectResultSizeDataAccessException notFound) {
			if (notFound.getActualSize() == 0) {
				throw new UsernameNotFoundException("User " + username
						+ " not found in directory.");
			}
			// Search should never return multiple results if properly configured, so just
			// rethrow
			throw notFound;
		}
	}

Return the LdapUserDetails containing the user's information

@param username the username to search for.

@return An LdapUserDetails object containing the details of the located user's
directory entry

@throws UsernameNotFoundException if no matching entry is found.

Return the LdapUserDetails containing the user s information


public String encode(CharSequence rawPassword) {
		String salt = PREFIX + this.saltGenerator.generateKey() + SUFFIX;
		return digest(salt, rawPassword);
	}

public String encode ( CharSequence rawPassword ) { String salt = PREFIX + this . saltGenerator . generateKey ( ) + SUFFIX ; return digest ( salt , rawPassword ) ; }

Encodes the rawPass using a MessageDigest. If a salt is specified it will be merged
with the password before encoding.

@param rawPassword The plain text password
@return Hex string of password digest (or base64 encoded string if
encodeHashAsBase64 is enabled.

Encodes the rawPass using a MessageDigest . If a salt is specified it will be merged with the password before encoding .


public boolean matches(CharSequence rawPassword, String encodedPassword) {
		String salt = extractSalt(encodedPassword);
		String rawPasswordEncoded = digest(salt, rawPassword);
		return PasswordEncoderUtils.equals(encodedPassword.toString(), rawPasswordEncoded);
	}

public boolean matches ( CharSequence rawPassword , String encodedPassword ) { String salt = extractSalt ( encodedPassword ) ; String rawPasswordEncoded = digest ( salt , rawPassword ) ; return PasswordEncoderUtils . equals ( encodedPassword . toString ( ) , rawPasswordEncoded ) ; }

Takes a previously encoded password and compares it with a rawpassword after mixing
in the salt and encoding that value

@param rawPassword plain text password
@param encodedPassword previously encoded password
@return true or false


private static void performVersionChecks(String minSpringVersion) {
		if (minSpringVersion == null) {
			return;
		}
		// Check Spring Compatibility
		String springVersion = SpringVersion.getVersion();
		String version = getVersion();

		if (disableChecks(springVersion, version)) {
			return;
		}

		logger.info("You are running with Spring Security Core " + version);
		if (new ComparableVersion(springVersion)
				.compareTo(new ComparableVersion(minSpringVersion)) < 0) {
			logger.warn("**** You are advised to use Spring " + minSpringVersion
					+ " or later with this version. You are running: " + springVersion);
		}
	}

Perform version checks with specific min Spring Version

@param minSpringVersion


private static boolean disableChecks(String springVersion,
			String springSecurityVersion) {
		if (springVersion == null || springVersion.equals(springSecurityVersion)) {
			return true;
		}
		return Boolean.getBoolean(DISABLE_CHECKS);
	}

private static boolean disableChecks ( String springVersion , String springSecurityVersion ) { if ( springVersion == null || springVersion . equals ( springSecurityVersion ) ) { return true ; } return Boolean . getBoolean ( DISABLE_CHECKS ) ; }

Disable if springVersion and springSecurityVersion are the same to allow working
with Uber Jars.

@param springVersion
@param springSecurityVersion
@return

Disable if springVersion and springSecurityVersion are the same to allow working with Uber Jars .


private static String getSpringVersion() {
		Properties properties = new Properties();
		try {
			properties.load(SpringSecurityCoreVersion.class.getClassLoader().getResourceAsStream("META-INF/spring-security.versions"));
		} catch (IOException | NullPointerException e) {
			return null;
		}
		return properties.getProperty("org.springframework:spring-core");
	}

private static String getSpringVersion ( ) { Properties properties = new Properties ( ) ; try { properties . load ( SpringSecurityCoreVersion . class . getClassLoader ( ) . getResourceAsStream ( "META-INF/spring-security.versions" ) ) ; } catch ( IOException | NullPointerException e ) { return null ; } return properties . getProperty ( "org.springframework:spring-core" ) ; }

Loads the spring version or null if it cannot be found.
@return

Loads the spring version or null if it cannot be found .


public AttributeExchangeConfigurer attributeExchange(String identifierPattern) {
		AttributeExchangeConfigurer attributeExchangeConfigurer = new AttributeExchangeConfigurer(
				identifierPattern);
		this.attributeExchangeConfigurers.add(attributeExchangeConfigurer);
		return attributeExchangeConfigurer;
	}

public AttributeExchangeConfigurer attributeExchange ( String identifierPattern ) { AttributeExchangeConfigurer attributeExchangeConfigurer = new AttributeExchangeConfigurer ( identifierPattern ) ; this . attributeExchangeConfigurers . add ( attributeExchangeConfigurer ) ; return attributeExchangeConfigurer ; }

Sets up OpenID attribute exchange for OpenID's matching the specified pattern.

@param identifierPattern the regular expression for matching on OpenID's (i.e.
"https://www.google.com/.*", ".*yahoo.com.*", etc)
@return a {@link AttributeExchangeConfigurer} for further customizations of the
attribute exchange

Sets up OpenID attribute exchange for OpenID s matching the specified pattern .


public OAuth2ClientConfigurer<HttpSecurity> oauth2Client() throws Exception {
		OAuth2ClientConfigurer<HttpSecurity> configurer = getOrApply(new OAuth2ClientConfigurer<>());
		this.postProcess(configurer);
		return configurer;
	}

public OAuth2ClientConfigurer < HttpSecurity > oauth2Client ( ) throws Exception { OAuth2ClientConfigurer < HttpSecurity > configurer = getOrApply ( new OAuth2ClientConfigurer <> ( ) ) ; this . postProcess ( configurer ) ; return configurer ; }

Configures OAuth 2.0 Client support.

@since 5.1
@see OAuth 2.0 Authorization Framework
@return the {@link OAuth2ClientConfigurer} for further customizations
@throws Exception


public OAuth2ResourceServerConfigurer<HttpSecurity> oauth2ResourceServer() throws Exception {
		OAuth2ResourceServerConfigurer<HttpSecurity> configurer = getOrApply(new OAuth2ResourceServerConfigurer<>(getContext()));
		this.postProcess(configurer);
		return configurer;
	}

public OAuth2ResourceServerConfigurer < HttpSecurity > oauth2ResourceServer ( ) throws Exception { OAuth2ResourceServerConfigurer < HttpSecurity > configurer = getOrApply ( new OAuth2ResourceServerConfigurer <> ( getContext ( ) ) ) ; this . postProcess ( configurer ) ; return configurer ; }

Configures OAuth 2.0 Resource Server support.

@since 5.1
@see OAuth 2.0 Authorization Framework
@return the {@link OAuth2ResourceServerConfigurer} for further customizations
@throws Exception

Configures OAuth 2 . 0 Resource Server support .


public ChannelSecurityConfigurer<HttpSecurity>.ChannelRequestMatcherRegistry requiresChannel()
			throws Exception {
		ApplicationContext context = getContext();
		return getOrApply(new ChannelSecurityConfigurer<>(context))
				.getRegistry();
	}

public ChannelSecurityConfigurer < HttpSecurity > . ChannelRequestMatcherRegistry requiresChannel ( ) throws Exception { ApplicationContext context = getContext ( ) ; return getOrApply ( new ChannelSecurityConfigurer <> ( context ) ) . getRegistry ( ) ; }

Configures channel security. In order for this configuration to be useful at least
one mapping to a required channel must be provided.

Example Configuration

The example below demonstrates how to require HTTPs for every request. Only
requiring HTTPS for some requests is supported, but not recommended since an
application that allows for HTTP introduces many security vulnerabilities. For one
such example, read about Firesheep.

@Configuration
@EnableWebSecurity
public class ChannelSecurityConfig extends WebSecurityConfigurerAdapter {

@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/**").hasRole("USER").and().formLogin()
.and().requiresChannel().anyRequest().requiresSecure();
}

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser("user").password("password").roles("USER");
}
}

@return the {@link ChannelSecurityConfigurer} for further customizations
@throws Exception

Configures channel security . In order for this configuration to be useful at least one mapping to a required channel must be provided .


public boolean compare(final String dn, final String attributeName, final Object value) {
		final String comparisonFilter = "(" + attributeName + "={0})";

		class LdapCompareCallback implements ContextExecutor {

			public Object executeWithContext(DirContext ctx) throws NamingException {
				SearchControls ctls = new SearchControls();
				ctls.setReturningAttributes(NO_ATTRS);
				ctls.setSearchScope(SearchControls.OBJECT_SCOPE);

				NamingEnumeration<SearchResult> results = ctx.search(dn,
						comparisonFilter, new Object[] { value }, ctls);

				Boolean match = Boolean.valueOf(results.hasMore());
				LdapUtils.closeEnumeration(results);

				return match;
			}
		}

		Boolean matches = (Boolean) executeReadOnly(new LdapCompareCallback());

		return matches.booleanValue();
	}

public boolean compare ( final String dn , final String attributeName , final Object value ) { final String comparisonFilter = "(" + attributeName + "={0})" ; class LdapCompareCallback implements ContextExecutor { public Object executeWithContext ( DirContext ctx ) throws NamingException { SearchControls ctls = new SearchControls ( ) ; ctls . setReturningAttributes ( NO_ATTRS ) ; ctls . setSearchScope ( SearchControls . OBJECT_SCOPE ) ; NamingEnumeration < SearchResult > results = ctx . search ( dn , comparisonFilter , new Object [ ] { value } , ctls ) ; Boolean match = Boolean . valueOf ( results . hasMore ( ) ) ; LdapUtils . closeEnumeration ( results ) ; return match ; } } Boolean matches = ( Boolean ) executeReadOnly ( new LdapCompareCallback ( ) ) ; return matches . booleanValue ( ) ; }

Performs an LDAP compare operation of the value of an attribute for a particular
directory entry.

@param dn the entry who's attribute is to be used
@param attributeName the attribute who's value we want to compare
@param value the value to be checked against the directory value

@return true if the supplied value matches that in the directory

Performs an LDAP compare operation of the value of an attribute for a particular directory entry .


public DirContextOperations retrieveEntry(final String dn,
			final String[] attributesToRetrieve) {

		return (DirContextOperations) executeReadOnly(new ContextExecutor() {
			public Object executeWithContext(DirContext ctx) throws NamingException {
				Attributes attrs = ctx.getAttributes(dn, attributesToRetrieve);

				// Object object = ctx.lookup(LdapUtils.getRelativeName(dn, ctx));

				return new DirContextAdapter(attrs, new DistinguishedName(dn),
						new DistinguishedName(ctx.getNameInNamespace()));
			}
		});
	}

Composes an object from the attributes of the given DN.

@param dn the directory entry which will be read
@param attributesToRetrieve the named attributes which will be retrieved from the
directory entry.

@return the object created by the mapper

Composes an object from the attributes of the given DN .


public Set<String> searchForSingleAttributeValues(final String base,
			final String filter, final Object[] params, final String attributeName) {
		String[] attributeNames = new String[] { attributeName };
		Set<Map<String, List<String>>> multipleAttributeValues = searchForMultipleAttributeValues(
				base, filter, params, attributeNames);
		Set<String> result = new HashSet<>();
		for (Map<String, List<String>> map : multipleAttributeValues) {
			List<String> values = map.get(attributeName);
			if (values != null) {
				result.addAll(values);
			}
		}
		return result;
	}

public Set < String > searchForSingleAttributeValues ( final String base , final String filter , final Object [ ] params , final String attributeName ) { String [ ] attributeNames = new String [ ] { attributeName } ; Set < Map < String , List < String > > > multipleAttributeValues = searchForMultipleAttributeValues ( base , filter , params , attributeNames ) ; Set < String > result = new HashSet <> ( ) ; for ( Map < String , List < String > > map : multipleAttributeValues ) { List < String > values = map . get ( attributeName ) ; if ( values != null ) { result . addAll ( values ) ; } } return result ; }

Performs a search using the supplied filter and returns the union of the values of
the named attribute found in all entries matched by the search. Note that one
directory entry may have several values for the attribute. Intended for role
searches and similar scenarios.

@param base the DN to search in
@param filter search filter to use
@param params the parameters to substitute in the search filter
@param attributeName the attribute who's values are to be retrieved.

@return the set of String values for the attribute as a union of the values found
in all the matching entries.

Performs a search using the supplied filter and returns the union of the values of the named attribute found in all entries matched by the search . Note that one directory entry may have several values for the attribute . Intended for role searches and similar scenarios .


public Set<Map<String, List<String>>> searchForMultipleAttributeValues(
			final String base, final String filter, final Object[] params,
			final String[] attributeNames) {
		// Escape the params acording to RFC2254
		Object[] encodedParams = new String[params.length];

		for (int i = 0; i < params.length; i++) {
			encodedParams[i] = LdapEncoder.filterEncode(params[i].toString());
		}

		String formattedFilter = MessageFormat.format(filter, encodedParams);
		logger.debug("Using filter: " + formattedFilter);

		final HashSet<Map<String, List<String>>> set = new HashSet<Map<String, List<String>>>();

		ContextMapper roleMapper = new ContextMapper() {
			public Object mapFromContext(Object ctx) {
				DirContextAdapter adapter = (DirContextAdapter) ctx;
				Map<String, List<String>> record = new HashMap<String, List<String>>();
				if (attributeNames == null || attributeNames.length == 0) {
					try {
						for (NamingEnumeration ae = adapter.getAttributes().getAll(); ae
								.hasMore();) {
							Attribute attr = (Attribute) ae.next();
							extractStringAttributeValues(adapter, record, attr.getID());
						}
					}
					catch (NamingException x) {
						org.springframework.ldap.support.LdapUtils
								.convertLdapException(x);
					}
				}
				else {
					for (String attributeName : attributeNames) {
						extractStringAttributeValues(adapter, record, attributeName);
					}
				}
				record.put(DN_KEY, Arrays.asList(getAdapterDN(adapter)));
				set.add(record);
				return null;
			}
		};

		SearchControls ctls = new SearchControls();
		ctls.setSearchScope(searchControls.getSearchScope());
		ctls.setReturningAttributes(attributeNames != null && attributeNames.length > 0 ? attributeNames
				: null);

		search(base, formattedFilter, ctls, roleMapper);

		return set;
	}

Performs a search using the supplied filter and returns the values of each named
attribute found in all entries matched by the search. Note that one directory entry
may have several values for the attribute. Intended for role searches and similar
scenarios.

@param base the DN to search in
@param filter search filter to use
@param params the parameters to substitute in the search filter
@param attributeNames the attributes' values that are to be retrieved.

@return the set of String values for each attribute found in all the matching
entries. The attribute name is the key for each set of values. In addition each map
contains the DN as a String with the key predefined key {@link #DN_KEY}.

Performs a search using the supplied filter and returns the values of each named attribute found in all entries matched by the search . Note that one directory entry may have several values for the attribute . Intended for role searches and similar scenarios .


public static DirContextOperations searchForSingleEntryInternal(DirContext ctx,
			SearchControls searchControls, String base, String filter, Object[] params)
			throws NamingException {
		final DistinguishedName ctxBaseDn = new DistinguishedName(
				ctx.getNameInNamespace());
		final DistinguishedName searchBaseDn = new DistinguishedName(base);
		final NamingEnumeration<SearchResult> resultsEnum = ctx.search(searchBaseDn,
				filter, params, buildControls(searchControls));

		if (logger.isDebugEnabled()) {
			logger.debug("Searching for entry under DN '" + ctxBaseDn + "', base = '"
					+ searchBaseDn + "', filter = '" + filter + "'");
		}

		Set<DirContextOperations> results = new HashSet<>();
		try {
			while (resultsEnum.hasMore()) {
				SearchResult searchResult = resultsEnum.next();
				DirContextAdapter dca = (DirContextAdapter) searchResult.getObject();
				Assert.notNull(dca,
						"No object returned by search, DirContext is not correctly configured");

				if (logger.isDebugEnabled()) {
					logger.debug("Found DN: " + dca.getDn());
				}
				results.add(dca);
			}
		}
		catch (PartialResultException e) {
			LdapUtils.closeEnumeration(resultsEnum);
			logger.info("Ignoring PartialResultException");
		}

		if (results.size() == 0) {
			throw new IncorrectResultSizeDataAccessException(1, 0);
		}

		if (results.size() > 1) {
			throw new IncorrectResultSizeDataAccessException(1, results.size());
		}

		return results.iterator().next();
	}

Internal method extracted to avoid code duplication in AD search.

Internal method extracted to avoid code duplication in AD search .


private static SearchControls buildControls(SearchControls originalControls) {
		return new SearchControls(originalControls.getSearchScope(),
				originalControls.getCountLimit(), originalControls.getTimeLimit(),
				originalControls.getReturningAttributes(), RETURN_OBJECT,
				originalControls.getDerefLinkFlag());
	}

private static SearchControls buildControls ( SearchControls originalControls ) { return new SearchControls ( originalControls . getSearchScope ( ) , originalControls . getCountLimit ( ) , originalControls . getTimeLimit ( ) , originalControls . getReturningAttributes ( ) , RETURN_OBJECT , originalControls . getDerefLinkFlag ( ) ) ; }

We need to make sure the search controls has the return object flag set to true, in
order for the search to return DirContextAdapter instances.
@param originalControls
@return

We need to make sure the search controls has the return object flag set to true in order for the search to return DirContextAdapter instances .


private void lookupPrimaryKeys(final Map<Serializable, Acl> acls,
			final Set<Long> findNow, final List<Sid> sids) {
		Assert.notNull(acls, "ACLs are required");
		Assert.notEmpty(findNow, "Items to find now required");

		String sql = computeRepeatingSql(lookupPrimaryKeysWhereClause, findNow.size());

		Set<Long> parentsToLookup = jdbcTemplate.query(sql,
				new PreparedStatementSetter() {
					public void setValues(PreparedStatement ps) throws SQLException {
						int i = 0;

						for (Long toFind : findNow) {
							i++;
							ps.setLong(i, toFind);
						}
					}
				}, new ProcessResultSet(acls, sids));

		// Lookup the parents, now that our JdbcTemplate has released the database
		// connection (SEC-547)
		if (parentsToLookup.size() > 0) {
			lookupPrimaryKeys(acls, parentsToLookup, sids);
		}
	}

Locates the primary key IDs specified in "findNow", adding AclImpl instances with
StubAclParents to the "acls" Map.

@param acls the AclImpls (with StubAclParents)
@param findNow Long-based primary keys to retrieve
@param sids

Locates the primary key IDs specified in findNow adding AclImpl instances with StubAclParents to the acls Map .


public PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails buildDetails(
			HttpServletRequest context) {

		Collection<String> j2eeUserRoles = getUserRoles(context);
		Collection<? extends GrantedAuthority> userGas = j2eeUserRoles2GrantedAuthoritiesMapper
				.getGrantedAuthorities(j2eeUserRoles);

		if (logger.isDebugEnabled()) {
			logger.debug("J2EE roles [" + j2eeUserRoles
					+ "] mapped to Granted Authorities: [" + userGas + "]");
		}

		PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails result = new PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails(
				context, userGas);

		return result;
	}

Builds the authentication details object.

@see org.springframework.security.authentication.AuthenticationDetailsSource#buildDetails(Object)

Builds the authentication details object .