下面列出了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();
}
}
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));
}
}
}
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());
}
});
}
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);
}
}
});
}
@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();
}
}
@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));
}
}
};
}
@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());
}
}
};
}
/**
* 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;
}
};
}
@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));
}
}
};
}
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));
}
}
};
}
@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));
}
}
}
@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();
}
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);
}
@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);
}
}
@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));
}
@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);
}
}
@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);
}
}
@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;
}
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;
}
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");
});
}
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);
});
});
}
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);
}
}
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);
}
});
}
});
}
/**
* 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);
}
}
});
}