Example usage for java.util.concurrent CompletableFuture completedFuture

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

Introduction

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

Prototype

public static <U> CompletableFuture<U> completedFuture(U value) 

Source Link

Document

Returns a new CompletableFuture that is already completed with the given value.

Usage

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

@Override
public CompletableFuture<Void> destroy() {
    destroyed = true;//w  w  w . j  a  va  2  s  .co m

    executor.shutdown();
    backgroundExecutor.shutdown();
    communicationExecutor.shutdown();

    listeners.clear();

    clusterCommunicator.removeSubscriber(updateMessageSubject);
    clusterCommunicator.removeSubscriber(updateRequestSubject);
    clusterCommunicator.removeSubscriber(antiEntropyAdvertisementSubject);
    return CompletableFuture.completedFuture(null);
}

From source file:org.onosproject.tl1.impl.DefaultTl1Controller.java

@Override
/**//from  ww w  .j  av  a 2  s  . co  m
 * This implementation returns an empty string on failure.
 */
public CompletableFuture<String> sendMsg(DeviceId deviceId, Tl1Command msg) {
    log.debug("Sending TL1 message to device {}: {}", deviceId, msg);

    Tl1Device device = deviceMap.get(deviceId);
    if (device == null || !device.isConnected() || !mastershipService.isLocalMaster(deviceId)) {
        return CompletableFuture.completedFuture(StringUtils.EMPTY);
    }

    // Create and store completable future, complete it in the channel handler when we receive a response
    CompletableFuture<String> future = new CompletableFuture<>();
    Channel channel = device.channel();
    if (!msgMap.containsKey(channel)) {
        return CompletableFuture.completedFuture(StringUtils.EMPTY);
    }
    msgMap.get(channel).put(msg.ctag(), future);

    // Write message to channel
    channel.writeAndFlush(Unpooled.copiedBuffer(msg.toString(), CharsetUtil.UTF_8));

    return future;
}

From source file:org.openbase.display.DisplayView.java

private <V> Future<V> runTask(final Callable<V> callable) throws CouldNotPerformException {
    try {/* ww w  .  j  av a  2s .c om*/

        if (Platform.isFxApplicationThread()) {
            try {
                return CompletableFuture.completedFuture(callable.call());
            } catch (Exception ex) {
                ExceptionPrinter.printHistory(new CouldNotPerformException("Could not perform task!", ex),
                        logger);
            }
        }

        FutureTask<V> future = new FutureTask(() -> {
            try {
                return callable.call();
            } catch (Exception ex) {
                throw ExceptionPrinter.printHistoryAndReturnThrowable(ex, logger);
            }
        });
        Platform.runLater(future);
        return future;
    } catch (Exception ex) {
        throw new CouldNotPerformException("Could not perform task!", ex);
    }
}

From source file:org.opendaylight.netvirt.federation.plugin.FederationPluginIngress.java

@Override
public synchronized CompletableFuture<Void> abort() {
    logger.info("Abort Netvirt ingress plugin for remoteIp {}", remoteIp);
    aborted = true;//from w  w w  . java 2s. c o m
    return CompletableFuture.completedFuture(null);
}

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

/**
 * Subscribes to the state topic on the given connection and informs about updates on the given listener.
 *
 * @param connection A broker connection
 * @param scheduler A scheduler to realize the timeout
 * @param timeout A timeout in milliseconds. Can be 0 to disable the timeout and let the future return earlier.
 * @param channelStateUpdateListener An update listener
 * @return A future that completes with true if the subscribing worked, with false if the stateTopic is not set
 *         and exceptionally otherwise./* w  ww  .  j  a  v  a  2s .co m*/
 */
public CompletableFuture<@Nullable Void> start(MqttBrokerConnection connection,
        ScheduledExecutorService scheduler, int timeout) {
    if (hasSubscribed) {
        return CompletableFuture.completedFuture(null);
    }

    this.connection = connection;

    if (StringUtils.isBlank(config.stateTopic)) {
        return CompletableFuture.completedFuture(null);
    }

    this.future = new CompletableFuture<>();
    connection.subscribe(config.stateTopic, this).thenRun(() -> {
        hasSubscribed = true;
        logger.debug("Subscribed channel {} to topic: {}", this.channelUID, config.stateTopic);
        if (timeout > 0 && !future.isDone()) {
            this.scheduledFuture = scheduler.schedule(this::receivedOrTimeout, timeout, TimeUnit.MILLISECONDS);
        } else {
            receivedOrTimeout();
        }
    }).exceptionally(this::subscribeFail);
    return future;
}

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// w ww  . j ava 2s  .  co  m
 * @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.homeassistant.internal.AbstractComponent.java

/**
 * Subscribes to all state channels of the component and adds all channels to the provided channel type provider.
 *
 * @param connection The connection/*  w w  w .ja v a2  s.  co m*/
 * @param channelStateUpdateListener A listener
 * @return A future that completes as soon as all subscriptions have been performed. Completes exceptionally on
 *         errors.
 */
public CompletableFuture<@Nullable Void> start(MqttBrokerConnection connection,
        ScheduledExecutorService scheduler, int timeout) {
    return channels.values().stream().map(v -> v.start(connection, scheduler, timeout))
            .reduce(CompletableFuture.completedFuture(null), (f, v) -> f.thenCompose(b -> v));
}

From source file:org.openhab.binding.mqtt.homeassistant.internal.AbstractComponent.java

/**
 * Unsubscribe from all state channels of the component.
 *
 * @return A future that completes as soon as all subscriptions removals have been performed. Completes
 *         exceptionally on errors./* w  w  w.j  ava 2 s .c  o m*/
 */
public CompletableFuture<@Nullable Void> stop() {
    return channels.values().stream().map(v -> v.stop()).reduce(CompletableFuture.completedFuture(null),
            (f, v) -> f.thenCompose(b -> v));
}

From source file:org.openhab.binding.mqtt.homeassistant.internal.handler.HomeAssistantThingHandler.java

@Override
public void dispose() {
    discoverComponents.stopDiscovery();/*from w  ww . j a v  a 2  s  .c  o  m*/
    delayedProcessing.join();

    haComponents.values().forEach(c -> c.removeChannelTypes(channelTypeProvider));

    // Unsubscribe from all components and component channel MQTT topics and more importantly
    // remove the reference to this handler.
    try {
        haComponents.values().stream().map(e -> e.stop())
                .reduce(CompletableFuture.completedFuture(null), (a, v) -> a.thenCompose(b -> v))
                .get(500, TimeUnit.MILLISECONDS);
    } catch (InterruptedException | ExecutionException | TimeoutException ignore) {
        // Ignore any interrupts and timeouts on finish
    }
    super.dispose();
}

From source file:org.openhab.binding.mqtt.homeassistant.internal.handler.HomeAssistantThingHandler.java

/**
 * Start a background discovery for the configured HA MQTT object-id.
 *///  w  w  w . j a v  a2 s .  com
@Override
protected CompletableFuture<@Nullable Void> start(MqttBrokerConnection connection) {
    connection.setRetain(true);
    connection.setQos(1);

    updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.GONE, "No response from the device yet");

    // Start all known components and channels within the components and put the Thing offline
    // if any subscribing failed ( == broker connection lost)
    CompletableFuture<@Nullable Void> future = haComponents.values().stream()
            .map(e -> e.start(connection, scheduler, attributeReceiveTimeout))
            .reduce(CompletableFuture.completedFuture(null), (a, v) -> a.thenCompose(b -> v)) // reduce to one
            .exceptionally(e -> {
                updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, e.getMessage());
                return null;
            });

    return future
            .thenCompose(b -> discoverComponents.startDiscovery(connection, 0, discoveryHomeAssistantID, this));
}