rx.exceptions.OnErrorThrowable Java Examples

The following examples show how to use rx.exceptions.OnErrorThrowable. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Transformers.java    From mobius with Apache License 2.0 6 votes vote down vote up
/**
 * Creates an {@link Transformer} that will flatten the provided {@link Action0} into the stream
 * as a {@link Completable} every time it receives an effect from the upstream effects observable.
 * This Completable will be subscribed on the specified {@link Scheduler}. This will result in
 * calling the provided Action on the specified scheduler every time an effect dispatched to the
 * created effect transformer.
 *
 * @param doEffect {@link Action0} to be run every time the effect is requested
 * @param scheduler the {@link Scheduler} that the action should be run on
 * @param <F> the type of Effect this transformer handles
 * @param <E> these transformers are for effects that do not result in any events; however, they
 *     still need to share the same Event type
 * @return a {@link Transformer} that can be used with an {@link SubtypeEffectHandlerBuilder}
 */
static <F, E> Transformer<F, E> fromAction(
    final Action0 doEffect, @Nullable final Scheduler scheduler) {
  return fromConsumer(
      new Action1<F>() {
        @Override
        public void call(F f) {
          try {
            doEffect.call();
          } catch (Exception e) {
            throw OnErrorThrowable.from(e);
          }
        }
      },
      scheduler);
}
 
Example #2
Source File: TestUtils.java    From Prana with Apache License 2.0 6 votes vote down vote up
public static String getResponse(HttpClientRequest<ByteBuf> request, HttpClient<ByteBuf, ByteBuf> client) {
    return client.submit(request).flatMap(new Func1<HttpClientResponse<ByteBuf>, Observable<String>>() {
        @Override
        public Observable<String> call(HttpClientResponse<ByteBuf> response) {
            return response.getContent().map(new Func1<ByteBuf, String>() {
                @Override
                public String call(ByteBuf byteBuf) {
                    return byteBuf.toString(Charset.defaultCharset());
                }
            });
        }
    }).onErrorFlatMap(new Func1<OnErrorThrowable, Observable<String>>() {
        @Override
        public Observable<String> call(OnErrorThrowable onErrorThrowable) {
            throw onErrorThrowable;
        }
    }).toBlocking().first();
}
 
Example #3
Source File: UserUtils.java    From divide with Apache License 2.0 6 votes vote down vote up
public static Observable<BackendUser> getAnonymousUser(Context context){
    final String id = UserUtils.getDeviceIdUnique(context);

    return BackendUser.signInInBackground(id,id).onErrorFlatMap(new Func1<OnErrorThrowable, Observable<? extends BackendUser>>() {
        @Override
        public Observable<? extends BackendUser> call(OnErrorThrowable onErrorThrowable) {
            return BackendUser.signUpInBackground(id,id,id);
        }
    }).map(new Func1<BackendUser, BackendUser>() {
        @Override
        public BackendUser call(BackendUser user) {
            user.put(ANONYMOUS_KEY,true);
            user.saveASync();
            return user;
        }
    });
}
 
Example #4
Source File: OperatorGroupBy.java    From mantis with Apache License 2.0 6 votes vote down vote up
@Override
public void onNext(T t) {
    try {
        final K key = keySelector.call(t);
        GroupState<K, T> group = groups.get(key);
        if (group == null) {
            // this group doesn't exist
            if (child.isUnsubscribed()) {
                // we have been unsubscribed on the outer so won't send any  more groups
                return;
            }
            group = createNewGroup(key);
        }
        emitItem(group, NotificationLite.next(t));
    } catch (Throwable e) {
        onError(OnErrorThrowable.addValueAsLastCause(e, t));
    }
}
 
Example #5
Source File: OperatorParallelMerge.java    From RxJavaParallel with Apache License 2.0 6 votes vote down vote up
private int drainAll() {
    int emitted = 0;
    // drain it all
    Object o;
    while ((o = q.poll()) != null) {
        if (q.isCompleted(o)) {
            parentSubscriber.completeInner(this);
        } else {
            try {
                if (!q.accept(o, parentSubscriber.actual)) {
                    emitted++;
                }
            } catch (Throwable e) {
                // special error handling due to complexity of merge
                onError(OnErrorThrowable.addValueAsLastCause(e, o));
            }
        }
    }
    return emitted;
}
 
Example #6
Source File: OperatorParallelMerge.java    From RxJavaParallel with Apache License 2.0 5 votes vote down vote up
private int drainRequested() {
    int emitted = 0;
    // drain what was requested
    long toEmit = producer.requested;
    Object o;
    for (int i = 0; i < toEmit; i++) {
        o = q.poll();
        if (o == null) {
            // no more items
            break;
        } else if (q.isCompleted(o)) {
            parentSubscriber.completeInner(this);
        } else {
            try {
                if (!q.accept(o, parentSubscriber.actual)) {
                    emitted++;
                }
            } catch (Throwable e) {
                // special error handling due to complexity of merge
                onError(OnErrorThrowable.addValueAsLastCause(e, o));
            }
        }
    }

    // decrement the number we emitted from outstanding requests
    MergeProducer.REQUESTED.getAndAdd(producer, -emitted);
    return emitted;
}
 
Example #7
Source File: HealthCheckHandler.java    From Prana with Apache License 2.0 5 votes vote down vote up
@Override
Observable<Void> handle(final Context context) {
    String externalHealthCheckURL = DynamicProperty.getInstance("prana.host.healthcheck.url")
            .getString(DEFAULT_HEALTHCHECK_ENDPOINT);
    context.setHeader("Content-type", DEFAULT_CONTENT_TYPE);
    if (Strings.isNullOrEmpty(externalHealthCheckURL)) {
        return context.sendSimple(DEFAULT_OK_HEALTH);
    } else {
        return getResponse(externalHealthCheckURL).flatMap(new Func1<HttpClientResponse<ByteBuf>, Observable<Void>>() {
            @Override
            public Observable<Void> call(HttpClientResponse<ByteBuf> response) {
                if (response.getStatus().code() == HttpResponseStatus.OK.code()) {
                    context.sendSimple(DEFAULT_OK_HEALTH);
                } else {
                    context.sendError(HttpResponseStatus.SERVICE_UNAVAILABLE, DEFAULT_FAIL_HEALTH);
                }
                return DEFAULT_NOOP_RESPONSE;
            }
        }).onErrorFlatMap(new Func1<OnErrorThrowable, Observable<Void>>() {
            @Override
            public Observable<Void> call(OnErrorThrowable onErrorThrowable) {
                context.sendError(HttpResponseStatus.SERVICE_UNAVAILABLE, DEFAULT_FAIL_HEALTH);
                return DEFAULT_NOOP_RESPONSE;
            }
        });
    }
}
 
Example #8
Source File: WampClient.java    From jawampa with Apache License 2.0 5 votes vote down vote up
/**
 * Performs a remote procedure call through the router.<br>
 * The function will return immediately, as the actual call will happen
 * asynchronously.<br>
 * This overload of the call function will automatically map the received
 * reply value into the specified Java type by using Jacksons object mapping
 * facilities.<br>
 * Only the first value in the array of positional arguments will be taken
 * into account for the transformation. If multiple return values are required
 * another overload of this function has to be used.<br>
 * If the expected return type is not {@link Void} but the return value array
 * contains no value or if the value in the array can not be deserialized into
 * the expected type the returned {@link Observable} will be completed with
 * an error.
 * @param procedure The name of the procedure to call. Must be a valid WAMP
 * Uri.
 * @param flags Additional call flags if any. This can be null.
 * @param returnValueClass The class of the expected return value. If the function
 * uses no return values Void should be used.
 * @param args The list of positional arguments for the remote procedure call.
 * These will be get serialized according to the Jackson library serializing
 * behavior.
 * @return An observable that provides a notification whether the call was
 * was successful and the return value. If the call is successful the
 * returned observable will be completed with a single value (the return value).
 * If the remote procedure call yields an error the observable will be completed
 * with an error.
 */
public <T> Observable<T> call(final String procedure, final EnumSet<CallFlags> flags,
                              final Class<T> returnValueClass, Object... args)
{
    return call(procedure, flags, ArgArrayBuilder.buildArgumentsArray(clientConfig.objectMapper(), args), null)
        .map(new Func1<Reply,T>() {
        @Override
        public T call(Reply reply) {
            if (returnValueClass == null || returnValueClass == Void.class) {
                // We don't need a return value
                return null;
            }
            
            if (reply.arguments == null || reply.arguments.size() < 1)
                throw OnErrorThrowable.from(new ApplicationError(ApplicationError.MISSING_RESULT));
                
            JsonNode resultNode = reply.arguments.get(0);
            if (resultNode.isNull()) return null;
            
            T result;
            try {
                result = clientConfig.objectMapper().convertValue(resultNode, returnValueClass);
            } catch (IllegalArgumentException e) {
                // The returned exception is an aggregate one. That's not too nice :(
                throw OnErrorThrowable.from(new ApplicationError(ApplicationError.INVALID_VALUE_TYPE));
            }
            return result;
        }
    });
}
 
Example #9
Source File: WampClient.java    From jawampa with Apache License 2.0 5 votes vote down vote up
/**
 * Returns an observable that allows to subscribe on the given topic.<br>
 * The actual subscription will only be made after subscribe() was called
 * on it.<br>
 * makeSubscriptionWithDetails will automatically transform the
 * received events data into the type eventClass and will therefore return
 * a mapped Observable of type EventDetails. It will only look at and transform the first
 * argument of the received events arguments, therefore it can only be used
 * for events that carry either a single or no argument.<br>
 * Received publications will be pushed to the Subscriber via it's
 * onNext method.<br>
 * The client can unsubscribe from the topic by calling unsubscribe() on
 * it's Subscription.<br>
 * If the connection closes onCompleted will be called.<br>
 * In case of errors during subscription onError will be called.
 * @param topic The topic to subscribe on.<br>
 * Must be valid WAMP URI.
 * @param flags Flags to indicate type of subscription. This cannot be null.
 * @param eventClass The class type into which the received event argument
 * should be transformed. E.g. use String.class to let the client try to
 * transform the first argument into a String and let the return value of
 * of the call be Observable&lt;EventDetails&lt;String&gt;&gt;.
 * @return An observable of type EventDetails that can be used to subscribe on the topic.
 * EventDetails contains topic and message. EventDetails.topic can be useful in getting 
 * the complete topic name during wild card or prefix subscriptions 
 */
public <T> Observable<EventDetails<T>> makeSubscriptionWithDetails(final String topic, SubscriptionFlags flags, final Class<T> eventClass)
{
    return makeSubscription(topic, flags).map(new Func1<PubSubData,EventDetails<T>>() {
        @Override
        public EventDetails<T> call(PubSubData ev) {
            if (eventClass == null || eventClass == Void.class) {
                // We don't need a value
                return null;
            }
            
            //get the complete topic name 
            //which may not be the same as method parameter 'topic' during wildcard or prefix subscriptions 
            String actualTopic = null;
            if(ev.details != null && ev.details.get("topic") != null){
            	actualTopic = ev.details.get("topic").asText();
            }

            if (ev.arguments == null || ev.arguments.size() < 1)
                throw OnErrorThrowable.from(new ApplicationError(ApplicationError.MISSING_VALUE));

            JsonNode eventNode = ev.arguments.get(0);
            if (eventNode.isNull()) return null;

            T eventValue;
            try {
                eventValue = clientConfig.objectMapper().convertValue(eventNode, eventClass);
            } catch (IllegalArgumentException e) {
                throw OnErrorThrowable.from(new ApplicationError(ApplicationError.INVALID_VALUE_TYPE));
            }
            return new EventDetails<T>(eventValue, actualTopic);
        }
    });
}
 
Example #10
Source File: WampClient.java    From jawampa with Apache License 2.0 5 votes vote down vote up
/**
 * Returns an observable that allows to subscribe on the given topic.<br>
 * The actual subscription will only be made after subscribe() was called
 * on it.<br>
 * This version of makeSubscription will automatically transform the
 * received events data into the type eventClass and will therefore return
 * a mapped Observable. It will only look at and transform the first
 * argument of the received events arguments, therefore it can only be used
 * for events that carry either a single or no argument.<br>
 * Received publications will be pushed to the Subscriber via it's
 * onNext method.<br>
 * The client can unsubscribe from the topic by calling unsubscribe() on
 * it's Subscription.<br>
 * If the connection closes onCompleted will be called.<br>
 * In case of errors during subscription onError will be called.
 * @param topic The topic to subscribe on.<br>
 * Must be valid WAMP URI.
 * @param flags Flags to indicate type of subscription. This cannot be null.
 * @param eventClass The class type into which the received event argument
 * should be transformed. E.g. use String.class to let the client try to
 * transform the first argument into a String and let the return value of
 * of the call be Observable&lt;String&gt;.
 * @return An observable that can be used to subscribe on the topic.
 */
public <T> Observable<T> makeSubscription(final String topic, SubscriptionFlags flags, final Class<T> eventClass)
{
    return makeSubscription(topic, flags).map(new Func1<PubSubData,T>() {
        @Override
        public T call(PubSubData ev) {
            if (eventClass == null || eventClass == Void.class) {
                // We don't need a value
                return null;
            }

            if (ev.arguments == null || ev.arguments.size() < 1)
                throw OnErrorThrowable.from(new ApplicationError(ApplicationError.MISSING_VALUE));

            JsonNode eventNode = ev.arguments.get(0);
            if (eventNode.isNull()) return null;

            T eventValue;
            try {
                eventValue = clientConfig.objectMapper().convertValue(eventNode, eventClass);
            } catch (IllegalArgumentException e) {
                throw OnErrorThrowable.from(new ApplicationError(ApplicationError.INVALID_VALUE_TYPE));
            }
            return eventValue;
        }
    });
}
 
Example #11
Source File: OnSubscribeMapLast.java    From rxjava-extras with Apache License 2.0 5 votes vote down vote up
@Override
public void onCompleted() {
    if (value != EMPTY) {
        T value2;
        try {
            value2 = function.call(value);
        } catch (Throwable e) {
            Exceptions.throwIfFatal(e);
            onError(OnErrorThrowable.addValueAsLastCause(e, value));
            return;
        }
        child.onNext(value2);
    }
    child.onCompleted();
}
 
Example #12
Source File: WampClient.java    From GreenBits with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Performs a remote procedure call through the router.<br>
 * The function will return immediately, as the actual call will happen
 * asynchronously.<br>
 * This overload of the call function will automatically map the received
 * reply value into the specified Java type by using Jacksons object mapping
 * facilities.<br>
 * Only the first value in the array of positional arguments will be taken
 * into account for the transformation. If multiple return values are required
 * another overload of this function has to be used.<br>
 * If the expected return type is not {@link Void} but the return value array
 * contains no value or if the value in the array can not be deserialized into
 * the expected type the returned {@link Observable} will be completed with
 * an error.
 * @param procedure The name of the procedure to call. Must be a valid WAMP
 * Uri.
 * @param flags Additional call flags if any. This can be null.
 * @param returnValueClass The class of the expected return value. If the function
 * uses no return values Void should be used.
 * @param args The list of positional arguments for the remote procedure call.
 * These will be get serialized according to the Jackson library serializing
 * behavior.
 * @return An observable that provides a notification whether the call was
 * was successful and the return value. If the call is successful the
 * returned observable will be completed with a single value (the return value).
 * If the remote procedure call yields an error the observable will be completed
 * with an error.
 */
public <T> Observable<T> call(final String procedure, final EnumSet<CallFlags> flags,
                              final Class<T> returnValueClass, Object... args)
{
    return call(procedure, flags, ArgArrayBuilder.buildArgumentsArray(clientConfig.objectMapper(), args), null)
        .map(new Func1<Reply,T>() {
        @Override
        public T call(Reply reply) {
            if (returnValueClass == null || returnValueClass == Void.class) {
                // We don't need a return value
                return null;
            }
            
            if (reply.arguments == null || reply.arguments.size() < 1)
                throw OnErrorThrowable.from(new ApplicationError(ApplicationError.MISSING_RESULT));
                
            JsonNode resultNode = reply.arguments.get(0);
            if (resultNode.isNull()) return null;
            
            T result;
            try {
                result = clientConfig.objectMapper().convertValue(resultNode, returnValueClass);
            } catch (IllegalArgumentException e) {
                // The returned exception is an aggregate one. That's not too nice :(
                throw OnErrorThrowable.from(new ApplicationError(ApplicationError.INVALID_VALUE_TYPE));
            }
            return result;
        }
    });
}
 
Example #13
Source File: WampClient.java    From GreenBits with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Returns an observable that allows to subscribe on the given topic.<br>
 * The actual subscription will only be made after subscribe() was called
 * on it.<br>
 * makeSubscriptionWithDetails will automatically transform the
 * received events data into the type eventClass and will therefore return
 * a mapped Observable of type EventDetails. It will only look at and transform the first
 * argument of the received events arguments, therefore it can only be used
 * for events that carry either a single or no argument.<br>
 * Received publications will be pushed to the Subscriber via it's
 * onNext method.<br>
 * The client can unsubscribe from the topic by calling unsubscribe() on
 * it's Subscription.<br>
 * If the connection closes onCompleted will be called.<br>
 * In case of errors during subscription onError will be called.
 * @param topic The topic to subscribe on.<br>
 * Must be valid WAMP URI.
 * @param flags Flags to indicate type of subscription. This cannot be null.
 * @param eventClass The class type into which the received event argument
 * should be transformed. E.g. use String.class to let the client try to
 * transform the first argument into a String and let the return value of
 * of the call be Observable&lt;EventDetails&lt;String&gt;&gt;.
 * @return An observable of type EventDetails that can be used to subscribe on the topic.
 * EventDetails contains topic and message. EventDetails.topic can be useful in getting 
 * the complete topic name during wild card or prefix subscriptions 
 */
public <T> Observable<EventDetails<T>> makeSubscriptionWithDetails(final String topic, SubscriptionFlags flags, final Class<T> eventClass)
{
    return makeSubscription(topic, flags).map(new Func1<PubSubData,EventDetails<T>>() {
        @Override
        public EventDetails<T> call(PubSubData ev) {
            if (eventClass == null || eventClass == Void.class) {
                // We don't need a value
                return null;
            }
            
            //get the complete topic name 
            //which may not be the same as method parameter 'topic' during wildcard or prefix subscriptions 
            String actualTopic = null;
            if(ev.details != null && ev.details.get("topic") != null){
            	actualTopic = ev.details.get("topic").asText();
            }

            if (ev.arguments == null || ev.arguments.size() < 1)
                throw OnErrorThrowable.from(new ApplicationError(ApplicationError.MISSING_VALUE));

            JsonNode eventNode = ev.arguments.get(0);
            if (eventNode.isNull()) return null;

            T eventValue;
            try {
                eventValue = clientConfig.objectMapper().convertValue(eventNode, eventClass);
            } catch (IllegalArgumentException e) {
                throw OnErrorThrowable.from(new ApplicationError(ApplicationError.INVALID_VALUE_TYPE));
            }
            return new EventDetails<T>(eventValue, actualTopic);
        }
    });
}
 
Example #14
Source File: WampClient.java    From GreenBits with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Returns an observable that allows to subscribe on the given topic.<br>
 * The actual subscription will only be made after subscribe() was called
 * on it.<br>
 * This version of makeSubscription will automatically transform the
 * received events data into the type eventClass and will therefore return
 * a mapped Observable. It will only look at and transform the first
 * argument of the received events arguments, therefore it can only be used
 * for events that carry either a single or no argument.<br>
 * Received publications will be pushed to the Subscriber via it's
 * onNext method.<br>
 * The client can unsubscribe from the topic by calling unsubscribe() on
 * it's Subscription.<br>
 * If the connection closes onCompleted will be called.<br>
 * In case of errors during subscription onError will be called.
 * @param topic The topic to subscribe on.<br>
 * Must be valid WAMP URI.
 * @param flags Flags to indicate type of subscription. This cannot be null.
 * @param eventClass The class type into which the received event argument
 * should be transformed. E.g. use String.class to let the client try to
 * transform the first argument into a String and let the return value of
 * of the call be Observable&lt;String&gt;.
 * @return An observable that can be used to subscribe on the topic.
 */
public <T> Observable<T> makeSubscription(final String topic, SubscriptionFlags flags, final Class<T> eventClass)
{
    return makeSubscription(topic, flags).map(new Func1<PubSubData,T>() {
        @Override
        public T call(PubSubData ev) {
            if (eventClass == null || eventClass == Void.class) {
                // We don't need a value
                return null;
            }

            if (ev.arguments == null || ev.arguments.size() < 1)
                throw OnErrorThrowable.from(new ApplicationError(ApplicationError.MISSING_VALUE));

            JsonNode eventNode = ev.arguments.get(0);
            if (eventNode.isNull()) return null;

            T eventValue;
            try {
                eventValue = clientConfig.objectMapper().convertValue(eventNode, eventClass);
            } catch (IllegalArgumentException e) {
                throw OnErrorThrowable.from(new ApplicationError(ApplicationError.INVALID_VALUE_TYPE));
            }
            return eventValue;
        }
    });
}
 
Example #15
Source File: MainActivity.java    From RxJava_RxAndroid with Apache License 2.0 5 votes vote down vote up
static rx.Observable<String> sampleObservable() {
    return rx.Observable.defer(new Func0<rx.Observable<String>>() {
        @Override public rx.Observable<String> call() {
            try {
                // Do some long running operation
                Thread.sleep(TimeUnit.SECONDS.toMillis(5));
            } catch (InterruptedException e) {
                throw OnErrorThrowable.from(e);
            }
            return Observable.just("one", "two", "three", "four", "five");
        }
    });
}
 
Example #16
Source File: MainActivity.java    From RxJava_RxAndroid with Apache License 2.0 5 votes vote down vote up
static Observable<String> sampleObservable() {
    return Observable.defer(new Func0<Observable<String>>() {
        @Override public Observable<String> call() {
            try {
                // Do some long running operation
                Thread.sleep(TimeUnit.SECONDS.toMillis(5));
            } catch (InterruptedException e) {
                throw OnErrorThrowable.from(e);
            }
            return Observable.just("one", "two", "three", "four", "five");
        }
    });
}
 
Example #17
Source File: SSTableRecordReader.java    From aegisthus with Apache License 2.0 4 votes vote down vote up
@Override
public void initialize(@Nonnull InputSplit inputSplit, @Nonnull final TaskAttemptContext ctx)
        throws IOException, InterruptedException {
    Configuration conf = ctx.getConfiguration();
    final AegSplit split = (AegSplit) inputSplit;

    long start = split.getStart();
    InputStream is = split.getInput(conf);
    long end = split.getDataEnd();
    URI fileUri = split.getPath().toUri();
    String filename = fileUri.toString();
    sourcePath = fileUri.getPath();
    traceDataFromSource = conf.getBoolean(Aegisthus.Feature.CONF_TRACE_DATA_FROM_SOURCE, false);

    LOG.info("File: {}", sourcePath);
    LOG.info("Start: {}", start);
    LOG.info("End: {}", end);

    try {
        Descriptor.Version version = Descriptor.Version.CURRENT;
        try {
            version = Descriptor.fromFilename(filename).version;
        } catch (Exception ignored) {
            // The 2.0 fromFilename parser fails on the latest Cassandra filenames, ignore this error and uses latest
        }
        scanner = new SSTableColumnScanner(is, start, end, version);
        LOG.info("Creating observable");
        rx.Observable<AtomWritable> observable = scanner.observable();
        observable = observable
                .onErrorFlatMap(new Func1<OnErrorThrowable, Observable<? extends AtomWritable>>() {
                    @Override
                    public Observable<? extends AtomWritable> call(OnErrorThrowable onErrorThrowable) {
                        LOG.error("failure deserializing file {}", split.getPath(), onErrorThrowable);
                        ctx.getCounter("aegisthus", "error_skipped_input").increment(1L);
                        return Observable.empty();
                    }
                });

        iterator = ObservableToIterator.toIterator(observable);
        LOG.info("done initializing");
    } catch (IOException e) {
        throw new IOError(e);
    }
}