rx.exceptions.Exceptions Java Examples

The following examples show how to use rx.exceptions.Exceptions. 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: DiskManagerImpl.java    From octoandroid with GNU General Public License v3.0 6 votes vote down vote up
@Override
public Func1<PrinterDbEntity, ConnectionEntity> getConnectionInDb() {
    return new Func1<PrinterDbEntity, ConnectionEntity>() {
        @Override
        public ConnectionEntity call(PrinterDbEntity printerDbEntity) {
            try {
                String json = printerDbEntity.getConnectionJson();
                ConnectionEntity entity = mEntitySerializer.deserialize(json, ConnectionEntity.class);
                if (entity == null) throw Exceptions.propagate(new PrinterDataNotFoundException());
                return entity;
            } catch (Exception e) {
                throw Exceptions.propagate(new PrinterDataNotFoundException(e));
            }
        }
    };
}
 
Example #2
Source File: EventHubImpl.java    From azure-libraries-for-java with MIT License 6 votes vote down vote up
private Observable<CloudStorageAccount> getCloudStorageAsync(final StorageAccount storageAccount) {
    return storageAccount.getKeysAsync()
            .flatMapIterable(new Func1<List<StorageAccountKey>, Iterable<StorageAccountKey>>() {
                @Override
                public Iterable<StorageAccountKey> call(List<StorageAccountKey> storageAccountKeys) {
                    return storageAccountKeys;
                }
            })
            .last()
            .map(new Func1<StorageAccountKey, CloudStorageAccount>() {
                @Override
                public CloudStorageAccount call(StorageAccountKey storageAccountKey) {
                    try {
                    return CloudStorageAccount.parse(Utils.getStorageConnectionString(storageAccount.name(), storageAccountKey.value(), manager().inner().restClient()));
                    } catch (URISyntaxException syntaxException) {
                        throw Exceptions.propagate(syntaxException);
                    } catch (InvalidKeyException keyException) {
                        throw Exceptions.propagate(keyException);
                    }
                }
            });
}
 
Example #3
Source File: VirtualMachinesImpl.java    From azure-libraries-for-java with MIT License 6 votes vote down vote up
@Override
public Observable<String> captureAsync(String groupName, String name, String containerName, String vhdPrefix, boolean overwriteVhd) {
    VirtualMachineCaptureParameters parameters = new VirtualMachineCaptureParameters();
    parameters.withDestinationContainerName(containerName);
    parameters.withOverwriteVhds(overwriteVhd);
    parameters.withVhdPrefix(vhdPrefix);
    return this.inner().captureAsync(groupName, name, parameters)
            .map(new Func1<VirtualMachineCaptureResultInner, String>() {
                @Override
                public String call(VirtualMachineCaptureResultInner innerResult) {
                    if (innerResult == null) {
                        return null;
                    }
                    ObjectMapper mapper = new ObjectMapper();
                    //Object to JSON string
                    try {
                        return mapper.writeValueAsString(innerResult);
                    } catch (JsonProcessingException e) {
                        throw Exceptions.propagate(e);
                    }
                }
            });
}
 
Example #4
Source File: EventHubImpl.java    From azure-libraries-for-java with MIT License 6 votes vote down vote up
private Observable<Boolean> createContainerIfNotExistsAsync(final StorageAccount storageAccount,
                                                            final String containerName) {
    return getCloudStorageAsync(storageAccount)
            .flatMap(new Func1<CloudStorageAccount, Observable<Boolean>>() {
                @Override
                public Observable<Boolean> call(final CloudStorageAccount cloudStorageAccount) {
                    return Observable.fromCallable(new Callable<Boolean>() {
                        @Override
                        public Boolean call() {
                            CloudBlobClient blobClient = cloudStorageAccount.createCloudBlobClient();
                            try {
                                return blobClient.getContainerReference(containerName).createIfNotExists();
                            } catch (StorageException stgException) {
                                throw Exceptions.propagate(stgException);
                            } catch (URISyntaxException syntaxException) {
                                throw Exceptions.propagate(syntaxException);
                            }
                        }
                    }).subscribeOn(SdkContext.getRxScheduler());
                }
            });
}
 
Example #5
Source File: NetworkLastFmStore.java    From Jockey with Apache License 2.0 6 votes vote down vote up
@Override
public Observable<LfmArtist> getArtistInfo(String artistName) {
    Observable<LfmArtist> result = mCachedArtistInfo.get(artistName);
    if (result == null) {
        result = mService.getArtistInfo(artistName)
                .map(response -> {
                    if (!response.isSuccessful()) {
                        String message = "Call to getArtistInfo failed with response code "
                                + response.code()
                                + "\n" + response.message();

                        throw Exceptions.propagate(new IOException(message));
                    }

                    return response.body().getArtist();
                })
                .cache();

        mCachedArtistInfo.put(artistName, result);
    }

    return result;
}
 
Example #6
Source File: Observable.java    From letv with Apache License 2.0 6 votes vote down vote up
static <T> Subscription subscribe(Subscriber<? super T> subscriber, Observable<T> observable) {
    if (subscriber == null) {
        throw new IllegalArgumentException("observer can not be null");
    } else if (observable.onSubscribe == null) {
        throw new IllegalStateException("onSubscribe function can not be null.");
    } else {
        subscriber.onStart();
        if (!(subscriber instanceof SafeSubscriber)) {
            subscriber = new SafeSubscriber(subscriber);
        }
        try {
            hook.onSubscribeStart(observable, observable.onSubscribe).call(subscriber);
            return hook.onSubscribeReturn(subscriber);
        } catch (Throwable e2) {
            Exceptions.throwIfFatal(e2);
            hook.onSubscribeError(new OnErrorFailedException("Error occurred attempting to subscribe [" + e.getMessage() + "] and then again while trying to pass to onError.", e2));
        }
    }
}
 
Example #7
Source File: PrivacyPolicyManager.java    From Jockey with Apache License 2.0 6 votes vote down vote up
private Observable<PrivacyPolicyMetadata> getPrivacyPolicyMetadata() {
    if (privacyPolicyMetadata == null) {
        privacyPolicyMetadata = service.getPrivacyPolicyMetadata()
                .map(response -> {
                    if (!response.isSuccessful()) {
                        throw Exceptions.propagate(
                                new IOException("Failed to fetch privacy policy metadata: "
                                        + response.code() + ", " + response.message())
                        );
                    } else {
                        return response.body();
                    }
                })
                .doOnError(throwable -> privacyPolicyMetadata = null)
                .cache();
    }

    return privacyPolicyMetadata;
}
 
Example #8
Source File: LocalPlaylistStore.java    From Jockey with Apache License 2.0 6 votes vote down vote up
private void saveAutoPlaylistConfiguration(AutoPlaylist playlist) {
    Observable.just(playlist)
            .observeOn(Schedulers.io())
            .subscribe(p -> {
                try {
                    writeAutoPlaylistConfiguration(p);
                } catch (IOException e) {
                    throw Exceptions.propagate(e);
                }
            }, throwable -> {
                Timber.e(throwable, "Failed to write AutoPlaylist configuration");
            });

    // Write an initial set of values to the MediaStore so other apps can see this playlist
    playlist.generatePlaylist(mMusicStore, this, mPlayCountStore)
            .take(1)
            .subscribeOn(Schedulers.computation())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(contents -> {
                editPlaylist(playlist, contents);
            }, throwable -> {
                Timber.e(throwable, "Failed to write AutoPlaylist contents");
            });
}
 
Example #9
Source File: MyRxJavaCallAdapterFactory.java    From Ticket-Analysis with MIT License 6 votes vote down vote up
@Override
public void request(long n) {
    if (n < 0) throw new IllegalArgumentException("n < 0: " + n);
    if (n == 0) return; // Nothing to do when requesting 0.
    if (!compareAndSet(false, true)) return; // Request was already triggered.

    try {
        Response<T> response = call.execute();
        if (!subscriber.isUnsubscribed()) {
            subscriber.onNext(response);
        }
    } catch (Throwable t) {
        Exceptions.throwIfFatal(t);
        if (!subscriber.isUnsubscribed()) {
            subscriber.onError(t);
        }
        return;
    }

    if (!subscriber.isUnsubscribed()) {
        subscriber.onCompleted();
    }
}
 
Example #10
Source File: ResourceFlowableDoOnNext.java    From akarnokd-misc with Apache License 2.0 6 votes vote down vote up
@Override
public void onNext(T t) {
    if (done) {
        ResourceFlowable.releaseItem(t, release);
    } else {
        try {
            onNext.accept(t);
        } catch (Throwable ex) {
            Exceptions.throwIfFatal(ex);
            upstream.cancel();
            ResourceFlowable.releaseItem(t, release);
            done = true;
            actual.onError(ex);
            return;
        }

        actual.onNext(t);
    }
}
 
Example #11
Source File: ResourceFlowableMap.java    From akarnokd-misc with Apache License 2.0 6 votes vote down vote up
@Override
public void onNext(T t) {
    if (done) {
        ResourceFlowable.releaseItem(t, release);
    } else {
        R v;

        try {
            v = ObjectHelper.requireNonNull(mapper.apply(t), "The mapper returned a null value");
        } catch (Throwable ex) {
            Exceptions.throwIfFatal(ex);
            upstream.cancel();
            ResourceFlowable.releaseItem(t, release);
            done = true;
            actual.onError(ex);
            return;
        }

        ResourceFlowable.releaseItem(t, release);

        actual.onNext(v);
    }
}
 
Example #12
Source File: ResourceFlowableIterable.java    From akarnokd-misc with Apache License 2.0 6 votes vote down vote up
@Override
protected void subscribeActual(Subscriber<? super T> subscriber) {
    Iterator<? extends T> it;
    boolean b;
    try {
        it = items.iterator();

        b = it.hasNext();
    } catch (Throwable ex) {
        Exceptions.throwIfFatal(ex);
        EmptySubscription.error(ex, subscriber);
        return;
    }

    if (!b) {
        EmptySubscription.complete(subscriber);
        return;
    }

    subscriber.onSubscribe(new RFIteratorSubscription<>(subscriber, release, it));
}
 
Example #13
Source File: OperatorFreeze.java    From ferro with Apache License 2.0 6 votes vote down vote up
private void bufferEvent(T event) {
    for (ListIterator<T> it = frozenEventsBuffer.listIterator(); it.hasNext(); ) {
        T frozenEvent = it.next();
        try {
            if (replaceFrozenEventPredicate.call(frozenEvent, event)) {
                it.remove();
            }
        } catch (Throwable ex) {
            Exceptions.throwIfFatal(ex);
            unsubscribe();
            onError(ex);
            return;
        }
    }
    frozenEventsBuffer.add(event);
}
 
Example #14
Source File: DataAccessImpl.java    From hawkular-metrics with Apache License 2.0 6 votes vote down vote up
private <T> Observable.Transformer<T, T> applyInsertRetryPolicy() {
    return tObservable -> tObservable
            .retryWhen(errors -> {
                Observable<Integer> range = Observable.range(1, 2);
                return errors
                        .zipWith(range, (t, i) -> {
                            if (t instanceof DriverException) {
                                return i;
                            }
                            throw Exceptions.propagate(t);
                        })
                        .flatMap(retryCount -> {
                            long delay = (long) Math.min(Math.pow(2, retryCount) * 1000, 3000);
                            log.debug("Retrying batch insert in " + delay + " ms");
                            return Observable.timer(delay, TimeUnit.MILLISECONDS);
                        });
            });
}
 
Example #15
Source File: DiskManagerImpl.java    From octoandroid with GNU General Public License v3.0 6 votes vote down vote up
/**
 * This is used to sync the database when deleting from account manager.
 */
@Override
public Func1<PrinterDbEntity, Boolean> syncDbAndAccountDeletion() {
    return new Func1<PrinterDbEntity, Boolean>() {
        @Override
        public Boolean call(PrinterDbEntity printerDbEntity) {
            PrinterDbEntity old = mDbHelper.getPrinterFromDbByName(printerDbEntity.getName());
            if (old == null) {
                throw Exceptions.propagate(new PrinterDataNotFoundException());
            }

            // DO NOT CALL any methods related to deleting from account or you will infinite loop!
            // ie: mAccountManager.removeAccount()

            if (mPrefHelper.isPrinterActive(old)) mPrefHelper.resetActivePrinter();
            mDbHelper.deletePrinterInDb(old);
            return true;
        }
    };
}
 
Example #16
Source File: DiskManagerImpl.java    From octoandroid with GNU General Public License v3.0 6 votes vote down vote up
@Override
public Action1<ConnectionEntity> putConnectionInDb() {
    return new Action1<ConnectionEntity>() {
        @Override
        public void call(ConnectionEntity connectionEntity) {
            try {
                PrinterDbEntity printerDbEntity = mDbHelper.getActivePrinterDbEntity();
                String connectionJson = mEntitySerializer.serialize(connectionEntity);
                printerDbEntity.setConnectionJson(connectionJson);
                mDbHelper.insertOrReplace(printerDbEntity);
            } catch (Exception e) {
                throw Exceptions.propagate(new ErrorSavingException());
            }
        }
    };
}
 
Example #17
Source File: DiskManagerImpl.java    From octoandroid with GNU General Public License v3.0 6 votes vote down vote up
@Override
public Func1<VersionEntity, VersionEntity> putVersionInDb() {
    return new Func1<VersionEntity, VersionEntity>() {
        @Override
        public VersionEntity call(VersionEntity versionEntity) {
            try {
                PrinterDbEntity printerDbEntity = mDbHelper.getActivePrinterDbEntity();
                String versionJson = mEntitySerializer.serialize(versionEntity);
                printerDbEntity.setVersionJson(versionJson);
                mDbHelper.insertOrReplace(printerDbEntity);
                return versionEntity;
            } catch (Exception e) {
                throw Exceptions.propagate(new ErrorSavingException(e));
            }
        }
    };
}
 
Example #18
Source File: PrinterDbEntityMapper.java    From octoandroid with GNU General Public License v3.0 6 votes vote down vote up
public static Func1<List<PrinterDbEntity>, List<Printer>> mapToPrinters() {
    return new Func1<List<PrinterDbEntity>, List<Printer>>() {
        @Override
        public List<Printer> call(List<PrinterDbEntity> printerDbEntities) {
            try {
                List<Printer> printers = new ArrayList<>();
                for (PrinterDbEntity printerDbEntity : printerDbEntities) {
                    printers.add(printerDbEntityToPrinter(printerDbEntity));
                }
                return printers;
            } catch (Exception e) {
                throw Exceptions.propagate(new EntityMapperException(e));
            }
        }
    };
}
 
Example #19
Source File: RxJavaCallAdapterFactory.java    From likequanmintv with Apache License 2.0 6 votes vote down vote up
@Override public void request(long n) {
  if (n < 0) throw new IllegalArgumentException("n < 0: " + n);
  if (n == 0) return; // Nothing to do when requesting 0.
  if (!compareAndSet(false, true)) return; // Request was already triggered.

  try {
    Response<T> response = call.execute();
    if (!subscriber.isUnsubscribed()) {
      subscriber.onNext(response);
    }
  } catch (Throwable t) {
    Exceptions.throwIfFatal(t);
    if (!subscriber.isUnsubscribed()) {
      subscriber.onError(t);
    }
    return;
  }

  if (!subscriber.isUnsubscribed()) {
    subscriber.onCompleted();
  }
}
 
Example #20
Source File: BodyOnSubscribe.java    From okhttp-OkGo with Apache License 2.0 6 votes vote down vote up
@Override
public void onNext(Response<R> response) {
    if (response.isSuccessful()) {
        subscriber.onNext(response.body());
    } else {
        subscriberTerminated = true;
        Throwable t = new HttpException(response);
        try {
            subscriber.onError(t);
        } catch (OnCompletedFailedException | OnErrorFailedException | OnErrorNotImplementedException e) {
            RxJavaHooks.getOnError().call(e);
        } catch (Throwable inner) {
            Exceptions.throwIfFatal(inner);
            RxJavaHooks.getOnError().call(new CompositeException(t, inner));
        }
    }
}
 
Example #21
Source File: ResultOnSubscribe.java    From okhttp-OkGo with Apache License 2.0 6 votes vote down vote up
@Override
public void onError(Throwable throwable) {
    try {
        subscriber.onNext(Result.<R>error(throwable));
    } catch (Throwable t) {
        try {
            subscriber.onError(t);
        } catch (OnCompletedFailedException | OnErrorFailedException | OnErrorNotImplementedException e) {
            RxJavaHooks.getOnError().call(e);
        } catch (Throwable inner) {
            Exceptions.throwIfFatal(inner);
            RxJavaHooks.getOnError().call(new CompositeException(t, inner));
        }
        return;
    }
    subscriber.onCompleted();
}
 
Example #22
Source File: AzureClient.java    From autorest-clientruntime-for-java with MIT License 6 votes vote down vote up
/**
 * Given an observable representing a deferred PUT or PATCH action, this method returns {@link Single} object,
 * when subscribed to it, the deferred action will be performed and emits the polling state containing information
 * to track the progress of the action.
 *
 * Note: this method does not implicitly introduce concurrency, by default the deferred action will be executed
 * in scheduler (if any) set for the provided observable.
 *
 * @param observable an observable representing a deferred PUT or PATCH operation.
 * @param resourceType the java.lang.reflect.Type of the resource.
 * @param <T> the type of the resource
 * @return the observable of which a subscription will lead PUT or PATCH action.
 */
public <T> Single<PollingState<T>> beginPutOrPatchAsync(Observable<Response<ResponseBody>> observable, final Type resourceType) {
    return observable.map(new Func1<Response<ResponseBody>, PollingState<T>>() {
        @Override
        public PollingState<T> call(Response<ResponseBody> response) {
            RuntimeException exception = createExceptionFromResponse(response, 200, 201, 202);
            if (exception != null) {
                throw  exception;
            }
            try {
                final PollingState<T> pollingState = PollingState.create(response, LongRunningOperationOptions.DEFAULT, longRunningOperationRetryTimeout(), resourceType, restClient().serializerAdapter());
                pollingState.withPollingUrlFromResponse(response);
                pollingState.withPollingRetryTimeoutFromResponse(response);
                pollingState.withPutOrPatchResourceUri(response.raw().request().url().toString());
                return pollingState;
            } catch (IOException ioException) {
                throw Exceptions.propagate(ioException);
            }
        }
    }).toSingle();
}
 
Example #23
Source File: AzureClient.java    From autorest-clientruntime-for-java with MIT License 6 votes vote down vote up
/**
 * Given an observable representing a deferred POST or DELETE action, this method returns {@link Single} object,
 * when subscribed to it, the deferred action will be performed and emits the polling state containing information
 * to track the progress of the action.
 *
 * @param observable an observable representing a deferred POST or DELETE operation.
 * @param lroOptions long running operation options.
 * @param resourceType the java.lang.reflect.Type of the resource.
 * @param <T> the type of the resource
 * @return the observable of which a subscription will lead POST or DELETE action.
 */
public <T> Single<PollingState<T>> beginPostOrDeleteAsync(Observable<Response<ResponseBody>> observable, final LongRunningOperationOptions lroOptions, final Type resourceType) {
    return observable.map(new Func1<Response<ResponseBody>, PollingState<T>>() {
        @Override
        public PollingState<T> call(Response<ResponseBody> response) {
            RuntimeException exception = createExceptionFromResponse(response, 200, 202, 204);
            if (exception != null) {
                throw  exception;
            }
            try {
                final PollingState<T> pollingState = PollingState.create(response, lroOptions, longRunningOperationRetryTimeout(), resourceType, restClient().serializerAdapter());
                pollingState.withPollingUrlFromResponse(response);
                pollingState.withPollingRetryTimeoutFromResponse(response);
                return pollingState;
            } catch (IOException ioException) {
                throw Exceptions.propagate(ioException);
            }
        }
    }).toSingle();
}
 
Example #24
Source File: ResourceFlowableToFlowable.java    From akarnokd-misc with Apache License 2.0 6 votes vote down vote up
@Override
public void onNext(T t) {
    if (done) {
        ResourceFlowable.releaseItem(t, release);
    } else {
        R v;

        try {
            v = ObjectHelper.requireNonNull(mapper.apply(t), "The mapper returned a null value");
        } catch (Throwable ex) {
            Exceptions.throwIfFatal(ex);
            upstream.cancel();
            ResourceFlowable.releaseItem(t, release);
            done = true;
            actual.onError(ex);
            return;
        }

        ResourceFlowable.releaseItem(t, release);

        actual.onNext(v);
    }
}
 
Example #25
Source File: ResourceFlowableDefer.java    From akarnokd-misc with Apache License 2.0 5 votes vote down vote up
@Override
protected void subscribeActual(Subscriber<? super T> subscriber) {
    ResourceFlowable<T> rf;

    try {
        rf = call.call();
    } catch (Throwable ex) {
        Exceptions.throwIfFatal(ex);
        EmptySubscription.error(ex, subscriber);
        return;
    }

    rf.subscribe(subscriber);
}
 
Example #26
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 #27
Source File: MesosClient.java    From mesos-rxjava with Apache License 2.0 5 votes vote down vote up
@Override
public void onError(final Throwable e) {
    Exceptions.throwIfFatal(e);
    try {
        delegate.onError(e);
        queue.offer(Optional.of(e));
    } catch (Exception e1) {
        queue.offer(Optional.of(e1));
    }
}
 
Example #28
Source File: AbstractBody.java    From datamill with ISC License 5 votes vote down vote up
@Override
public <T> Observable<T> fromJson(Class<T> clazz) {
    return asString().map(json -> {
        try {
            return jsonMapper.readValue(json, clazz);
        } catch (IOException e) {
            throw Exceptions.propagate(e);
        }
    });
}
 
Example #29
Source File: WebsocketInterceptor.java    From octoandroid with GNU General Public License v3.0 5 votes vote down vote up
private String getWebsocketUrl(PrinterDbEntity printerDbEntity) {
    String scheme = printerDbEntity.getScheme();
    String host = printerDbEntity.getHost();
    String path = printerDbEntity.getWebsocketPath();

    String socketScheme = scheme.replace("http", "ws"); // Also works for https
    try {
        return new URI(socketScheme, host, path, null).toString();
    } catch (URISyntaxException e) {
        throw Exceptions.propagate(new URISyntaxException(e.getInput(), e.getReason()));
    }
}
 
Example #30
Source File: PrinterDbEntityMapper.java    From octoandroid with GNU General Public License v3.0 5 votes vote down vote up
public static Func1<PrinterDbEntity, Printer> maptoPrinter() {
    return new Func1<PrinterDbEntity, Printer>() {
        @Override
        public Printer call(PrinterDbEntity printerDbEntity) {
            try {
                return printerDbEntityToPrinter(printerDbEntity);
            } catch (Exception e) {
                throw Exceptions.propagate(new EntityMapperException(e));
            }
        }
    };
}