Example usage for java.util.concurrent CompletableFuture whenComplete

List of usage examples for java.util.concurrent CompletableFuture whenComplete

Introduction

In this page you can find the example usage for java.util.concurrent CompletableFuture whenComplete.

Prototype

public CompletableFuture<T> whenComplete(BiConsumer<? super T, ? super Throwable> action) 

Source Link

Usage

From source file:net.javacrumbs.futureconverter.springjava.ListenableCompletableFutureWrapper.java

ListenableCompletableFutureWrapper(CompletableFuture<T> wrapped) {
    super(wrapped);
    wrapped.whenComplete((result, ex) -> {
        if (ex != null) {
            if (ex instanceof CompletionException && ex.getCause() != null) {
                callbackRegistry.failure(ex.getCause());
            } else {
                callbackRegistry.failure(ex);
            }/*from   ww w .ja v  a  2s . c o  m*/
        } else {
            callbackRegistry.success(result);
        }
    });
}

From source file:com.ibasco.agql.protocols.valve.source.query.client.SourceRconClient.java

/**
 * <p>Send an authentication request to the Server. Password credentials are stored into memory and can later be
 * re-used in case a re-authentication is needed.</p>
 *
 * @param address/*from   ww w .j  a  v a2 s .  co  m*/
 *         The {@link InetSocketAddress} of the source server
 * @param password
 *         A non-empty password {@link String}
 *
 * @return A {@link CompletableFuture} which returns a {@link SourceRconAuthStatus} that holds the status of the
 * authentication request.
 *
 * @throws IllegalArgumentException
 *         Thrown when the address or password supplied is empty or null
 */
public CompletableFuture<SourceRconAuthStatus> authenticate(InetSocketAddress address, String password) {
    if (StringUtils.isBlank(password) || address == null)
        throw new IllegalArgumentException("Password or Address is empty or null");

    //Remove existing meta if exists
    if (this.credentialsMap.containsKey(address)) {
        log.debug("Existing auth meta found. Removing");
        this.credentialsMap.remove(address);
    }

    int id = SourceRconUtil.createRequestId();
    log.debug("[AUTH]: Request with id: {}", id);
    CompletableFuture<SourceRconAuthStatus> authRequestFuture = sendRequest(
            new SourceRconAuthRequest(address, id, password), RequestPriority.HIGH);
    authRequestFuture.whenComplete((status, error) -> {
        log.debug("[AUTH] Response : Status: {}, Error: {}", status,
                (error != null) ? error.getMessage() : "N/A");
        if (error != null) {
            throw new SourceRconAuthException(error);
        }
        if (status != null && status.isAuthenticated()) {
            String oldPassword = this.credentialsMap.put(address, password);
            if (!StringUtils.isBlank(oldPassword)) {
                log.debug("Replaced existing auth password from '{}' to '{}'", oldPassword, password);
            }
        }
    });
    return authRequestFuture;
}

From source file:com.microsoft.azure.servicebus.samples.timetolive.TimeToLive.java

CompletableFuture pickUpAndFixDeadLetters(String connectionString, String queueName,
        IMessageSender resubmitSender, ExecutorService executorService) throws Exception {
    CompletableFuture running = new CompletableFuture();
    QueueClient receiver = new QueueClient(
            new ConnectionStringBuilder(connectionString, "BasicQueue/$deadletterqueue"), ReceiveMode.PEEKLOCK);

    running.whenComplete((r, t) -> {
        try {/*  w w w  .j  av  a 2 s  .com*/
            receiver.close();
        } catch (ServiceBusException e) {
            System.out.printf(e.getMessage());
        }
    });

    // register the RegisterMessageHandler callback
    receiver.registerMessageHandler(new IMessageHandler() {
        // callback invoked when the message handler loop has obtained a message
        public CompletableFuture<Void> onMessageAsync(IMessage message) {
            try {
                IMessage resubmitMessage = new Message(message.getBody());
                System.out.printf(
                        "\n\t\tFixing: \n\t\t\tMessageId = %s, \n\t\t\tSequenceNumber = %s, \n\t\t\tLabel = %s\n",
                        message.getMessageId(), message.getSequenceNumber(), message.getLabel());
                resubmitMessage.setMessageId(message.getMessageId());
                resubmitMessage.setLabel(message.getLabel());
                resubmitMessage.setContentType(message.getContentType());
                resubmitMessage.setTimeToLive(Duration.ofMinutes(2));

                resubmitSender.send(resubmitMessage);
                return receiver.completeAsync(message.getLockToken());
            } catch (Exception e) {
                CompletableFuture failure = new CompletableFuture();
                failure.completeExceptionally(e);
                return failure;
            }
        }

        // callback invoked when the message handler has an exception to report
        public void notifyException(Throwable throwable, ExceptionPhase exceptionPhase) {
            System.out.printf(exceptionPhase + "-" + throwable.getMessage());
        }
    },
            // 1 concurrent call, messages are auto-completed, auto-renew duration
            new MessageHandlerOptions(1, false, Duration.ofMinutes(1)), executorService);

    return running;
}

From source file:com.microsoft.azure.servicebus.samples.deadletterqueue.DeadletterQueue.java

CompletableFuture receiveMessagesAsync(String connectionString, String queueName,
        ExecutorService executorService) throws Exception {

    CompletableFuture running = new CompletableFuture();
    QueueClient receiver = new QueueClient(new ConnectionStringBuilder(connectionString, "BasicQueue"),
            ReceiveMode.PEEKLOCK);/*  w  ww.  j  a va 2s  .  c om*/

    running.whenComplete((r, t) -> {
        try {
            receiver.close();
        } catch (ServiceBusException e) {
            System.out.printf(e.getMessage());
        }
    });

    // register the RegisterMessageHandler callback
    receiver.registerMessageHandler(new IMessageHandler() {
        // callback invoked when the message handler loop has obtained a message
        public CompletableFuture<Void> onMessageAsync(IMessage message) {
            // receives message is passed to callback
            if (message.getLabel() != null && message.getContentType() != null
                    && message.getLabel().contentEquals("Scientist")
                    && message.getContentType().contentEquals("application/json")) {

                byte[] body = message.getBody();
                Map scientist = GSON.fromJson(new String(body, UTF_8), Map.class);

                System.out.printf(
                        "\n\t\t\t\tMessage received: \n\t\t\t\t\t\tMessageId = %s, \n\t\t\t\t\t\tSequenceNumber = %s, \n\t\t\t\t\t\tEnqueuedTimeUtc = %s,"
                                + "\n\t\t\t\t\t\tExpiresAtUtc = %s, \n\t\t\t\t\t\tContentType = \"%s\",  \n\t\t\t\t\t\tContent: [ firstName = %s, name = %s ]\n",
                        message.getMessageId(), message.getSequenceNumber(), message.getEnqueuedTimeUtc(),
                        message.getExpiresAtUtc(), message.getContentType(),
                        scientist != null ? scientist.get("firstName") : "",
                        scientist != null ? scientist.get("name") : "");
            } else {
                return receiver.deadLetterAsync(message.getLockToken());
            }
            return receiver.completeAsync(message.getLockToken());
        }

        // callback invoked when the message handler has an exception to report
        public void notifyException(Throwable throwable, ExceptionPhase exceptionPhase) {
            System.out.printf(exceptionPhase + "-" + throwable.getMessage());
        }
    },
            // 1 concurrent call, messages are auto-completed, auto-renew duration
            new MessageHandlerOptions(1, false, Duration.ofMinutes(1)), executorService);

    return running;
}

From source file:com.microsoft.azure.servicebus.samples.deadletterqueue.DeadletterQueue.java

CompletableFuture PickUpAndFixDeadletters(String connectionString, String queueName,
        IMessageSender resubmitSender, ExecutorService executorService) throws Exception {
    CompletableFuture running = new CompletableFuture();
    QueueClient receiver = new QueueClient(
            new ConnectionStringBuilder(connectionString, "BasicQueue/$deadletterqueue"), ReceiveMode.PEEKLOCK);

    running.whenComplete((r, t) -> {
        try {// w  w  w  .j  a v  a 2  s  .  c  om
            receiver.close();
        } catch (ServiceBusException e) {
            System.out.printf(e.getMessage());
        }
    });

    // register the RegisterMessageHandler callback
    receiver.registerMessageHandler(new IMessageHandler() {
        // callback invoked when the message handler loop has obtained a message
        public CompletableFuture<Void> onMessageAsync(IMessage message) {
            try {
                IMessage resubmitMessage = new Message(message.getBody());
                if (message.getLabel() != null && message.getLabel().contentEquals("Physicist")) {
                    System.out.printf(
                            "\n\t\tFixing: \n\t\t\tMessageId = %s, \n\t\t\tSequenceNumber = %s, \n\t\t\tLabel = %s\n",
                            message.getMessageId(), message.getSequenceNumber(), message.getLabel());
                    resubmitMessage.setMessageId(message.getMessageId());
                    resubmitMessage.setLabel("Scientist");
                    resubmitMessage.setContentType(message.getContentType());
                    resubmitMessage.setTimeToLive(Duration.ofMinutes(2));
                    resubmitSender.send(resubmitMessage);
                }
                return receiver.completeAsync(message.getLockToken());
            } catch (Exception e) {
                CompletableFuture failure = new CompletableFuture();
                failure.completeExceptionally(e);
                return failure;
            }
        }

        // callback invoked when the message handler has an exception to report
        public void notifyException(Throwable throwable, ExceptionPhase exceptionPhase) {
            System.out.printf(exceptionPhase + "-" + throwable.getMessage());
        }
    },
            // 1 concurrent call, messages are auto-completed, auto-renew duration
            new MessageHandlerOptions(1, false, Duration.ofMinutes(1)), executorService);

    return running;
}

From source file:uk.co.sdev.async.http.ning.CompletableFutureClientTest.java

@Test
public void getShouldFallbackIfResponseMapperThrowsException() throws Exception {
    stubGet("/foo", new Foo(12));

    HandOff<Foo> handOff = new HandOff<>();

    CompletableFuture<Foo> futureFoo = completableFutureClient.get("http://localhost:9101/foo", request -> {
        ;//from  w w  w .  j  a  va  2 s.  c o m
    }, (ResponseMapper<Foo>) response -> {
        throw new Exception();
    }).handle(withFallback(new Foo(0))).whenComplete((foo, t) -> {
        System.out.println("Foo:" + foo.getValue());
    });

    futureFoo.whenComplete((foo, t) -> handOff.put(foo));

    Foo foo = handOff.get(2);
    assertThat(foo.getValue(), is(0));
}

From source file:io.pravega.controller.server.SegmentHelper.java

private <ResultT> void sendRequestAsync(final WireCommand request, final ReplyProcessor replyProcessor,
        final CompletableFuture<ResultT> resultFuture, final ConnectionFactory connectionFactory,
        final PravegaNodeUri uri) {
    CompletableFuture<ClientConnection> connectionFuture = connectionFactory.establishConnection(uri,
            replyProcessor);/*ww  w.j  av  a  2s  .  com*/
    connectionFuture.whenComplete((connection, e) -> {
        if (connection == null) {
            resultFuture.completeExceptionally(new WireCommandFailedException(new ConnectionFailedException(e),
                    request.getType(), WireCommandFailedException.Reason.ConnectionFailed));
        } else {
            try {
                connection.send(request);
            } catch (ConnectionFailedException cfe) {
                throw new WireCommandFailedException(cfe, request.getType(),
                        WireCommandFailedException.Reason.ConnectionFailed);
            } catch (Exception e2) {
                throw new RuntimeException(e2);
            }
        }
    }).exceptionally(e -> {
        Throwable cause = ExceptionHelpers.getRealException(e);
        if (cause instanceof WireCommandFailedException) {
            resultFuture.completeExceptionally(cause);
        } else if (cause instanceof ConnectionFailedException) {
            resultFuture.completeExceptionally(new WireCommandFailedException(cause, request.getType(),
                    WireCommandFailedException.Reason.ConnectionFailed));
        } else {
            resultFuture.completeExceptionally(new RuntimeException(cause));
        }
        return null;
    });
    resultFuture.whenComplete((result, e) -> {
        connectionFuture.thenAccept(c -> c.close());
    });
}

From source file:ai.grakn.client.LoaderClient.java

/**
 * Send a collection of insert queries to the TasksController, blocking until
 * there is availability to send./* w ww .ja  v a 2  s.  c om*/
 *
 * Release the semaphore when a task completes.
 * If there was an error communicating with the host to get the status, throw an exception.
 *
 * @param queries Queries to be inserted
 */
private void sendQueriesToLoader(Collection<InsertQuery> queries) {
    try {
        blocker.acquire();
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    }

    try {
        String taskId = executePost(getConfiguration(queries, batchNumber.incrementAndGet()));

        CompletableFuture<Json> status = makeTaskCompletionFuture(taskId);

        // Add this status to the set of completable futures
        futures.put(status.hashCode(), status);

        // Function to execute when the task completes
        status.whenComplete((result, error) -> {
            unblock(status);

            if (error != null) {
                LOG.error(getFullStackTrace(error));
            }

            onCompletionOfTask.accept(result);
        });
    } catch (Throwable throwable) {
        LOG.error(getFullStackTrace(throwable));
        blocker.release();
    }
}

From source file:io.pravega.client.stream.mock.MockController.java

private <T> void sendRequestOverNewConnection(WireCommand request, ReplyProcessor replyProcessor,
        CompletableFuture<T> resultFuture) {
    ClientConnection connection = getAndHandleExceptions(
            connectionFactory.establishConnection(new PravegaNodeUri(endpoint, port), replyProcessor),
            RuntimeException::new);
    resultFuture.whenComplete((result, e) -> {
        connection.close();/* w  ww . j  av a  2s  .  com*/
    });
    try {
        connection.send(request);
    } catch (Exception e) {
        resultFuture.completeExceptionally(e);
    }
}

From source file:com.ibasco.agql.protocols.valve.source.query.client.SourceRconClient.java

/**
 * <p>Sends a command to the Source server. Authentication is REQUIRED</p>
 *
 * @param address// w  w  w. j  av  a 2s. co  m
 *         The {@link InetSocketAddress} of the source server
 * @param command
 *         The {@link String} containing the command to be issued on the server
 *
 * @return A {@link CompletableFuture} which contains a response {@link String} returned by the server
 *
 * @throws RconNotYetAuthException
 *         thrown if not yet authenticated to the server
 * @see #authenticate(InetSocketAddress, String)
 */
public CompletableFuture<String> execute(InetSocketAddress address, String command)
        throws RconNotYetAuthException {
    if (!isAuthenticated(address))
        throw new RconNotYetAuthException(
                "You are not yet authorized to access the server's rcon interface. Please authenticate first.");

    final Integer id = SourceRconUtil.createRequestId();

    CompletableFuture<String> response;

    SourceRconCmdRequest request = new SourceRconCmdRequest(address, id, command);

    if (reauthenticate && (_reauth != null && _reauth)) {
        log.debug("Re-authenticating from server");
        response = this.authenticate(address).thenCompose(status -> {
            if (status.isAuthenticated())
                return sendRequest(request);
            else
                return CompletableFuture.completedFuture("Unable to re-authenticate from server");
        });
    } else {
        log.debug("Executing command '{}' using request id: {}", command, id);
        response = sendRequest(request);
    }

    if (response != null)
        response.whenComplete(this::reauthOnError);

    return response;
}