List of usage examples for java.util.concurrent CompletableFuture completeExceptionally
public boolean completeExceptionally(Throwable ex)
From source file:org.apache.tinkerpop.gremlin.server.GremlinServer.java
/** * Start Gremlin Server with {@link Settings} provided to the constructor. *//*from w w w . j ava2s.c om*/ public synchronized CompletableFuture<ServerGremlinExecutor<EventLoopGroup>> start() throws Exception { if (serverStarted != null) { // server already started - don't get it rolling again return serverStarted; } serverStarted = new CompletableFuture<>(); final CompletableFuture<ServerGremlinExecutor<EventLoopGroup>> serverReadyFuture = serverStarted; try { final ServerBootstrap b = new ServerBootstrap(); // when high value is reached then the channel becomes non-writable and stays like that until the // low value is so that there is time to recover b.childOption(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, settings.writeBufferLowWaterMark); b.childOption(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, settings.writeBufferHighWaterMark); b.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT); // fire off any lifecycle scripts that were provided by the user. hooks get initialized during // ServerGremlinExecutor initialization serverGremlinExecutor.getHooks().forEach(hook -> { logger.info("Executing start up {}", LifeCycleHook.class.getSimpleName()); try { hook.onStartUp(new LifeCycleHook.Context(logger)); } catch (UnsupportedOperationException uoe) { // if the user doesn't implement onStartUp the scriptengine will throw // this exception. it can safely be ignored. } }); final Channelizer channelizer = createChannelizer(settings); channelizer.init(serverGremlinExecutor); b.group(bossGroup, workerGroup).childHandler(channelizer); if (isEpollEnabled) { b.channel(EpollServerSocketChannel.class); } else { b.channel(NioServerSocketChannel.class); } // bind to host/port and wait for channel to be ready b.bind(settings.host, settings.port).addListener(new ChannelFutureListener() { @Override public void operationComplete(final ChannelFuture channelFuture) throws Exception { if (channelFuture.isSuccess()) { ch = channelFuture.channel(); logger.info( "Gremlin Server configured with worker thread pool of {}, gremlin pool of {} and boss thread pool of {}.", settings.threadPoolWorker, settings.gremlinPool, settings.threadPoolBoss); logger.info("Channel started at port {}.", settings.port); serverReadyFuture.complete(serverGremlinExecutor); } else { serverReadyFuture.completeExceptionally(new IOException(String.format( "Could not bind to %s and %s - perhaps something else is bound to that address.", settings.host, settings.port))); } } }); } catch (Exception ex) { logger.error("Gremlin Server Error", ex); serverReadyFuture.completeExceptionally(ex); } return serverStarted; }
From source file:org.auraframework.modules.impl.ModulesCompilerJ2V8.java
private ModulesCompilerData compile(String entry, String options) throws Exception { String script = "" + "const compiler = require('" + ModulesCompilerUtil.COMPILER_JS_PATH + "');" + "const promise = compiler.compile('" + entry + "', " + options + ");" + "promise.then(onResultCallback).catch(onErrorCallback);"; CompletableFuture<ModulesCompilerData> future = new CompletableFuture<>(); JavaVoidCallback onErrorCallback = new JavaVoidCallback() { @Override/* www.j a v a2 s .c o m*/ public void invoke(final V8Object receiver, final V8Array parameters) { String error = parameters.toString(); future.completeExceptionally(new RuntimeException(error)); logger.warning("ModulesCompilerJ2v8: error " + entry + ": " + error); } }; JavaVoidCallback onResultCallback = new JavaVoidCallback() { @Override public void invoke(final V8Object receiver, final V8Array parameters) { ModulesCompilerData data = ModulesCompilerUtil.parseCompilerOutput(parameters.getObject(0)); future.complete(data); } }; NodeJS nodeJS = J2V8Util.createNodeJS(); MemoryManager memoryManager = new MemoryManager(nodeJS.getRuntime()); nodeJS.getRuntime().registerJavaMethod(onErrorCallback, "onErrorCallback"); nodeJS.getRuntime().registerJavaMethod(onResultCallback, "onResultCallback"); File tempScript = ModulesCompilerUtil.createTempScriptFile(script, "temp"); try { nodeJS.exec(tempScript); while (nodeJS.isRunning()) { nodeJS.handleMessage(); } } finally { memoryManager.release(); nodeJS.release(); tempScript.delete(); } return future.get(); }
From source file:org.eclipse.smarthome.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/*from w w w . j av a 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); } } // 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.eclipse.smarthome.io.transport.mqtt.MqttBrokerConnection.java
/** * Add a new message consumer to this connection. Multiple subscribers with the same * topic are allowed. This method will not protect you from adding a subscriber object * multiple times!//from w w w.j av a 2s . c om * * If there is a retained message for the topic, you are guaranteed to receive a callback * for each new subscriber, even for the same topic. * * @param topic The topic to subscribe to. * @param subscriber The callback listener for received messages for the given topic. * @return Completes with true if successful. Completes with false if not connected yet. Exceptionally otherwise. */ public CompletableFuture<Boolean> subscribe(String topic, MqttMessageSubscriber subscriber) { CompletableFuture<Boolean> future = new CompletableFuture<Boolean>(); synchronized (subscribers) { TopicSubscribers subscriberList = subscribers.getOrDefault(topic, new TopicSubscribers(topic)); subscribers.put(topic, subscriberList); subscriberList.add(subscriber); } final MqttAsyncClient client = this.client; if (client == null) { future.completeExceptionally(new Exception("No MQTT client")); return future; } if (client.isConnected()) { try { client.subscribe(topic, qos, future, actionCallback); } catch (org.eclipse.paho.client.mqttv3.MqttException e) { future.completeExceptionally(e); } } else { // The subscription will be performed on connecting. future.complete(false); } return future; }
From source file:org.eclipse.smarthome.io.transport.mqtt.MqttBrokerConnection.java
/** * Subscribes to a topic on the given connection, but does not alter the subscriber list. * * @param topic The topic to subscribe to. * @return Completes with true if successful. Exceptionally otherwise. *///w w w. j a v a2 s . co m protected CompletableFuture<Boolean> subscribeRaw(String topic) { logger.trace("subscribeRaw message consumer for topic '{}' from broker '{}'", topic, host); CompletableFuture<Boolean> future = new CompletableFuture<Boolean>(); try { MqttAsyncClient client = this.client; if (client != null && client.isConnected()) { client.subscribe(topic, qos, future, actionCallback); } else { future.complete(false); } } catch (org.eclipse.paho.client.mqttv3.MqttException e) { logger.info("Error subscribing to topic {}", topic, e); future.completeExceptionally(e); } return future; }
From source file:org.eclipse.smarthome.io.transport.mqtt.MqttBrokerConnection.java
/** * Unsubscribes from a topic on the given connection, but does not alter the subscriber list. * * @param client The client connection/*from w ww . j av a 2s. c o m*/ * @param topic The topic to unsubscribe from * @return Completes with true if successful. Completes with false if no broker connection is established. * Exceptionally otherwise. */ protected CompletableFuture<Boolean> unsubscribeRaw(MqttAsyncClient client, String topic) { logger.trace("Unsubscribing message consumer for topic '{}' from broker '{}'", topic, host); CompletableFuture<Boolean> future = new CompletableFuture<Boolean>(); try { if (client.isConnected()) { client.unsubscribe(topic, future, actionCallback); } else { future.complete(false); } } catch (org.eclipse.paho.client.mqttv3.MqttException e) { logger.info("Error unsubscribing topic from broker", e); future.completeExceptionally(e); } return future; }
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 www . j a va2 s .c om 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
/** * Publish a message to the broker with the given QoS and retained flag. * * @param topic The topic/* w ww . j a v a 2s . c o m*/ * @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.hyperledger.fabric.sdk.Channel.java
/** * Send transaction to one of a specified set of orderers with the specified user context. * IF there are no event hubs or eventing peers this future returns immediately completed * indicating that orderer has accepted the transaction only. * * @param proposalResponses//from w ww. j ava 2 s .c o m * @param transactionOptions * @return Future allowing access to the result of the transaction invocation. */ public CompletableFuture<TransactionEvent> sendTransaction(Collection<ProposalResponse> proposalResponses, TransactionOptions transactionOptions) { try { if (null == transactionOptions) { throw new InvalidArgumentException("Parameter transactionOptions can't be null"); } checkChannelState(); User userContext = transactionOptions.userContext != null ? transactionOptions.userContext : client.getUserContext(); userContextCheck(userContext); if (null == proposalResponses) { throw new InvalidArgumentException("sendTransaction proposalResponses was null"); } List<Orderer> orderers = transactionOptions.orderers != null ? transactionOptions.orderers : new ArrayList<>(getOrderers()); // make certain we have our own copy final List<Orderer> shuffeledOrderers = new ArrayList<>(orderers); if (transactionOptions.shuffleOrders) { Collections.shuffle(shuffeledOrderers); } if (config.getProposalConsistencyValidation()) { HashSet<ProposalResponse> invalid = new HashSet<>(); int consistencyGroups = SDKUtils.getProposalConsistencySets(proposalResponses, invalid).size(); if (consistencyGroups != 1 || !invalid.isEmpty()) { throw new IllegalArgumentException(format( "The proposal responses have %d inconsistent groups with %d that are invalid." + " Expected all to be consistent and none to be invalid.", consistencyGroups, invalid.size())); } } List<FabricProposalResponse.Endorsement> ed = new LinkedList<>(); FabricProposal.Proposal proposal = null; ByteString proposalResponsePayload = null; String proposalTransactionID = null; TransactionContext transactionContext = null; for (ProposalResponse sdkProposalResponse : proposalResponses) { ed.add(sdkProposalResponse.getProposalResponse().getEndorsement()); if (proposal == null) { proposal = sdkProposalResponse.getProposal(); proposalTransactionID = sdkProposalResponse.getTransactionID(); if (proposalTransactionID == null) { throw new InvalidArgumentException("Proposals with missing transaction ID"); } proposalResponsePayload = sdkProposalResponse.getProposalResponse().getPayload(); if (proposalResponsePayload == null) { throw new InvalidArgumentException("Proposals with missing payload."); } transactionContext = sdkProposalResponse.getTransactionContext(); if (transactionContext == null) { throw new InvalidArgumentException("Proposals with missing transaction context."); } } else { final String transactionID = sdkProposalResponse.getTransactionID(); if (transactionID == null) { throw new InvalidArgumentException("Proposals with missing transaction id."); } if (!proposalTransactionID.equals(transactionID)) { throw new InvalidArgumentException( format("Proposals with different transaction IDs %s, and %s", proposalTransactionID, transactionID)); } } } TransactionBuilder transactionBuilder = TransactionBuilder.newBuilder(); Payload transactionPayload = transactionBuilder.chaincodeProposal(proposal).endorsements(ed) .proposalResponsePayload(proposalResponsePayload).build(); Envelope transactionEnvelope = createTransactionEnvelope(transactionPayload, transactionContext); NOfEvents nOfEvents = transactionOptions.nOfEvents; if (nOfEvents == null) { nOfEvents = NOfEvents.createNofEvents(); Collection<Peer> eventingPeers = getEventingPeers(); boolean anyAdded = false; if (!eventingPeers.isEmpty()) { anyAdded = true; nOfEvents.addPeers(eventingPeers); } Collection<EventHub> eventHubs = getEventHubs(); if (!eventHubs.isEmpty()) { anyAdded = true; nOfEvents.addEventHubs(getEventHubs()); } if (!anyAdded) { nOfEvents = NOfEvents.createNoEvents(); } } else if (nOfEvents != NOfEvents.nofNoEvents) { StringBuilder issues = new StringBuilder(100); Collection<Peer> eventingPeers = getEventingPeers(); nOfEvents.unSeenPeers().forEach(peer -> { if (peer.getChannel() != this) { issues.append(format("Peer %s added to NOFEvents does not belong this channel. ", peer.getName())); } else if (!eventingPeers.contains(peer)) { issues.append(format("Peer %s added to NOFEvents is not a eventing Peer in this channel. ", peer.getName())); } }); nOfEvents.unSeenEventHubs().forEach(eventHub -> { if (!eventHubs.contains(eventHub)) { issues.append(format("Eventhub %s added to NOFEvents does not belong this channel. ", eventHub.getName())); } }); if (nOfEvents.unSeenEventHubs().isEmpty() && nOfEvents.unSeenPeers().isEmpty()) { issues.append("NofEvents had no Eventhubs added or Peer eventing services."); } String foundIssues = issues.toString(); if (!foundIssues.isEmpty()) { throw new InvalidArgumentException(foundIssues); } } final boolean replyonly = nOfEvents == NOfEvents.nofNoEvents || (getEventHubs().isEmpty() && getEventingPeers().isEmpty()); CompletableFuture<TransactionEvent> sret; if (replyonly) { //If there are no eventhubs to complete the future, complete it // immediately but give no transaction event logger.debug(format( "Completing transaction id %s immediately no event hubs or peer eventing services found in channel %s.", proposalTransactionID, name)); sret = new CompletableFuture<>(); } else { sret = registerTxListener(proposalTransactionID, nOfEvents, transactionOptions.failFast); } logger.debug(format("Channel %s sending transaction to orderer(s) with TxID %s ", name, proposalTransactionID)); boolean success = false; Exception lException = null; // Save last exception to report to user .. others are just logged. BroadcastResponse resp = null; Orderer failed = null; for (Orderer orderer : shuffeledOrderers) { if (failed != null) { logger.warn(format("Channel %s %s failed. Now trying %s.", name, failed, orderer)); } failed = orderer; try { if (null != diagnosticFileDumper) { logger.trace(format("Sending to channel %s, orderer: %s, transaction: %s", name, orderer.getName(), diagnosticFileDumper .createDiagnosticProtobufFile(transactionEnvelope.toByteArray()))); } resp = orderer.sendTransaction(transactionEnvelope); lException = null; // no longer last exception .. maybe just failed. if (resp.getStatus() == Status.SUCCESS) { success = true; break; } else { logger.warn(format("Channel %s %s failed. Status returned %s", name, orderer, getRespData(resp))); } } catch (Exception e) { String emsg = format("Channel %s unsuccessful sendTransaction to orderer %s (%s)", name, orderer.getName(), orderer.getUrl()); if (resp != null) { emsg = format("Channel %s unsuccessful sendTransaction to orderer %s (%s). %s", name, orderer.getName(), orderer.getUrl(), getRespData(resp)); } logger.error(emsg); lException = new Exception(emsg, e); } } if (success) { logger.debug(format("Channel %s successful sent to Orderer transaction id: %s", name, proposalTransactionID)); if (replyonly) { sret.complete(null); // just say we're done. } return sret; } else { String emsg = format( "Channel %s failed to place transaction %s on Orderer. Cause: UNSUCCESSFUL. %s", name, proposalTransactionID, getRespData(resp)); unregisterTxListener(proposalTransactionID); CompletableFuture<TransactionEvent> ret = new CompletableFuture<>(); ret.completeExceptionally( lException != null ? new Exception(emsg, lException) : new Exception(emsg)); return ret; } } catch (Exception e) { CompletableFuture<TransactionEvent> future = new CompletableFuture<>(); future.completeExceptionally(e); return future; } }
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 ww w .j av a2 s. c o m 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); }); }