List of usage examples for java.util.concurrent CompletableFuture complete
public boolean complete(T value)
From source file:io.atomix.cluster.messaging.impl.NettyMessagingService.java
private <T> void executeOnPooledConnection(Address address, String type, Function<ClientConnection, CompletableFuture<T>> callback, Executor executor, CompletableFuture<T> future) { if (address.equals(localAddress)) { callback.apply(localClientConnection).whenComplete((result, error) -> { if (error == null) { executor.execute(() -> future.complete(result)); } else { executor.execute(() -> future.completeExceptionally(error)); }/* w w w.ja v a2s. co m*/ }); return; } getChannel(address, type).whenComplete((channel, channelError) -> { if (channelError == null) { final ClientConnection connection = getOrCreateRemoteClientConnection(channel); callback.apply(connection).whenComplete((result, sendError) -> { if (sendError == null) { executor.execute(() -> future.complete(result)); } else { final Throwable cause = Throwables.getRootCause(sendError); if (!(cause instanceof TimeoutException) && !(cause instanceof MessagingException)) { channel.close().addListener(f -> { connection.close(); clientConnections.remove(channel); }); } executor.execute(() -> future.completeExceptionally(sendError)); } }); } else { executor.execute(() -> future.completeExceptionally(channelError)); } }); }
From source file:com.yahoo.pulsar.broker.service.BrokerService.java
/** * Unload all the topic served by the broker service under the given service unit * * @param serviceUnit// w ww . j a v a 2 s . c om * @return */ public CompletableFuture<Integer> unloadServiceUnit(NamespaceBundle serviceUnit) { CompletableFuture<Integer> result = new CompletableFuture<Integer>(); List<CompletableFuture<Void>> closeFutures = Lists.newArrayList(); topics.forEach((name, topicFuture) -> { DestinationName topicName = DestinationName.get(name); if (serviceUnit.includes(topicName)) { // Topic needs to be unloaded log.info("[{}] Unloading topic", topicName); closeFutures.add(topicFuture.thenCompose(Topic::close)); } }); CompletableFuture<Void> aggregator = FutureUtil.waitForAll(closeFutures); aggregator.thenAccept(res -> result.complete(closeFutures.size())).exceptionally(ex -> { result.completeExceptionally(ex); return null; }); return result; }
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.//w w w . j a v a2 s . 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.apache.distributedlog.BKLogHandler.java
private void asyncGetLastLogRecord(final Iterator<LogSegmentMetadata> ledgerIter, final CompletableFuture<LogRecordWithDLSN> promise, final boolean fence, final boolean includeControlRecord, final boolean includeEndOfStream) { if (ledgerIter.hasNext()) { LogSegmentMetadata metadata = ledgerIter.next(); asyncReadLastRecord(metadata, fence, includeControlRecord, includeEndOfStream) .whenComplete(new FutureEventListener<LogRecordWithDLSN>() { @Override//from w w w . ja v a2 s . c om public void onSuccess(LogRecordWithDLSN record) { if (null == record) { asyncGetLastLogRecord(ledgerIter, promise, fence, includeControlRecord, includeEndOfStream); } else { promise.complete(record); } } @Override public void onFailure(Throwable cause) { promise.completeExceptionally(cause); } }); } else { promise.completeExceptionally( new LogEmptyException("Log " + getFullyQualifiedName() + " has no records")); } }
From source file:org.onosproject.segmentrouting.pwaas.L2TunnelHandler.java
/** * Deletes the pseudo wire termination./* w ww . jav a 2 s . c o m*/ * * @param l2Tunnel the tunnel * @param egress the egress connect point * @param future the async task * @param direction the direction of the tunnel */ private void tearDownPseudoWireTerm(DefaultL2Tunnel l2Tunnel, ConnectPoint egress, CompletableFuture<ObjectiveError> future, Direction direction) { /* * We verify the mastership for the termination. */ String key = generateKey(l2Tunnel.tunnelId(), direction); if (!srManager.mastershipService.isLocalMaster(egress.deviceId())) { log.info("Abort delete of {} for {}: I am not the master", TERMINATION, key); if (future != null) { future.complete(null); } return; } if (!l2TerminationNextObjStore.containsKey(key)) { log.info("Abort delete of {} for {}: next does not exist in the store", TERMINATION, key); if (future != null) { future.complete(null); } return; } NextObjective nextObjective = l2TerminationNextObjStore.get(key).value(); ForwardingObjective.Builder fwdBuilder = createTermFwdObjective(l2Tunnel.pwLabel(), l2Tunnel.tunnelId(), egress.port(), nextObjective.id()); ObjectiveContext context = new DefaultObjectiveContext( (objective) -> log.debug("FwdObj for {} {} removed", TERMINATION, l2Tunnel.tunnelId()), (objective, error) -> log.warn("Failed to remove fwdObj for {} {}", TERMINATION, l2Tunnel.tunnelId(), error)); srManager.flowObjectiveService.forward(egress.deviceId(), fwdBuilder.remove(context)); context = new ObjectiveContext() { @Override public void onSuccess(Objective objective) { log.debug("Previous {} next for {} removed", TERMINATION, key); if (future != null) { future.complete(null); } } @Override public void onError(Objective objective, ObjectiveError error) { log.warn("Failed to remove previous {} next for {}: {}", TERMINATION, key, error); if (future != null) { future.complete(error); } } }; srManager.flowObjectiveService.next(egress.deviceId(), (NextObjective) nextObjective.copy().remove(context)); l2TerminationNextObjStore.remove(key); }
From source file:io.sqp.client.impl.SqpConnectionImpl.java
@Override public CompletableFuture<String> registerTypeMapping(String name, String schema, String... keywords) { CompletableFuture<String> future = new CompletableFuture<>(); if (!checkOpenAndNoErrors(future)) { return future; }/*from w w w . j av a2 s. c o m*/ ObjectMapper objectMapper = JacksonObjectMapperFactory.objectMapper(_config.getProtocolFormat()); JsonNode schemaNode; try { schemaNode = objectMapper.readTree(schema); } catch (IOException e) { SqpException error = new TypeConversionException("The schema could not be parsed: " + e.getMessage(), e); future.completeExceptionally(error); return future; } send(new TypeMappingMessage(name, schemaNode, Arrays.asList(keywords)), new ResponseHandler<>(future, m -> { if (m.isA(MessageType.ReadyMessage)) { return false; // just ignore them } else if (m.isA(MessageType.TypeMappingRegisteredMessage)) { TypeMappingRegisteredMessage response = m.secureCast(); future.complete(response.getNative()); return true; } throw new UnexpectedMessageException("waiting for information response", m); })); return future; }
From source file:io.pravega.controller.store.stream.InMemoryStream.java
@Override CompletableFuture<Integer> createNewTransaction(UUID txId, long timestamp, long leaseExpiryTime, long maxExecutionExpiryTime, long scaleGracePeriod) { Preconditions.checkNotNull(txId);/*from w ww. j a va2 s . com*/ final CompletableFuture<Integer> result = new CompletableFuture<>(); final Data<Integer> txnData = new Data<>(new ActiveTxnRecord(timestamp, leaseExpiryTime, maxExecutionExpiryTime, scaleGracePeriod, TxnStatus.OPEN).toByteArray(), 0); synchronized (txnsLock) { activeTxns.putIfAbsent(txId.toString(), txnData); } int epoch = activeEpoch.get(); synchronized (txnsLock) { if (!epochTxnMap.containsKey(epoch)) { result.completeExceptionally(StoreException.create(StoreException.Type.DATA_NOT_FOUND, "Stream: " + getName() + " Transaction: " + txId.toString() + " Epoch: " + epoch)); } else { epochTxnMap.compute(epoch, (x, y) -> { y.add(txId.toString()); return y; }); result.complete(epoch); } } return result; }
From source file:io.pravega.controller.task.Stream.StreamMetadataTasks.java
public CompletableFuture<Void> writeEvent(ControllerEvent event) { CompletableFuture<Void> result = new CompletableFuture<>(); getRequestWriter().writeEvent(event).whenComplete((r, e) -> { if (e != null) { log.warn("exception while posting event {} {}", e.getClass().getName(), e.getMessage()); if (e instanceof TaskExceptions.ProcessingDisabledException) { result.completeExceptionally(e); } else { // transform any other event write exception to retryable exception result.completeExceptionally(new TaskExceptions.PostEventException("Failed to post event", e)); }//from w w w.j av a2 s .c o m } else { log.info("event posted successfully"); result.complete(null); } }); return result; }
From source file:org.apache.pulsar.compaction.TwoPhaseCompactor.java
private CompletableFuture<Long> phaseTwoSeekThenLoop(RawReader reader, MessageId from, MessageId to, MessageId lastReadId, Map<String, MessageId> latestForKey, BookKeeper bk, LedgerHandle ledger) { CompletableFuture<Long> promise = new CompletableFuture<>(); reader.seekAsync(from).thenCompose((v) -> { Semaphore outstanding = new Semaphore(MAX_OUTSTANDING); CompletableFuture<Void> loopPromise = new CompletableFuture<Void>(); phaseTwoLoop(reader, to, latestForKey, ledger, outstanding, loopPromise); return loopPromise; }).thenCompose((v) -> closeLedger(ledger)) .thenCompose((v) -> reader.acknowledgeCumulativeAsync(lastReadId, ImmutableMap.of(COMPACTED_TOPIC_LEDGER_PROPERTY, ledger.getId()))) .whenComplete((res, exception) -> { if (exception != null) { deleteLedger(bk, ledger).whenComplete((res2, exception2) -> { if (exception2 != null) { log.warn("Cleanup of ledger {} for failed", ledger, exception2); }/* ww w .ja v a 2 s .c o m*/ // complete with original exception promise.completeExceptionally(exception); }); } else { promise.complete(ledger.getId()); } }); return promise; }
From source file:org.apache.pulsar.broker.namespace.NamespaceService.java
protected CompletableFuture<LookupResult> createLookupResult(String candidateBroker) throws Exception { CompletableFuture<LookupResult> lookupFuture = new CompletableFuture<>(); try {//from w w w . j a v a 2 s . c o m checkArgument(StringUtils.isNotBlank(candidateBroker), "Lookup broker can't be null " + candidateBroker); URI uri = new URI(candidateBroker); String path = String.format("%s/%s:%s", LoadManager.LOADBALANCE_BROKERS_ROOT, uri.getHost(), uri.getPort()); pulsar.getLocalZkCache().getDataAsync(path, pulsar.getLoadManager().get().getLoadReportDeserializer()) .thenAccept(reportData -> { if (reportData.isPresent()) { ServiceLookupData lookupData = reportData.get(); lookupFuture.complete(new LookupResult(lookupData.getWebServiceUrl(), lookupData.getWebServiceUrlTls(), lookupData.getPulsarServiceUrl(), lookupData.getPulsarServiceUrlTls())); } else { lookupFuture.completeExceptionally(new KeeperException.NoNodeException(path)); } }).exceptionally(ex -> { lookupFuture.completeExceptionally(ex); return null; }); } catch (Exception e) { lookupFuture.completeExceptionally(e); } return lookupFuture; }