Example usage for java.util.concurrent CompletableFuture completeExceptionally

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

Introduction

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

Prototype

public boolean completeExceptionally(Throwable ex) 

Source Link

Document

If not already completed, causes invocations of #get() and related methods to throw the given exception.

Usage

From source file:org.onosproject.store.consistent.impl.DistributedLeadershipManager.java

private void doWithdraw(String path, CompletableFuture<Void> future) {
    if (activeTopics.contains(path)) {
        future.completeExceptionally(
                new CancellationException(String.format("%s is now a active topic", path)));
    }/* www .j  a v a  2s .  co  m*/
    try {
        leaderMap.computeIf(path, localNodeId::equals, (topic, leader) -> null);
        candidateMap.computeIf(path, candidates -> candidates != null && candidates.contains(localNodeId),
                (topic, candidates) -> candidates.stream().filter(nodeId -> !localNodeId.equals(nodeId))
                        .collect(Collectors.toList()));
        future.complete(null);
    } catch (Exception e) {
        log.debug("Failed to verify (and clear) any lock this node might be holding for {}", path, e);
        retryWithdraw(path, future);
    }
}

From source file:org.onosproject.store.primitives.impl.CopycatTransportConnection.java

@Override
public <T, U> CompletableFuture<U> send(T message) {
    ThreadContext context = ThreadContext.currentContextOrThrow();
    CompletableFuture<U> result = new CompletableFuture<>();
    try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
        new DataOutputStream(baos).writeLong(connectionId);
        context.serializer().writeObject(message, baos);
        if (message instanceof ReferenceCounted) {
            ((ReferenceCounted<?>) message).release();
        }//from  www  . j a  v  a  2s.  c om
        messagingService.sendAndReceive(CopycatTransport.toEndpoint(remoteAddress), outboundMessageSubject,
                baos.toByteArray(), context.executor()).whenComplete((r, e) -> {
                    Throwable wrappedError = e;
                    if (e != null) {
                        Throwable rootCause = Throwables.getRootCause(e);
                        if (MessagingException.class.isAssignableFrom(rootCause.getClass())) {
                            wrappedError = new TransportException(e);
                        }
                    }
                    handleResponse(r, wrappedError, result, context);
                });
    } catch (SerializationException | IOException e) {
        result.completeExceptionally(e);
    }
    return result;
}

From source file:org.onosproject.store.primitives.impl.CopycatTransportConnection.java

private <T> void handleResponse(byte[] response, Throwable error, CompletableFuture<T> future,
        ThreadContext context) {/* w w w .  ja  va  2 s  . com*/
    if (error != null) {
        context.execute(() -> future.completeExceptionally(error));
        return;
    }
    checkNotNull(response);
    InputStream input = new ByteArrayInputStream(response);
    try {
        byte status = (byte) input.read();
        if (status == FAILURE) {
            Throwable t = context.serializer().readObject(input);
            context.execute(() -> future.completeExceptionally(t));
        } else {
            context.execute(() -> future.complete(context.serializer().readObject(input)));
        }
    } catch (IOException e) {
        context.execute(() -> future.completeExceptionally(e));
    }
}

From source file:org.openhab.binding.mqtt.generic.ChannelState.java

/**
 * Publishes a value on MQTT. A command topic needs to be set in the configuration.
 *
 * @param command The command to send/*from  w  ww .ja  v a2s  .c om*/
 * @return A future that completes with true if the publishing worked and false if it is a readonly topic
 *         and exceptionally otherwise.
 */
public CompletableFuture<Boolean> publishValue(Command command) {
    cachedValue.update(command);

    String mqttCommandValue = cachedValue.getMQTTpublishValue();

    final MqttBrokerConnection connection = this.connection;

    if (connection == null) {
        CompletableFuture<Boolean> f = new CompletableFuture<>();
        f.completeExceptionally(new IllegalStateException(
                "The connection object has not been set. start() should have been called!"));
        return f;
    }

    if (readOnly) {
        logger.debug(
                "You have tried to publish {} to the mqtt topic '{}' that was marked read-only. You can't 'set' anything on a sensor state topic for example.",
                mqttCommandValue, config.commandTopic);
        return CompletableFuture.completedFuture(false);
    }

    // Formatter: Applied before the channel state value is published to the MQTT broker.
    if (config.formatBeforePublish.length() > 0) {
        try (Formatter formatter = new Formatter()) {
            Formatter format = formatter.format(config.formatBeforePublish, mqttCommandValue);
            mqttCommandValue = format.toString();
        } catch (IllegalFormatException e) {
            logger.debug("Format pattern incorrect for {}", channelUID, e);
        }
    }
    // Outgoing transformations
    for (ChannelStateTransformation t : transformationsOut) {
        mqttCommandValue = t.processValue(mqttCommandValue);
    }
    // Send retained messages if this is a stateful channel
    return connection.publish(config.commandTopic, mqttCommandValue.getBytes(), 1, config.retained);
}

From source file:org.openhab.binding.mqtt.generic.internal.generic.ChannelState.java

/**
 * Publishes a value on MQTT. A command topic needs to be set in the configuration.
 *
 * @param command The command to send/* w  w  w .j a va 2s. c om*/
 * @return A future that completes with true if the publishing worked and false and/or exceptionally otherwise.
 */
public CompletableFuture<@Nullable Void> publishValue(Command command) {
    cachedValue.update(command);

    String mqttCommandValue = cachedValue.getMQTTpublishValue();

    final MqttBrokerConnection connection = this.connection;

    if (!readOnly && connection != null) {
        // Formatter: Applied before the channel state value is published to the MQTT broker.
        if (config.formatBeforePublish.length() > 0) {
            try (Formatter formatter = new Formatter()) {
                Formatter format = formatter.format(config.formatBeforePublish, mqttCommandValue);
                mqttCommandValue = format.toString();
            } catch (IllegalFormatException e) {
                logger.debug("Format pattern incorrect for {}", channelUID, e);
            }
        }
        // Outgoing transformations
        for (ChannelStateTransformation t : transformationsOut) {
            mqttCommandValue = t.processValue(mqttCommandValue);
        }
        // Send retained messages if this is a stateful channel
        return connection.publish(config.commandTopic, mqttCommandValue.getBytes(), 1, config.retained)
                .thenRun(() -> {
                });
    } else {
        CompletableFuture<@Nullable Void> f = new CompletableFuture<>();
        f.completeExceptionally(new IllegalStateException("No connection or readOnly channel!"));
        return f;
    }
}

From source file:org.pac4j.vertx.cas.VertxSharedDataLogoutHandler.java

@Override
public void destroySession(WebContext context) {
    final String logoutRequest = context.getRequestParameter("logoutRequest");
    LOG.debug("logoutRequest: {}", logoutRequest);
    final String ticket = StringUtils.substringBetween(logoutRequest, "SessionIndex>", "</");
    LOG.debug("extract ticket: {}", ticket);
    // get the session id first, then remove the pac4j profile from that session
    // TODO:        ALSO MODIFY TO REMOVE VERTX USER
    final CompletableFuture<Void> userLogoutFuture = new CompletableFuture<>();
    final String sessionId = getSessionId(ticket);
    sessionStore.getObservable(sessionId).map(session -> session.remove(SESSION_USER_HOLDER_KEY))
            .doOnError(e -> {/*from w  w w.  j  ava2 s .co  m*/
                e.printStackTrace();
            }).subscribe(s -> userLogoutFuture.complete(null));
    try {
        userLogoutFuture.get(blockingTimeoutSeconds, TimeUnit.SECONDS);
    } catch (InterruptedException | ExecutionException | TimeoutException e) {
        userLogoutFuture.completeExceptionally(new TechnicalException(e));
    }

    doDestroySession(ticket);
}

From source file:org.springframework.ide.eclipse.boot.dash.test.CloudFoundryClientTest.java

private Future<Void> doAsync(Thunk task) {
    CompletableFuture<Void> result = new CompletableFuture<>();
    Job job = new Job("Async task") {
        protected IStatus run(IProgressMonitor monitor) {
            try {
                task.call();/*from   w  w w.  j  ava 2 s .co m*/
                result.complete(null);
            } catch (Throwable e) {
                result.completeExceptionally(e);
            }
            return Status.OK_STATUS;
        }
    };
    job.schedule();
    return result;
}