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

The following examples show how to use java.util.concurrent.CompletionStage#handle() . 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: DeferredResultMethodReturnValueHandler.java    From spring-analysis-note with MIT License 6 votes vote down vote up
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 File: Maybe.java    From mug with 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
Source File: DeferredResultMethodReturnValueHandler.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@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
Source File: CQLStoreManager.java    From grakn with GNU Affero General Public License v3.0 6 votes vote down vote up
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
Source File: CDIProxyServlet.java    From openwebbeans-meecrowave with Apache License 2.0 6 votes vote down vote up
@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 File: AsyncMethodCallbacks.java    From armeria with 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 File: RpcResponse.java    From armeria with 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 File: RequestContext.java    From armeria with 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
Source File: RestSearchClient.java    From apicurio-registry with Apache License 2.0 5 votes vote down vote up
@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
Source File: DeferredResultMethodReturnValueHandler.java    From java-technology-stack with MIT License 5 votes vote down vote up
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 File: MaybeTest.java    From mug with 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
Source File: CompletableFutureTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/** 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 File: DeferredHttpResponse.java    From armeria with 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
Source File: AbstractCompletionStageTest.java    From completion-stage with Apache License 2.0 5 votes vote down vote up
@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
Source File: AbstractCompletionStageTest.java    From completion-stage with Apache License 2.0 5 votes vote down vote up
@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 File: Try.java    From java-dataloader with 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);
    });
}