org.apache.http.nio.client.methods.HttpAsyncMethods#rx.exceptions.Exceptions源码实例Demo

下面列出了org.apache.http.nio.client.methods.HttpAsyncMethods#rx.exceptions.Exceptions 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

@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();
    }
}
 
源代码2 项目: letv   文件: Observable.java
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));
        }
    }
}
 
源代码3 项目: azure-libraries-for-java   文件: EventHubImpl.java
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());
                }
            });
}
 
源代码4 项目: azure-libraries-for-java   文件: EventHubImpl.java
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);
                    }
                }
            });
}
 
@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);
                    }
                }
            });
}
 
源代码6 项目: likequanmintv   文件: RxJavaCallAdapterFactory.java
@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();
  }
}
 
源代码7 项目: octoandroid   文件: DiskManagerImpl.java
@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));
            }
        }
    };
}
 
源代码8 项目: octoandroid   文件: DiskManagerImpl.java
@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());
            }
        }
    };
}
 
源代码9 项目: octoandroid   文件: DiskManagerImpl.java
/**
 * 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;
        }
    };
}
 
源代码10 项目: octoandroid   文件: DiskManagerImpl.java
@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));
            }
        }
    };
}
 
源代码11 项目: octoandroid   文件: PrinterDbEntityMapper.java
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));
            }
        }
    };
}
 
源代码12 项目: okhttp-OkGo   文件: BodyOnSubscribe.java
@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));
        }
    }
}
 
源代码13 项目: okhttp-OkGo   文件: ResultOnSubscribe.java
@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();
}
 
/**
 * 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();
}
 
/**
 * 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();
}
 
源代码16 项目: ferro   文件: OperatorFreeze.java
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);
}
 
源代码17 项目: akarnokd-misc   文件: ResourceFlowableToFlowable.java
@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);
    }
}
 
源代码18 项目: akarnokd-misc   文件: ResourceFlowableIterable.java
@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));
}
 
源代码19 项目: akarnokd-misc   文件: ResourceFlowableMap.java
@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);
    }
}
 
源代码20 项目: akarnokd-misc   文件: ResourceFlowableDoOnNext.java
@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);
    }
}
 
源代码21 项目: Jockey   文件: NetworkLastFmStore.java
@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;
}
 
源代码22 项目: Jockey   文件: PrivacyPolicyManager.java
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;
}
 
源代码23 项目: Jockey   文件: LocalPlaylistStore.java
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");
            });
}
 
源代码24 项目: hawkular-metrics   文件: DataAccessImpl.java
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);
                        });
            });
}
 
源代码25 项目: letv   文件: Completable.java
public final void subscribe(CompletableSubscriber s) {
    requireNonNull(s);
    try {
        this.onSubscribe.call(s);
    } catch (NullPointerException ex) {
        throw ex;
    } catch (Throwable ex2) {
        ERROR_HANDLER.handleError(ex2);
        Exceptions.throwIfFatal(ex2);
        NullPointerException toNpe = toNpe(ex2);
    }
}
 
源代码26 项目: letv   文件: Observable.java
public final Subscription unsafeSubscribe(Subscriber<? super T> subscriber) {
    try {
        subscriber.onStart();
        hook.onSubscribeStart(this, this.onSubscribe).call(subscriber);
        return hook.onSubscribeReturn(subscriber);
    } catch (Throwable e2) {
        Exceptions.throwIfFatal(e2);
        hook.onSubscribeError(new RuntimeException("Error occurred attempting to subscribe [" + e.getMessage() + "] and then again while trying to pass to onError.", e2));
    }
}
 
private Observable<Triple<String, String, String>> createFileShareAsync(final StorageAccount storageAccount) {
    return storageAccount.getKeysAsync()
            .map(new Func1<List<StorageAccountKey>, String>() {
                @Override
                public String call(List<StorageAccountKey> storageAccountKeys) {
                    return storageAccountKeys.get(0).value();
                }
            })
            .flatMap(new Func1<String, Observable<Triple<String, String, String>>>() {
                CloudFileClient cloudFileClient;
                @Override
                public Observable<Triple<String, String, String>> call(final String storageAccountKey) {
                    try {
                        cloudFileClient = CloudStorageAccount.parse(Utils.getStorageConnectionString(
                                storageAccount.name(),
                                storageAccountKey,
                                manager().inner().restClient()))
                                .createCloudFileClient();
                    } catch (URISyntaxException syntaxException) {
                        throw Exceptions.propagate(syntaxException);
                    } catch (InvalidKeyException keyException) {
                        throw Exceptions.propagate(keyException);
                    }
                    return Observable.from(newFileShares.entrySet())
                            .flatMap(new Func1<Map.Entry<String, String>, Observable<Triple<String, String, String>>>() {
                                @Override
                                public Observable<Triple<String, String, String>> call(Map.Entry<String, String> fileShareEntry) {
                                    return createSingleFileShareAsync(cloudFileClient, fileShareEntry.getKey(), fileShareEntry.getValue(), storageAccountKey);
                                }
                            });
                }
            });
}
 
源代码28 项目: azure-libraries-for-java   文件: Utils.java
/**
 * Download a file asynchronously.
 * @param url the URL pointing to the file
 * @param retrofit the retrofit client
 * @return an Observable pointing to the content of the file
 */
public static Observable<byte[]> downloadFileAsync(String url, Retrofit retrofit) {
    FileService service = retrofit.create(FileService.class);
    Observable<ResponseBody> response = service.download(url);
    return response.map(new Func1<ResponseBody, byte[]>() {
        @Override
        public byte[] call(ResponseBody responseBody) {
            try {
                return responseBody.bytes();
            } catch (IOException e) {
                throw Exceptions.propagate(e);
            }
        }
    });
}
 
private Observable<Indexable> getOrCreateStorageAccountContainer(final StorageAccount storageAccount, final String containerName, final String fileName, final FunctionalTaskItem.Context context) {
    final SqlDatabaseExportRequestImpl self = this;
    return storageAccount.getKeysAsync()
        .flatMap(new Func1<List<StorageAccountKey>, Observable<StorageAccountKey>>() {
            @Override
            public Observable<StorageAccountKey> call(List<StorageAccountKey> storageAccountKeys) {
                return Observable.from(storageAccountKeys).first();
            }
        })
        .flatMap(new Func1<StorageAccountKey, Observable<Indexable>>() {
            @Override
            public Observable<Indexable> call(StorageAccountKey storageAccountKey) {
                self.inner.withStorageUri(String.format("%s%s/%s", storageAccount.endPoints().primary().blob(), containerName, fileName));
                self.inner.withStorageKeyType(StorageKeyType.STORAGE_ACCESS_KEY);
                self.inner.withStorageKey(storageAccountKey.value());
                try {
                    CloudStorageAccount cloudStorageAccount =
                        CloudStorageAccount.parse(Utils.getStorageConnectionString(storageAccount.name(), storageAccountKey.value(), sqlServerManager.inner().restClient()));
                    CloudBlobClient blobClient = cloudStorageAccount.createCloudBlobClient();
                    blobClient.getContainerReference(containerName)
                        .createIfNotExists();
                } catch (IndexOutOfBoundsException indexOutOfBoundsException) {
                    throw Exceptions.propagate(indexOutOfBoundsException);
                } catch (URISyntaxException syntaxException) {
                    throw Exceptions.propagate(syntaxException);
                } catch (StorageException stgException) {
                    throw Exceptions.propagate(stgException);
                } catch (InvalidKeyException keyException) {
                    throw Exceptions.propagate(keyException);
                }
                return context.voidObservable();
            }
        });
}
 
@Override
public Observable<byte[]> getContainerLogsAsync() {
    return manager().inner().webApps().getWebSiteContainerLogsSlotAsync(resourceGroupName(), parent().name(), name())
            .map(new Func1<InputStream, byte[]>() {
                @Override
                public byte[] call(InputStream inputStream) {
                    try {
                        return ByteStreams.toByteArray(inputStream);
                    } catch (IOException e) {
                        throw Exceptions.propagate(e);
                    }
                }
            });
}