private static <U, T> void reduceImpl(List<CompletableFuture<T>> values, int curIndex, U curValue, BiFunction<U, T, U> aggregator, CompletableFuture<U> result) { if (curIndex == values.size()) { result.complete(curValue); return; } values.get(curIndex). thenApply(oneValue -> aggregator.apply(curValue, oneValue)) .thenAccept(newValue -> reduceImpl(values, curIndex + 1, newValue, aggregator, result)); }
@Override public Task<Void> thenAccept(final Consumer<? super T> action) { final Consumer<? super T> wrap = TaskContext.wrap(action); if (defaultExecutor != null) { return from(super.thenAcceptAsync(wrap, defaultExecutor)); } return from(super.thenAccept(wrap)); }
@Override public DefaultConnectionFuture<Void> thenAccept(Consumer<? super T> action) { return adopt(delegate.thenAccept(action)); }
@Override public void close() { broadcastFuture.cancel(false); subscribeFuture.thenAccept(subscription -> subscription.close()); } }
private void unsubscribeFromEventsStream(String subscriptionId, String unsubscribeMethod) { sendAsync(unsubscribeRequest(subscriptionId, unsubscribeMethod), EthUnsubscribe.class) .thenAccept(ethUnsubscribe -> { log.debug("Successfully unsubscribed from subscription with id {}", subscriptionId); }) .exceptionally(throwable -> { log.error("Failed to unsubscribe from subscription with id {}", subscriptionId); return null; }); }
public static void main(String[] args) throws IOException { try (AsyncHttpClient asyncHttpClient = asyncHttpClient()) { asyncHttpClient .prepareGet("http://www.example.com/") .execute() .toCompletableFuture() .thenApply(Response::getResponseBody) .thenAccept(System.out::println) .join(); } } }
@Override void asyncReadEntry(PositionImpl position, AsyncCallbacks.ReadEntryCallback callback, Object ctx) { this.getLedgerHandle(position.getLedgerId()).thenAccept((ledger) -> { asyncReadEntry(ledger, position, callback, ctx); }).exceptionally((ex) -> { log.error("[{}] Error opening ledger for reading at position {} - {}", new Object[]{this.name, position, ex.getMessage()}); callback.readEntryFailed(ManagedLedgerException.getManagedLedgerException(ex.getCause()), ctx); return null; }); }
@Override public CompletableFuture<Void> thenAccept(Consumer<? super T> action) { return ctx.makeContextAware(super.thenAccept(ctx.makeContextAware(action))); }
@Override public void asyncInvoke(IN input, ResultFuture<IN> resultFuture) throws Exception { trigger.thenAccept(v -> resultFuture.complete(Collections.singleton(input))); } }
private boolean deleteClusterMeta(ClusterMetaEntity entity) { ClusterMetaType metaType = entity.getMetaType(); String metaKey = entity.getKey(); // Need to pay attention to delete metadata operations LOGGER.info("deleteClusterMeta {} {}", metaType, metaKey); if (!raftInitialized()) { LOGGER.error("Raft incomplete initialization!"); return false; } raftSessionClient.execute(operation( ClusterStateMachine.REMOVE, clientSerializer.encode(entity))) .<Long>thenApply(clientSerializer::decode) .thenAccept(result -> { LOGGER.info("deleteClusterMeta {}", result); }); return true; }
@Override public Mono<QueryResponseMessage<I>> initialResult() { return MonoWrapper.<QueryResponseMessage<I>>create(monoSinkWrapper -> query(query) .thenAccept(monoSinkWrapper::success) .exceptionally(t -> { monoSinkWrapper.error(t); return null; })).getMono(); }
/** * Opens the service context. * * @return a future to be completed once the service context has been opened */ public CompletableFuture<Void> open() { return primaryElection.getTerm() .thenAccept(this::changeRole) .thenRun(() -> service.init(this)); }
@Override public void publish(MemberId memberId, PublishRequest request) { getClient(memberId).thenAccept(protocol -> protocol.publish(request.session(), encode(request))); }
@Test public void asyncResultWithSeparateCallbacksAndValue() throws Exception { String value = "val"; final Set<String> values = new HashSet<>(1); ListenableFuture<String> future = AsyncResult.forValue(value); future.addCallback(values::add, (ex) -> fail("Failure callback not expected: " + ex)); assertSame(value, values.iterator().next()); assertSame(value, future.get()); assertSame(value, future.completable().get()); future.completable().thenAccept(v -> assertSame(value, v)); }
@Test public void successWithLambdas() throws Exception { final String s = "Hello World"; Callable<String> callable = () -> s; SuccessCallback<String> successCallback = mock(SuccessCallback.class); FailureCallback failureCallback = mock(FailureCallback.class); ListenableFutureTask<String> task = new ListenableFutureTask<>(callable); task.addCallback(successCallback, failureCallback); task.run(); verify(successCallback).onSuccess(s); verifyZeroInteractions(failureCallback); assertSame(s, task.get()); assertSame(s, task.completable().get()); task.completable().thenAccept(v -> assertSame(s, v)); }
@Test public void asyncResultWithCallbackAndValue() throws Exception { String value = "val"; final Set<String> values = new HashSet<>(1); ListenableFuture<String> future = AsyncResult.forValue(value); future.addCallback(new ListenableFutureCallback<String>() { @Override public void onSuccess(String result) { values.add(result); } @Override public void onFailure(Throwable ex) { fail("Failure callback not expected: " + ex); } }); assertSame(value, values.iterator().next()); assertSame(value, future.get()); assertSame(value, future.completable().get()); future.completable().thenAccept(v -> assertSame(value, v)); }
@SuppressWarnings({"Convert2MethodRef", "unused", "FutureReturnValueIgnored"}) private void simpleAsyncQueryExecution() throws Exception { //::FigureB GraphQL graphQL = buildSchema(); ExecutionInput executionInput = ExecutionInput.newExecutionInput().query("query { hero { name } }") .build(); CompletableFuture<ExecutionResult> promise = graphQL.executeAsync(executionInput); promise.thenAccept(executionResult -> { // here you might send back the results as JSON over HTTP encodeResultToJsonAndSendResponse(executionResult); }); promise.join(); //::/FigureB }
@Test public void testWriteHandlerSuccess() throws Exception { CompletableFuture<Void> close = new CompletableFuture<>(); server.connectHandler(socket -> { socket.pause(); close.thenAccept(v -> { socket.resume(); }); }); startServer(); client.connect(testAddress, onSuccess(so -> { writeUntilFull(so, v -> { so.write(Buffer.buffer("lost buffer"), onSuccess(ack -> testComplete())); close.complete(null); }); })); await(); }
@Test public void testWriteHandlerFailure() throws Exception { CompletableFuture<Void> close = new CompletableFuture<>(); server.connectHandler(socket -> { socket.pause(); close.thenAccept(v -> { socket.close(); }); }); startServer(); client.connect(testAddress, onSuccess(so -> { writeUntilFull(so, v -> { so.write(Buffer.buffer("lost buffer"), onFailure(err -> { testComplete(); })); close.complete(null); }); })); await(); }
@Test public void success() throws Exception { final String s = "Hello World"; Callable<String> callable = () -> s; ListenableFutureTask<String> task = new ListenableFutureTask<>(callable); task.addCallback(new ListenableFutureCallback<String>() { @Override public void onSuccess(String result) { assertEquals(s, result); } @Override public void onFailure(Throwable ex) { fail(ex.getMessage()); } }); task.run(); assertSame(s, task.get()); assertSame(s, task.completable().get()); task.completable().thenAccept(v -> assertSame(s, v)); }