Java Code Examples for java.util.concurrent.CompletionStage#handle()

The following examples show how to use java.util.concurrent.CompletionStage#handle() . These examples are extracted from open source projects. 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
private DeferredResult<Object> adaptCompletionStage(CompletionStage<?> future) {
	DeferredResult<Object> result = new DeferredResult<>();
	future.handle((BiFunction<Object, Throwable, Object>) (value, ex) -> {
		if (ex != null) {
			if (ex instanceof CompletionException && ex.getCause() != null) {
				ex = ex.getCause();
			}
			result.setErrorResult(ex);
		}
		else {
			result.setResult(value);
		}
		return null;
	});
	return result;
}
 
Example 2
Source Project: mug   File: Maybe.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Returns a wrapper of {@code stage} that if {@code stage} failed with exception of
 * {@code exceptionType}, that exception is caught and wrapped inside a {@link Maybe} to complete
 * the wrapper stage normally.
 *
 * <p>This is useful if the asynchronous code is interested in recovering from its own exception
 * without having to deal with other exception types.
 */
public static <T, E extends Throwable> CompletionStage<Maybe<T, E>> catchException(
    Class<E> exceptionType, CompletionStage<? extends T> stage) {
  requireNonNull(exceptionType);
  CompletableFuture<Maybe<T, E>> future = new CompletableFuture<>();
  stage.handle((v, e) -> {
    try {
      if (e == null) {
        future.complete(Maybe.of(v));
      } else {
        unwrapFutureException(exceptionType, e)
            .map(cause -> future.complete(Maybe.except(cause)))
            .orElseGet(() -> future.completeExceptionally(e));
      }
    } catch (Throwable x) {  // Just in case there was a bug. Don't hang the thread.
      if (x != e) x.addSuppressed(e);
      future.completeExceptionally(x);
    }
    return null;
  });
  return future;
}
 
Example 3
@Override
public DeferredResult<?> adaptToDeferredResult(Object returnValue) {
	Assert.isInstanceOf(CompletionStage.class, returnValue, "CompletionStage expected");
	final DeferredResult<Object> result = new DeferredResult<Object>();
	@SuppressWarnings("unchecked")
	CompletionStage<?> future = (CompletionStage<?>) returnValue;
	future.handle(new BiFunction<Object, Throwable, Object>() {
		@Override
		public Object apply(Object value, Throwable ex) {
			if (ex != null) {
				result.setErrorResult(ex);
			}
			else {
				result.setResult(value);
			}
			return null;
		}
	});
	return result;
}
 
Example 4
private CompletionStage<AsyncResultSet> executeAsyncOnSession(Statement statement) {
    try {
        this.semaphore.acquire();
        CompletionStage<AsyncResultSet> async = this.session.executeAsync(statement);
        async.handle((result, exception) -> {
            this.semaphore.release();
            if (exception != null) {
                return exception;
            } else {
                return result;
            }
        });
        return async;
    } catch (InterruptedException e) {
        this.semaphore.release();
        Thread.currentThread().interrupt();
        throw new JanusGraphException("Interrupted while acquiring resource to execute query on Session.");
    }
}
 
Example 5
@Override
protected CompletionStage<HttpServletResponse> doExecute(final Routes.Route route,
                                                         final HttpServletRequest req, final HttpServletResponse resp,
                                                         final String prefix) throws IOException {
    final CompletionStage<HttpServletResponse> stage;
    if (spy.isHasBeforeEvent()) {
        final BeforeRequest event = new BeforeRequest(req, resp);
        event.setRoute(route);
        event.setPrefix(prefix);
        beforeRequestEvent.fire(event);
        stage = super.doExecute(event.getRoute(), req, resp, event.getPrefix());
    } else {
        stage = super.doExecute(route, req, resp, prefix);
    }
    if (!spy.isHasAfterEvent()) {
        return stage;
    }
    return stage.handle((r, t) -> {
        afterResponseEvent.fire(new AfterResponse(req, resp));
        return r;
    });
}
 
Example 6
Source Project: armeria   File: AsyncMethodCallbacks.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Adds a callback that transfers the outcome of the specified {@link CompletionStage} to the specified
 * {@link AsyncMethodCallback}.
 *
 * <pre>{@code
 * > public class MyThriftService implements ThriftService.AsyncIface {
 * >     @Override
 * >     public void myServiceMethod(AsyncMethodCallback<MyResult> callback) {
 * >         final CompletableFuture<MyResult> future = ...;
 * >         AsyncMethodCallbacks.transfer(future, callback);
 * >     }
 * > }
 * }</pre>
 */
public static <T> void transfer(CompletionStage<T> src, AsyncMethodCallback<? super T> dest) {
    requireNonNull(src, "src");
    requireNonNull(dest, "dest");
    src.handle((res, cause) -> {
        try {
            if (cause != null) {
                invokeOnError(dest, cause);
            } else {
                dest.onComplete(res);
            }
        } catch (Exception e) {
            CompletionActions.log(e);
        }
        return null;
    });
}
 
Example 7
Source Project: armeria   File: RpcResponse.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Creates a new {@link RpcResponse} that is completed successfully or exceptionally based on the
 * completion of the specified {@link CompletionStage}.
 */
static RpcResponse from(CompletionStage<?> stage) {
    requireNonNull(stage, "stage");
    final CompletableRpcResponse res = new CompletableRpcResponse();
    stage.handle((value, cause) -> {
        if (cause != null) {
            res.completeExceptionally(cause);
        } else if (value instanceof RpcResponse) {
            ((RpcResponse) value).handle((rpcResponseResult, rpcResponseCause) -> {
                if (rpcResponseCause != null) {
                    res.completeExceptionally(Exceptions.peel(rpcResponseCause));
                } else {
                    res.complete(rpcResponseResult);
                }
                return null;
            });
        } else {
            res.complete(value);
        }
        return null;
    });
    return res;
}
 
Example 8
Source Project: armeria   File: RequestContext.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Returns a {@link CompletionStage} that makes sure the current {@link RequestContext} is set and
 * then invokes the input {@code stage}.
 */
default <T> CompletionStage<T> makeContextAware(CompletionStage<T> stage) {
    final CompletableFuture<T> future = JavaVersionSpecific.get().newRequestContextAwareFuture(this);
    stage.handle((result, cause) -> {
        try (SafeCloseable ignored = push()) {
            if (cause != null) {
                future.completeExceptionally(cause);
            } else {
                future.complete(result);
            }
        } catch (Throwable t) {
            future.completeExceptionally(t);
        }
        return null;
    });
    return future;
}
 
Example 9
@Override
public CompletionStage<Boolean> initialize(boolean reset) throws Exception {
    CompletionStage<RestResponse> caches = client.caches();
    RestResponse result = caches.toCompletableFuture().get();
    String body = result.getBody();
    if (result.getStatus() != 200) {
        log.log(Level.SEVERE, body);
        return CompletableFuture.completedFuture(Boolean.FALSE);
    }
    boolean hasProto = cacheExists(body, PROTO_CACHE);
    boolean hasSearch = cacheExists(body, cacheName);
    if (reset) {
        reset(hasProto, PROTO_CACHE, SEARCH_PROTO_KEY);
        reset(hasProto, PROTO_CACHE, COMMON_PROTO_KEY);
        reset(hasSearch, cacheName, null);
    }

    CompletionStage<RestResponse> cs = null;

    if (reset || !hasProto) {
        cs = registerProto(COMMON_PROTO_KEY).thenCompose(r -> registerProto(SEARCH_PROTO_KEY));
    }

    if (reset || !hasSearch) {
        RestEntity configEntity = new StringRestEntityOkHttp(MediaType.APPLICATION_JSON, JSON_CACHE_CONFIG);
        CompletionStage<RestResponse> searchCs = getCache().createWithConfiguration(configEntity);
        cs = (cs != null) ? cs.thenCombine(searchCs, RFN) : searchCs;
    }
    return (cs != null) ? cs.handle((r, t) -> (t == null)) : CompletableFuture.completedFuture(Boolean.TRUE);
}
 
Example 10
private DeferredResult<Object> adaptCompletionStage(CompletionStage<?> future) {
	DeferredResult<Object> result = new DeferredResult<>();
	future.handle((BiFunction<Object, Throwable, Object>) (value, ex) -> {
		if (ex != null) {
			result.setErrorResult(ex);
		}
		else {
			result.setResult(value);
		}
		return null;
	});
	return result;
}
 
Example 11
Source Project: mug   File: MaybeTest.java    License: Apache License 2.0 5 votes vote down vote up
private static <T> CompletionStage<T> naiveExceptionHandlingCode(
    CompletionStage<T> stage) {
  return stage.handle((v, e) -> {
    assertThat(e).isInstanceOf(MyException.class);
    return null;
  });
}
 
Example 12
/** Demo utility method for external reliable toCompletableFuture */
static <T> CompletableFuture<T> toCompletableFuture(CompletionStage<T> stage) {
    CompletableFuture<T> f = new CompletableFuture<>();
    stage.handle((T t, Throwable ex) -> {
                     if (ex != null) f.completeExceptionally(ex);
                     else f.complete(t);
                     return null;
                 });
    return f;
}
 
Example 13
Source Project: armeria   File: DeferredHttpResponse.java    License: Apache License 2.0 5 votes vote down vote up
void delegateWhenComplete(CompletionStage<? extends HttpResponse> stage) {
    requireNonNull(stage, "stage");
    stage.handle((delegate, thrown) -> {
        if (thrown != null) {
            close(Exceptions.peel(thrown));
        } else if (delegate == null) {
            close(new NullPointerException("delegate stage produced a null response: " + stage));
        } else {
            delegate(delegate);
        }
        return null;
    });
}
 
Example 14
@Test
public void handleShouldAcceptUnwrappedException() {
    CompletionStage<String> completionStage = createCompletionStage(EXCEPTION);

    BiFunction<String, Throwable, ?> handler = mock(BiFunction.class);
    completionStage.handle(handler);

    finish(completionStage);
    verify(handler, times(1)).apply(null, EXCEPTION);
}
 
Example 15
@Test
public void handleShouldBeCalled() {
    CompletionStage<String> completionStage = createCompletionStage(VALUE);

    BiFunction<String, Throwable, Integer> consumer = mock(BiFunction.class);
    completionStage.handle(consumer);

    finish(completionStage);

    verify(consumer).apply(VALUE, null);
}
 
Example 16
Source Project: java-dataloader   File: Try.java    License: Apache License 2.0 3 votes vote down vote up
/**
 * Creates a CompletionStage that, when it completes, will capture into a Try whether the given completionStage
 * was successful or not
 *
 * @param completionStage the completion stage that will complete
 * @param <V>             the value type
 *
 * @return a Try which is the result of the call
 */
public static <V> CompletionStage<Try<V>> tryStage(CompletionStage<V> completionStage) {
    return completionStage.handle((value, throwable) -> {
        if (throwable != null) {
            return failed(throwable);
        }
        return succeeded(value);
    });
}