List of usage examples for java.util.concurrent CompletableFuture completedFuture
public static <U> CompletableFuture<U> completedFuture(U value)
From source file:org.eclipse.smarthome.io.transport.mqtt.MqttBrokerConnection.java
/** * Remove a previously registered consumer from this connection. * If no more consumers are registered for a topic, the topic will be unsubscribed from. * * @param topic The topic to unsubscribe from. * @param subscriber The callback listener to remove. * @return Completes with true if successful. Exceptionally otherwise. *//*w w w . j a v a 2 s . co m*/ @SuppressWarnings({ "null", "unused" }) public CompletableFuture<Boolean> unsubscribe(String topic, MqttMessageSubscriber subscriber) { synchronized (subscribers) { final @Nullable List<MqttMessageSubscriber> list = subscribers.get(topic); if (list == null) { return CompletableFuture.completedFuture(true); } list.remove(subscriber); if (!list.isEmpty()) { return CompletableFuture.completedFuture(true); } // Remove from subscriber list subscribers.remove(topic); // No more subscribers to this topic. Unsubscribe topic on the broker MqttAsyncClient client = this.client; if (client != null) { return unsubscribeRaw(client, topic); } else { return CompletableFuture.completedFuture(false); } } }
From source file:org.eclipse.smarthome.io.transport.mqtt.MqttBrokerConnection.java
/** * This will establish a connection to the MQTT broker and if successful, notify all * publishers and subscribers that the connection has become active. This method will * do nothing if there is already an active connection. * * @return Returns a future that completes with true if already connected or connecting, * completes with false if a connection timeout has happened and completes exceptionally otherwise. *//*from w ww . java 2 s. c o m*/ public CompletableFuture<Boolean> start() { // We don't want multiple concurrent threads to start a connection synchronized (this) { if (connectionState() != MqttConnectionState.DISCONNECTED) { return CompletableFuture.completedFuture(true); } // Perform the connection attempt isConnecting = true; connectionObservers.forEach(o -> o.connectionStateChanged(MqttConnectionState.CONNECTING, null)); } // Ensure the reconnect strategy is started if (reconnectStrategy != null) { reconnectStrategy.start(); } // Close client if there is still one existing if (client != null) { try { client.close(); } catch (org.eclipse.paho.client.mqttv3.MqttException ignore) { } client = null; } CompletableFuture<Boolean> future = connectionCallback.createFuture(); StringBuilder serverURI = new StringBuilder(); switch (protocol) { case TCP: serverURI.append(secure ? "ssl://" : "tcp://"); break; case WEBSOCKETS: serverURI.append(secure ? "wss://" : "ws://"); break; default: future.completeExceptionally(new ConfigurationException("protocol", "Protocol unknown")); return future; } serverURI.append(host); serverURI.append(":"); serverURI.append(port); // Storage Path persistencePath = this.persistencePath; if (persistencePath == null) { persistencePath = Paths.get(ConfigConstants.getUserDataFolder()).resolve("mqtt").resolve(host); } try { persistencePath = Files.createDirectories(persistencePath); } catch (IOException e) { future.completeExceptionally(new MqttException(e)); return future; } MqttDefaultFilePersistence _dataStore = new MqttDefaultFilePersistence(persistencePath.toString()); // Create the client MqttAsyncClient _client; try { _client = createClient(serverURI.toString(), clientId, _dataStore); } catch (org.eclipse.paho.client.mqttv3.MqttException e) { future.completeExceptionally(new MqttException(e)); return future; } // Assign to object this.client = _client; this.dataStore = _dataStore; // Connect _client.setCallback(clientCallback); try { _client.connect(createMqttOptions(), null, connectionCallback); logger.info("Starting MQTT broker connection to '{}' with clientid {} and file store '{}'", host, getClientId(), persistencePath); } catch (org.eclipse.paho.client.mqttv3.MqttException | ConfigurationException e) { future.completeExceptionally(new MqttException(e)); return future; } // Connect timeout ScheduledExecutorService executor = timeoutExecutor; if (executor != null) { final ScheduledFuture<?> timeoutFuture = this.timeoutFuture .getAndSet(executor.schedule(() -> connectionCallback.onFailure(null, new TimeoutException()), timeout, TimeUnit.MILLISECONDS)); if (timeoutFuture != null) { timeoutFuture.cancel(false); } } return future; }
From source file:org.eclipse.smarthome.io.transport.mqtt.MqttBrokerConnection.java
/** * Unsubscribes from all subscribed topics, stops the reconnect strategy, disconnect and close the client. * * You can re-establish a connection calling {@link #start()} again. Do not call start, before the closing process * has finished completely.//from w ww. j a va 2s . co m * * @return Returns a future that completes as soon as the disconnect process has finished. */ public CompletableFuture<Boolean> stop() { MqttAsyncClient client = this.client; if (client == null) { return CompletableFuture.completedFuture(true); } logger.trace("Closing the MQTT broker connection '{}'", host); // Abort a connection attempt isConnecting = false; // Cancel the timeout future. If stop is called we can safely assume there is no interest in a connection // anymore. cancelTimeoutFuture(); // Stop the reconnect strategy if (reconnectStrategy != null) { reconnectStrategy.stop(); } CompletableFuture<Boolean> future = new CompletableFuture<Boolean>(); // Close connection if (client.isConnected()) { // We need to thread change here. Because paho does not allow to disconnect within a callback method unsubscribeAll().thenRunAsync(() -> { try { client.disconnect(100).waitForCompletion(100); if (client.isConnected()) { client.disconnectForcibly(); } future.complete(true); } catch (org.eclipse.paho.client.mqttv3.MqttException e) { logger.debug("Error while closing connection to broker", e); future.complete(false); } }); } else { future.complete(true); } return future.thenApply(this::finalizeStopAfterDisconnect); }
From source file:org.eclipse.smarthome.io.transport.mqtt.MqttBrokerConnection.java
/** * Publish a message to the broker with the given QoS and retained flag. * * @param topic The topic/*from ww w . ja v a2 s . com*/ * @param payload The message payload * @param qos The quality of service for this message * @param retain Set to true to retain the message on the broker * @param listener An optional listener to be notified of success or failure of the delivery. * @return Returns a future that completes with a result of true if the publishing succeeded and completes * exceptionally on an error or with a result of false if no broker connection is established. */ public CompletableFuture<Boolean> publish(String topic, byte[] payload, int qos, boolean retain) { MqttAsyncClient client = this.client; if (client == null) { return CompletableFuture.completedFuture(false); } // publish message asynchronously CompletableFuture<Boolean> f = new CompletableFuture<Boolean>(); try { client.publish(topic, payload, qos, retain, f, actionCallback); } catch (org.eclipse.paho.client.mqttv3.MqttException e) { f.completeExceptionally(new MqttException(e)); } return f; }
From source file:org.hillview.dataset.remoting.HillviewServer.java
/** * Subscriber that handles map, flatMap and zip. *//*from w w w. ja v a 2 s . c o m*/ private Subscriber<PartialResult<IDataSet>> createSubscriber(final Command command, final UUID id, final String operation, final StreamObserver<PartialResponse> responseObserver) { return new Subscriber<PartialResult<IDataSet>>() { @Nullable private PartialResponse memoizedResult = null; @Nullable private Integer memoizedDatasetIndex = null; private CompletableFuture queue = CompletableFuture.completedFuture(null); @Override public void onCompleted() { queue = queue.thenRunAsync(() -> { if (MEMOIZE && this.memoizedResult != null) { HillviewServer.this.memoizedCommands.insert(command, this.memoizedResult, Converters.checkNull(this.memoizedDatasetIndex)); } responseObserver.onCompleted(); HillviewServer.this.removeSubscription(id, operation + " completed"); }, executorService); } @Override public void onError(final Throwable e) { queue = queue.thenRunAsync(() -> { HillviewLogger.instance.error("Error when creating subscriber", e); e.printStackTrace(); responseObserver.onError(asStatusRuntimeException(e)); HillviewServer.this.removeSubscription(id, operation + " on error"); }, executorService); } @Override public void onNext(final PartialResult<IDataSet> pr) { queue = queue.thenRunAsync(() -> { Integer idsIndex = null; if (pr.deltaValue != null) { idsIndex = HillviewServer.this.save(pr.deltaValue); } final OperationResponse<PartialResult<Integer>> res = new OperationResponse<PartialResult<Integer>>( new PartialResult<Integer>(pr.deltaDone, idsIndex)); final byte[] bytes = SerializationUtils.serialize(res); final PartialResponse result = PartialResponse.newBuilder() .setSerializedOp(ByteString.copyFrom(bytes)).build(); if (MEMOIZE) { this.memoizedResult = result; this.memoizedDatasetIndex = idsIndex; } responseObserver.onNext(result); }, executorService); } }; }
From source file:org.hillview.dataset.remoting.HillviewServer.java
/** * Implementation of sketch() service in hillview.proto. *///from w w w . java 2 s.c om @Override @SuppressWarnings("unchecked") public void sketch(final Command command, final StreamObserver<PartialResponse> responseObserver) { try { final UUID commandId = this.getId(command); boolean memoize = MEMOIZE; // The value may change while we execute final IDataSet dataset = this.getIfValid(command.getIdsIndex(), responseObserver); if (dataset == null) return; if (this.respondIfReplyIsMemoized(command, responseObserver, false)) { HillviewLogger.instance.info("Found memoized sketch", "on IDataSet#{0}", command.getIdsIndex()); return; } final byte[] bytes = command.getSerializedOp().toByteArray(); final SketchOperation sketchOp = SerializationUtils.deserialize(bytes); final Observable<PartialResult> observable = dataset.sketch(sketchOp.sketch); Subscriber subscriber = new Subscriber<PartialResult>() { @Nullable private Object sketchResultAccumulator = memoize ? sketchOp.sketch.getZero() : null; private CompletableFuture queue = CompletableFuture.completedFuture(null); @Override public void onCompleted() { queue = queue.thenRunAsync(() -> { responseObserver.onCompleted(); HillviewServer.this.removeSubscription(commandId, "sketch completed"); if (memoize && this.sketchResultAccumulator != null) { final OperationResponse<PartialResult> res = new OperationResponse<PartialResult>( new PartialResult(1.0, this.sketchResultAccumulator)); final byte[] bytes = SerializationUtils.serialize(res); final PartialResponse memoizedResult = PartialResponse.newBuilder() .setSerializedOp(ByteString.copyFrom(bytes)).build(); HillviewServer.this.memoizedCommands.insert(command, memoizedResult, 0); } }, executorService); } @Override public void onError(final Throwable e) { queue = queue.thenRunAsync(() -> { HillviewLogger.instance.error("Exception in sketch", e); e.printStackTrace(); responseObserver.onError(asStatusRuntimeException(e)); HillviewServer.this.removeSubscription(commandId, "sketch onError"); }, executorService); } @Override public void onNext(final PartialResult pr) { queue = queue.thenRunAsync(() -> { if (memoize && this.sketchResultAccumulator != null) this.sketchResultAccumulator = sketchOp.sketch.add(this.sketchResultAccumulator, pr.deltaValue); final OperationResponse<PartialResult> res = new OperationResponse<PartialResult>(pr); final byte[] bytes = SerializationUtils.serialize(res); responseObserver.onNext( PartialResponse.newBuilder().setSerializedOp(ByteString.copyFrom(bytes)).build()); }, executorService); } }; final Subscription sub = observable.unsubscribeOn(ExecutorUtils.getUnsubscribeScheduler()) .subscribe(subscriber); boolean unsub = this.saveSubscription(commandId, sub, "sketch"); if (unsub) sub.unsubscribe(); } catch (final Exception e) { HillviewLogger.instance.error("Exception in sketch", e); e.printStackTrace(); responseObserver.onError(asStatusRuntimeException(e)); } }
From source file:org.jnode.net.NServerSocket.java
public CompletableFuture<NServerSocket> listen(int port) { if (isBound) { CompletableFuture cf = new CompletableFuture<>(); cf.completeExceptionally(new IllegalStateException("Server already bound")); return cf; }/*from w w w.j ava 2 s . c om*/ return createServerChannel(port).thenCompose((socketChannel) -> { this.ssc = socketChannel; return looper.register(socketChannel, SelectionKey.OP_ACCEPT, new ServerChannelEvent()); }).whenComplete((ok, ex) -> { if (ex != null && ssc != null && ssc.isOpen()) IOUtils.closeQuietly(ssc); }).thenCompose((SelectionKey selKey) -> { sk = selKey; isBound = true; return CompletableFuture.completedFuture(this); }); }
From source file:org.onosproject.store.cluster.messaging.impl.NettyMessagingManager.java
protected CompletableFuture<Void> sendAsync(Endpoint ep, InternalMessage message) { checkPermission(CLUSTER_WRITE);/*from ww w. j a v a 2 s. c o m*/ if (ep.equals(localEp)) { try { dispatchLocally(message); } catch (IOException e) { return Tools.exceptionalFuture(e); } return CompletableFuture.completedFuture(null); } CompletableFuture<Void> future = new CompletableFuture<>(); try { Connection connection = null; try { connection = channels.borrowObject(ep); connection.send(message, future); } finally { if (connection != null) { channels.returnObject(ep, connection); } } } catch (Exception e) { future.completeExceptionally(e); } return future; }
From source file:org.onosproject.store.primitives.impl.CopycatTransportConnection.java
@Override public CompletableFuture<Void> close() { closeListeners.forEach(listener -> listener.accept(this)); if (mode == CopycatTransport.Mode.CLIENT) { messagingService.unregisterHandler(inboundMessageSubject); }// w w w. j av a2 s. c o m return CompletableFuture.completedFuture(null); }
From source file:org.onosproject.store.primitives.impl.CopycatTransportServer.java
@Override public CompletableFuture<Void> close() { messagingService.unregisterHandler(messageSubject); executorService.shutdown();/* w w w . j a v a2 s .c om*/ return CompletableFuture.completedFuture(null); }