Example usage for java.util.concurrent CompletableFuture CompletableFuture

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

Introduction

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

Prototype

public CompletableFuture() 

Source Link

Document

Creates a new incomplete CompletableFuture.

Usage

From source file:org.apache.pulsar.broker.web.PulsarWebResource.java

public static CompletableFuture<ClusterData> checkLocalOrGetPeerReplicationCluster(PulsarService pulsarService,
        NamespaceName namespace) {//from   w  w  w  .  j av  a 2  s . c o m
    if (!namespace.isGlobal()) {
        return CompletableFuture.completedFuture(null);
    }
    final CompletableFuture<ClusterData> validationFuture = new CompletableFuture<>();
    final String localCluster = pulsarService.getConfiguration().getClusterName();
    final String path = AdminResource.path(POLICIES, namespace.toString());

    pulsarService.getConfigurationCache().policiesCache().getAsync(path).thenAccept(policiesResult -> {
        if (policiesResult.isPresent()) {
            Policies policies = policiesResult.get();
            if (policies.replication_clusters.isEmpty()) {
                String msg = String.format(
                        "Namespace does not have any clusters configured : local_cluster=%s ns=%s",
                        localCluster, namespace.toString());
                log.warn(msg);
                validationFuture.completeExceptionally(new RestException(Status.PRECONDITION_FAILED, msg));
            } else if (!policies.replication_clusters.contains(localCluster)) {
                ClusterData ownerPeerCluster = getOwnerFromPeerClusterList(pulsarService,
                        policies.replication_clusters);
                if (ownerPeerCluster != null) {
                    // found a peer that own this namespace
                    validationFuture.complete(ownerPeerCluster);
                    return;
                }
                String msg = String.format(
                        "Namespace missing local cluster name in clusters list: local_cluster=%s ns=%s clusters=%s",
                        localCluster, namespace.toString(), policies.replication_clusters);

                log.warn(msg);
                validationFuture.completeExceptionally(new RestException(Status.PRECONDITION_FAILED, msg));
            } else {
                validationFuture.complete(null);
            }
        } else {
            String msg = String.format("Policies not found for %s namespace", namespace.toString());
            log.error(msg);
            validationFuture.completeExceptionally(new RestException(Status.NOT_FOUND, msg));
        }
    }).exceptionally(ex -> {
        String msg = String.format(
                "Failed to validate global cluster configuration : cluster=%s ns=%s  emsg=%s", localCluster,
                namespace, ex.getMessage());
        log.error(msg);
        validationFuture.completeExceptionally(new RestException(ex));
        return null;
    });
    return validationFuture;
}

From source file:org.apache.distributedlog.lock.ZKSessionLock.java

/**
 * Try lock. If it failed, it would cleanup its attempt.
 *
 * @param wait/* ww w.  j  a  va 2 s .com*/
 *          whether to wait for ownership.
 * @param result
 *          promise to satisfy with current lock owner
 */
private void asyncTryLock(boolean wait, final CompletableFuture<String> result) {
    final CompletableFuture<String> lockResult = new CompletableFuture<String>();
    lockResult.whenComplete(new FutureEventListener<String>() {
        @Override
        public void onSuccess(String currentOwner) {
            result.complete(currentOwner);
        }

        @Override
        public void onFailure(final Throwable lockCause) {
            // If tryLock failed due to state changed, we don't need to cleanup
            if (lockCause instanceof LockStateChangedException) {
                LOG.info("skipping cleanup for {} at {} after encountering lock " + "state change exception : ",
                        new Object[] { lockId, lockPath, lockCause });
                result.completeExceptionally(lockCause);
                return;
            }
            if (LOG.isDebugEnabled()) {
                LOG.debug("{} is cleaning up its lock state for {} due to : ",
                        new Object[] { lockId, lockPath, lockCause });
            }

            // If we encountered any exception we should cleanup
            CompletableFuture<Void> unlockResult = asyncUnlock();
            unlockResult.whenComplete(new FutureEventListener<Void>() {
                @Override
                public void onSuccess(Void value) {
                    result.completeExceptionally(lockCause);
                }

                @Override
                public void onFailure(Throwable cause) {
                    result.completeExceptionally(lockCause);
                }
            });
        }
    });
    asyncTryLockWithoutCleanup(wait, lockResult);
}

From source file:org.apache.pulsar.broker.service.persistent.PersistentTopic.java

private CompletableFuture<Subscription> getDurableSubscription(String subscriptionName,
        InitialPosition initialPosition) {
    CompletableFuture<Subscription> subscriptionFuture = new CompletableFuture<>();
    ledger.asyncOpenCursor(Codec.encode(subscriptionName), initialPosition, new OpenCursorCallback() {
        @Override/*from  w w  w. j a  v a  2s  .co  m*/
        public void openCursorComplete(ManagedCursor cursor, Object ctx) {
            if (log.isDebugEnabled()) {
                log.debug("[{}][{}] Opened cursor", topic, subscriptionName);
            }

            subscriptionFuture.complete(subscriptions.computeIfAbsent(subscriptionName,
                    name -> createPersistentSubscription(subscriptionName, cursor)));
        }

        @Override
        public void openCursorFailed(ManagedLedgerException exception, Object ctx) {
            log.warn("[{}] Failed to create subscription for {}: {}", topic, subscriptionName,
                    exception.getMessage());
            USAGE_COUNT_UPDATER.decrementAndGet(PersistentTopic.this);
            subscriptionFuture.completeExceptionally(new PersistenceException(exception));
            if (exception instanceof ManagedLedgerFencedException) {
                // If the managed ledger has been fenced, we cannot continue using it. We need to close and reopen
                close();
            }
        }
    }, null);
    return subscriptionFuture;
}

From source file:org.onosproject.segmentrouting.pwaas.DefaultL2TunnelHandler.java

/**
 * Tears down connection points of pseudowires. We can either tear down both connection points,
 * or each one of them.//w w  w  .  j  a v a  2 s  .  c o m
 *
 * @param l2TunnelId The tunnel id for this pseudowire.
 * @param tearDownFirst Boolean, true if we want to tear down cp1
 * @param tearDownSecond Boolean, true if we want to tear down cp2
 * @param pending Boolean, if true remove only pseudowire from pending stores since no flows/groups
 *                in the network, else remove flows/groups in the devices also.
 * @return Result of tearing down the pseudowire, SUCCESS if everything was ok
 *         a descriptive error otherwise.
 */
private Result tearDownConnectionPoints(long l2TunnelId, boolean tearDownFirst, boolean tearDownSecond,
        boolean pending) {

    Result res;
    CompletableFuture<ObjectiveError> fwdInitNextFuture = new CompletableFuture<>();
    CompletableFuture<ObjectiveError> fwdTermNextFuture = new CompletableFuture<>();
    CompletableFuture<ObjectiveError> revInitNextFuture = new CompletableFuture<>();
    CompletableFuture<ObjectiveError> revTermNextFuture = new CompletableFuture<>();

    if (l2TunnelId == 0) {
        log.warn("Removal process : Tunnel id cannot be 0");
        return Result.WRONG_PARAMETERS.appendError("Pseudowire id can not be 0.");
    }

    res = checkIfPwExists(l2TunnelId, pending);
    if (res != Result.SUCCESS) {
        return res;
    }

    // remove and get the tunnel and the policy from the appropriate store
    // if null, return error.
    Versioned<L2Tunnel> l2TunnelVersioned = pending ? pendingL2TunnelStore.remove(Long.toString(l2TunnelId))
            : l2TunnelStore.remove(Long.toString(l2TunnelId));
    Versioned<L2TunnelPolicy> l2TunnelPolicyVersioned = pending
            ? pendingL2PolicyStore.remove(Long.toString(l2TunnelId))
            : l2PolicyStore.remove(Long.toString(l2TunnelId));
    if ((l2TunnelVersioned == null) || (l2TunnelPolicyVersioned == null)) {
        log.warn("Removal process : Policy and/or tunnel missing for tunnel id {}", l2TunnelId);
        return Result.INTERNAL_ERROR.appendError("Policy and/or tunnel missing for pseudowire!");
    }

    L2TunnelDescription pwToRemove = new DefaultL2TunnelDescription(l2TunnelVersioned.value(),
            l2TunnelPolicyVersioned.value());

    // remove the reserved transport vlan
    if (!pwToRemove.l2Tunnel().transportVlan().equals(UNTAGGED_TRANSPORT_VLAN)) {
        vlanStore.remove(pwToRemove.l2Tunnel().transportVlan());
    }

    if (pending) {
        // no need to remove flows / groups for a pseudowire
        // in pending state
        return Result.SUCCESS;
    }

    // remove flows/groups involving with this pseudowire
    if (tearDownFirst) {
        log.info("Removal process : Tearing down forward direction of pseudowire {}", l2TunnelId);

        VlanId egressVlan = determineEgressVlan(pwToRemove.l2TunnelPolicy().cP1OuterTag(),
                pwToRemove.l2TunnelPolicy().cP1InnerTag(), pwToRemove.l2TunnelPolicy().cP2OuterTag(),
                pwToRemove.l2TunnelPolicy().cP2InnerTag());
        deletePolicy(l2TunnelId, pwToRemove.l2TunnelPolicy().cP1(), pwToRemove.l2TunnelPolicy().cP1InnerTag(),
                pwToRemove.l2TunnelPolicy().cP1OuterTag(), egressVlan, fwdInitNextFuture, FWD);

        fwdInitNextFuture.thenAcceptAsync(status -> {
            if (status == null) {
                // Finally we will tear down the pseudo wire.
                tearDownPseudoWireInit(l2TunnelId, pwToRemove.l2TunnelPolicy().cP1(), fwdTermNextFuture, FWD);
            }
        });

        fwdTermNextFuture.thenAcceptAsync(status -> {
            if (status == null) {
                tearDownPseudoWireTerm(pwToRemove.l2Tunnel(), pwToRemove.l2TunnelPolicy().cP2(), null, FWD);
            }
        });
    }

    if (tearDownSecond) {
        log.info("Removal process : Tearing down reverse direction of pseudowire {}", l2TunnelId);

        VlanId egressVlan = determineEgressVlan(pwToRemove.l2TunnelPolicy().cP2OuterTag(),
                pwToRemove.l2TunnelPolicy().cP2InnerTag(), pwToRemove.l2TunnelPolicy().cP1OuterTag(),
                pwToRemove.l2TunnelPolicy().cP1InnerTag());

        // We do the same operations on the reverse side.
        deletePolicy(l2TunnelId, pwToRemove.l2TunnelPolicy().cP2(), pwToRemove.l2TunnelPolicy().cP2InnerTag(),
                pwToRemove.l2TunnelPolicy().cP2OuterTag(), egressVlan, revInitNextFuture, REV);

        revInitNextFuture.thenAcceptAsync(status -> {
            if (status == null) {
                tearDownPseudoWireInit(l2TunnelId, pwToRemove.l2TunnelPolicy().cP2(), revTermNextFuture, REV);
            }
        });

        revTermNextFuture.thenAcceptAsync(status -> {
            if (status == null) {
                tearDownPseudoWireTerm(pwToRemove.l2Tunnel(), pwToRemove.l2TunnelPolicy().cP1(), null, REV);
            }
        });
    }

    return Result.SUCCESS;
}

From source file:io.atomix.protocols.gossip.map.AntiEntropyMapDelegate.java

/**
 * Requests all updates from each peer in the provided list of peers.
 * <p>//w  w w.  j a v a 2  s  .  co  m
 * The returned future will be completed once at least one peer bootstraps this map or bootstrap requests to all peers
 * fail.
 *
 * @param peers the list of peers from which to request updates
 * @return a future to be completed once updates have been received from at least one peer
 */
private CompletableFuture<Void> requestBootstrapFromPeers(List<MemberId> peers) {
    if (peers.isEmpty()) {
        return CompletableFuture.completedFuture(null);
    }
    CompletableFuture<Void> future = new CompletableFuture<>();
    final int totalPeers = peers.size();
    AtomicBoolean successful = new AtomicBoolean();
    AtomicInteger totalCount = new AtomicInteger();
    AtomicReference<Throwable> lastError = new AtomicReference<>();

    // Iterate through all of the peers and send a bootstrap request. On the first peer that returns
    // a successful bootstrap response, complete the future. Otherwise, if no peers respond with any
    // successful bootstrap response, the future will be completed with the last exception.
    for (MemberId peer : peers) {
        requestBootstrapFromPeer(peer).whenComplete((result, error) -> {
            if (error == null) {
                if (successful.compareAndSet(false, true)) {
                    future.complete(null);
                } else if (totalCount.incrementAndGet() == totalPeers) {
                    Throwable e = lastError.get();
                    if (e != null) {
                        future.completeExceptionally(e);
                    }
                }
            } else {
                if (!successful.get() && totalCount.incrementAndGet() == totalPeers) {
                    future.completeExceptionally(error);
                } else {
                    lastError.set(error);
                }
            }
        });
    }
    return future;
}

From source file:org.apache.pulsar.client.impl.ClientCnx.java

CompletableFuture<ProducerResponse> sendRequestWithId(ByteBuf cmd, long requestId) {
    CompletableFuture<ProducerResponse> future = new CompletableFuture<>();
    pendingRequests.put(requestId, future);
    ctx.writeAndFlush(cmd).addListener(writeFuture -> {
        if (!writeFuture.isSuccess()) {
            log.warn("{} Failed to send request to broker: {}", ctx.channel(),
                    writeFuture.cause().getMessage());
            pendingRequests.remove(requestId);
            future.completeExceptionally(writeFuture.cause());
        }//w w  w  .  j a v a  2  s .c  om
    });
    requestTimeoutQueue.add(new RequestTime(System.currentTimeMillis(), requestId));
    return future;
}

From source file:org.apache.pulsar.broker.service.persistent.PersistentTopic.java

private CompletableFuture<? extends Subscription> getNonDurableSubscription(String subscriptionName,
        MessageId startMessageId) {// w ww.  ja  v  a  2s . c  o m
    CompletableFuture<Subscription> subscriptionFuture = new CompletableFuture<>();
    log.info("[{}][{}] Creating non-durable subscription at msg id {}", topic, subscriptionName,
            startMessageId);

    // Create a new non-durable cursor only for the first consumer that connects
    Subscription subscription = subscriptions.computeIfAbsent(subscriptionName, name -> {
        MessageIdImpl msgId = startMessageId != null ? (MessageIdImpl) startMessageId
                : (MessageIdImpl) MessageId.latest;

        long ledgerId = msgId.getLedgerId();
        long entryId = msgId.getEntryId();
        if (msgId instanceof BatchMessageIdImpl) {
            // When the start message is relative to a batch, we need to take one step back on the previous message,
            // because the "batch" might not have been consumed in its entirety.
            // The client will then be able to discard the first messages in the batch.
            if (((BatchMessageIdImpl) msgId).getBatchIndex() >= 0) {
                entryId = msgId.getEntryId() - 1;
            }
        }
        Position startPosition = new PositionImpl(ledgerId, entryId);
        ManagedCursor cursor = null;
        try {
            cursor = ledger.newNonDurableCursor(startPosition);
        } catch (ManagedLedgerException e) {
            subscriptionFuture.completeExceptionally(e);
        }

        return new PersistentSubscription(this, subscriptionName, cursor);
    });

    if (!subscriptionFuture.isDone()) {
        subscriptionFuture.complete(subscription);
    } else {
        // failed to initialize managed-cursor: clean up created subscription
        subscriptions.remove(subscriptionName);
    }

    return subscriptionFuture;
}

From source file:org.apache.pulsar.client.impl.ClientCnx.java

public CompletableFuture<MessageIdData> sendGetLastMessageId(ByteBuf request, long requestId) {
    CompletableFuture<MessageIdData> future = new CompletableFuture<>();

    pendingGetLastMessageIdRequests.put(requestId, future);

    ctx.writeAndFlush(request).addListener(writeFuture -> {
        if (!writeFuture.isSuccess()) {
            log.warn("{} Failed to send GetLastMessageId request to broker: {}", ctx.channel(),
                    writeFuture.cause().getMessage());
            pendingGetLastMessageIdRequests.remove(requestId);
            future.completeExceptionally(writeFuture.cause());
        }/*ww w. j  a  va  2s .c o  m*/
    });

    return future;
}

From source file:org.apache.hadoop.hbase.client.RawAsyncHBaseAdmin.java

private <PREQ, PRESP, RESP> CompletableFuture<RESP> adminCall(HBaseRpcController controller,
        AdminService.Interface stub, PREQ preq, AdminRpcCall<PRESP, PREQ> rpcCall,
        Converter<RESP, PRESP> respConverter) {
    CompletableFuture<RESP> future = new CompletableFuture<>();
    rpcCall.call(stub, controller, preq, new RpcCallback<PRESP>() {

        @Override//from w  w w  . j a v  a2 s  . com
        public void run(PRESP resp) {
            if (controller.failed()) {
                future.completeExceptionally(controller.getFailed());
            } else {
                try {
                    future.complete(respConverter.convert(resp));
                } catch (IOException e) {
                    future.completeExceptionally(e);
                }
            }
        }
    });
    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  w  w .j a  va2 s . c o  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);
}