Example usage for java.util.concurrent CompletableFuture complete

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

Introduction

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

Prototype

public boolean complete(T value) 

Source Link

Document

If not already completed, sets the value returned by #get() and related methods to the given value.

Usage

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

CompletableFuture<HRegionLocation> getRegionLocation() {
    for (;;) {/*from ww w.ja v a 2  s .c o  m*/
        HRegionLocation metaRegionLocation = this.metaRegionLocation.get();
        if (metaRegionLocation != null) {
            return CompletableFuture.completedFuture(metaRegionLocation);
        }
        if (LOG.isTraceEnabled()) {
            LOG.trace("Meta region location cache is null, try fetching from registry.");
        }
        if (metaRelocateFuture.compareAndSet(null, new CompletableFuture<>())) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Start fetching meta region location from registry.");
            }
            CompletableFuture<HRegionLocation> future = metaRelocateFuture.get();
            registry.getMetaRegionLocation().whenComplete((locs, error) -> {
                if (error != null) {
                    if (LOG.isDebugEnabled()) {
                        LOG.debug("Failed to fetch meta region location from registry", error);
                    }
                    metaRelocateFuture.getAndSet(null).completeExceptionally(error);
                    return;
                }
                HRegionLocation loc = locs.getDefaultRegionLocation();
                if (LOG.isDebugEnabled()) {
                    LOG.debug("The fetched meta region location is " + loc);
                }
                // Here we update cache before reset future, so it is possible that someone can get a
                // stale value. Consider this:
                // 1. update cache
                // 2. someone clear the cache and relocate again
                // 3. the metaRelocateFuture is not null so the old future is used.
                // 4. we clear metaRelocateFuture and complete the future in it with the value being
                // cleared in step 2.
                // But we do not think it is a big deal as it rarely happens, and even if it happens, the
                // caller will retry again later, no correctness problems.
                this.metaRegionLocation.set(loc);
                metaRelocateFuture.set(null);
                future.complete(loc);
            });
        } else {
            CompletableFuture<HRegionLocation> future = metaRelocateFuture.get();
            if (future != null) {
                return future;
            }
        }
    }
}

From source file:org.apache.bookkeeper.mledger.impl.OffloadPrefixTest.java

public void offloadThreeOneFails(int failIndex) throws Exception {
    CompletableFuture<Set<Long>> promise = new CompletableFuture<>();
    MockLedgerOffloader offloader = new ErroringMockLedgerOffloader(promise);
    ManagedLedgerConfig config = new ManagedLedgerConfig();
    config.setMaxEntriesPerLedger(10);//w ww . ja  v  a  2  s .c o m
    config.setMinimumRolloverTime(0, TimeUnit.SECONDS);
    config.setRetentionTime(10, TimeUnit.MINUTES);
    config.setLedgerOffloader(offloader);
    ManagedLedgerImpl ledger = (ManagedLedgerImpl) factory.open("my_test_ledger", config);

    int i = 0;
    for (; i < 35; i++) {
        String content = "entry-" + i;
        ledger.addEntry(content.getBytes());
    }
    Assert.assertEquals(ledger.getLedgersInfoAsList().size(), 4);

    // mark ledgers to fail
    promise.complete(ImmutableSet.of(ledger.getLedgersInfoAsList().get(failIndex).getLedgerId()));

    try {
        ledger.offloadPrefix(ledger.getLastConfirmedEntry());
    } catch (ManagedLedgerException e) {
        Assert.assertEquals(e.getCause().getClass(), CompletionException.class);
    }

    Assert.assertEquals(ledger.getLedgersInfoAsList().size(), 4);
    Assert.assertEquals(ledger.getLedgersInfoAsList().stream().filter(e -> e.getOffloadContext().getComplete())
            .map(e -> e.getLedgerId()).collect(Collectors.toSet()), offloader.offloadedLedgers());
    Assert.assertEquals(
            ledger.getLedgersInfoAsList().stream().filter(e -> e.getOffloadContext().getComplete()).count(), 2);
    Assert.assertFalse(ledger.getLedgersInfoAsList().get(failIndex).getOffloadContext().getComplete());
}

From source file:org.apache.pulsar.broker.authorization.PulsarAuthorizationProvider.java

/**
 * Check if the specified role has permission to receive messages from the specified fully qualified topic
 * name.//from w ww .  j a  va 2  s. c o m
 *
 * @param topicName
 *            the fully qualified topic name associated with the topic.
 * @param role
 *            the app id used to receive messages from the topic.
 * @param subscription
 *            the subscription name defined by the client
 */
@Override
public CompletableFuture<Boolean> canConsumeAsync(TopicName topicName, String role,
        AuthenticationDataSource authenticationData, String subscription) {
    CompletableFuture<Boolean> permissionFuture = new CompletableFuture<>();
    try {
        configCache.policiesCache().getAsync(POLICY_ROOT + topicName.getNamespace()).thenAccept(policies -> {
            if (!policies.isPresent()) {
                if (log.isDebugEnabled()) {
                    log.debug("Policies node couldn't be found for topic : {}", topicName);
                }
            } else {
                if (isNotBlank(subscription)) {
                    // validate if role is authorize to access subscription. (skip validatation if authorization
                    // list is empty)
                    Set<String> roles = policies.get().auth_policies.subscription_auth_roles.get(subscription);
                    if (roles != null && !roles.isEmpty() && !roles.contains(role)) {
                        log.warn("[{}] is not authorized to subscribe on {}-{}", role, topicName, subscription);
                        PulsarServerException ex = new PulsarServerException(
                                String.format("%s is not authorized to access subscription %s on topic %s",
                                        role, subscription, topicName));
                        permissionFuture.complete(false);
                        return;
                    }

                    // validate if subscription-auth mode is configured
                    switch (policies.get().subscription_auth_mode) {
                    case Prefix:
                        if (!subscription.startsWith(role)) {
                            PulsarServerException ex = new PulsarServerException(String.format(
                                    "Failed to create consumer - The subscription name needs to be prefixed by the authentication role, like %s-xxxx for topic: %s",
                                    role, topicName));
                            permissionFuture.completeExceptionally(ex);
                            return;
                        }
                        break;
                    default:
                        break;
                    }
                }
            }
            // check namespace and topic level consume-permissions
            checkAuthorization(topicName, role, AuthAction.consume).thenAccept(isAuthorized -> {
                permissionFuture.complete(isAuthorized);
            });
        }).exceptionally(ex -> {
            log.warn("Client with Role - {} failed to get permissions for topic - {}. {}", role, topicName,
                    ex.getMessage());
            permissionFuture.completeExceptionally(ex);
            return null;
        });
    } catch (Exception e) {
        log.warn("Client  with Role - {} failed to get permissions for topic - {}. {}", role, topicName,
                e.getMessage());
        permissionFuture.completeExceptionally(e);
    }
    return permissionFuture;
}

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

private void interceptAndComplete(final Message<T> message,
        final CompletableFuture<Message<T>> receivedFuture) {
    // call proper interceptor
    final Message<T> interceptMessage = beforeConsume(message);
    // return message to receivedCallback
    listenerExecutor.execute(() -> receivedFuture.complete(interceptMessage));
}

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!// w  w w. jav a2  s  . 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:io.pravega.controller.store.stream.InMemoryStream.java

@Override
CompletableFuture<Void> sealActiveTx(int epoch, UUID txId, boolean commit, ActiveTxnRecord txnRecord,
        int version) {
    Preconditions.checkNotNull(txId);//from   www  .  java 2  s  . co m

    CompletableFuture<Void> result = new CompletableFuture<>();
    synchronized (txnsLock) {
        if (!activeTxns.containsKey(txId.toString())) {
            result.completeExceptionally(StoreException.create(StoreException.Type.DATA_NOT_FOUND,
                    "Stream: " + getName() + " Transaction: " + txId.toString()));
        } else {
            activeTxns.compute(txId.toString(), (x, y) -> {
                if (version != y.getVersion()) {
                    result.completeExceptionally(StoreException.create(StoreException.Type.WRITE_CONFLICT,
                            "Stream: " + getName() + " Transaction: " + txId.toString()));
                    return y;
                } else {
                    ActiveTxnRecord previous = ActiveTxnRecord.parse(y.getData());
                    ActiveTxnRecord updated = new ActiveTxnRecord(previous.getTxCreationTimestamp(),
                            previous.getLeaseExpiryTime(), previous.getMaxExecutionExpiryTime(),
                            previous.getScaleGracePeriod(), commit ? TxnStatus.COMMITTING : TxnStatus.ABORTING);
                    result.complete(null);
                    return new Data<>(updated.toByteArray(), y.getVersion() + 1);
                }
            });
        }
    }
    return result;
}

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

public CompletableFuture<Boolean> hasMessageAvailableAsync() {
    final CompletableFuture<Boolean> booleanFuture = new CompletableFuture<>();

    if (lastMessageIdInBroker.compareTo(lastDequeuedMessage) > 0
            && ((MessageIdImpl) lastMessageIdInBroker).getEntryId() != -1) {
        booleanFuture.complete(true);
    } else {//ww w .  j av a 2 s . co  m
        getLastMessageIdAsync().thenAccept(messageId -> {
            lastMessageIdInBroker = messageId;
            if (lastMessageIdInBroker.compareTo(lastDequeuedMessage) > 0
                    && ((MessageIdImpl) lastMessageIdInBroker).getEntryId() != -1) {
                booleanFuture.complete(true);
            } else {
                booleanFuture.complete(false);
            }
        }).exceptionally(e -> {
            log.error("[{}][{}] Failed getLastMessageId command", topic, subscription);
            booleanFuture.completeExceptionally(e.getCause());
            return null;
        });
    }
    return booleanFuture;
}

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

/**
 * Deletes the pseudo wire initiation./*from   w w  w.  j  a va  2s. c  om*/
 *
 * @param l2TunnelId the tunnel id
 * @param ingress    the ingress connect point
 * @param future     to perform an async operation
 * @param direction  the direction: reverse of forward
 */
private void tearDownPseudoWireInit(long l2TunnelId, ConnectPoint ingress,
        CompletableFuture<ObjectiveError> future, Direction direction) {

    String key = generateKey(l2TunnelId, direction);
    if (!l2InitiationNextObjStore.containsKey(key)) {
        log.info("Abort delete of {} for {}: next does not exist in the store", INITIATION, key);
        if (future != null) {
            future.complete(null);
        }
        return;
    }

    // un-comment in case you want to delete groups used by the pw
    // however, this will break the update of pseudowires cause the L2 interface group can
    // not be deleted (it is referenced by other groups)
    /*
    NextObjective nextObjective = l2InitiationNextObjStore.get(key).value();
    ObjectiveContext context = new ObjectiveContext() {
    @Override
    public void onSuccess(Objective objective) {
        log.debug("Previous {} next for {} removed", INITIATION, key);
        if (future != null) {
            future.complete(null);
        }
    }
            
    @Override
    public void onError(Objective objective, ObjectiveError error) {
        log.warn("Failed to remove previous {} next for {}: {}", INITIATION, key, error);
        if (future != null) {
            future.complete(error);
        }
    }
    };
    srManager.flowObjectiveService.next(ingress.deviceId(), (NextObjective) nextObjective.copy().remove(context));
    */

    future.complete(null);
    l2InitiationNextObjStore.remove(key);
}

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

/**
 * Deletes a given policy using the parameter supplied.
 *
 * @param tunnelId     the tunnel id/*from  www. ja va2s .c om*/
 * @param ingress      the ingress point
 * @param ingressInner the ingress inner vlan id
 * @param ingressOuter the ingress outer vlan id
 * @param future       to perform the async operation
 * @param direction    the direction: forward or reverse
 */
private void deletePolicy(long tunnelId, ConnectPoint ingress, VlanId ingressInner, VlanId ingressOuter,
        VlanId egressVlan, CompletableFuture<ObjectiveError> future, Direction direction) {

    String key = generateKey(tunnelId, direction);
    if (!l2InitiationNextObjStore.containsKey(key)) {
        log.warn("Abort delete of policy for tunnel {}: next does not exist in the store", tunnelId);
        if (future != null) {
            future.complete(null);
        }
        return;
    }
    NextObjective nextObjective = l2InitiationNextObjStore.get(key).value();
    int nextId = nextObjective.id();
    List<Objective> objectives = Lists.newArrayList();
    // We create the forwarding objective.
    ForwardingObjective.Builder fwdBuilder = createInitFwdObjective(tunnelId, ingress.port(), nextId);
    ObjectiveContext context = new ObjectiveContext() {
        @Override
        public void onSuccess(Objective objective) {
            log.debug("Previous fwdObj for policy {} removed", tunnelId);
            if (future != null) {
                future.complete(null);
            }
        }

        @Override
        public void onError(Objective objective, ObjectiveError error) {
            log.warn("Failed to remove previous fwdObj for policy {}: {}", tunnelId, error);
            if (future != null) {
                future.complete(error);
            }
        }
    };
    objectives.add(fwdBuilder.remove(context));
    // We create the filtering objective to define the
    // permit traffic in the switch
    FilteringObjective.Builder filtBuilder = createFiltObjective(ingress.port(), ingressInner, ingressOuter);
    TrafficTreatment.Builder treatment = DefaultTrafficTreatment.builder().setTunnelId(tunnelId)
            .setVlanId(egressVlan);
    filtBuilder.withMeta(treatment.build());
    context = new DefaultObjectiveContext((objective) -> log.debug("FilterObj for policy {} revoked", tunnelId),
            (objective, error) -> log.warn("Failed to revoke filterObj for policy {}", tunnelId, error));
    objectives.add(filtBuilder.remove(context));

    for (Objective objective : objectives) {
        if (objective instanceof ForwardingObjective) {
            srManager.flowObjectiveService.forward(ingress.deviceId(), (ForwardingObjective) objective);
        } else {
            srManager.flowObjectiveService.filter(ingress.deviceId(), (FilteringObjective) objective);
        }
    }
}

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

private void cleanupAtClose(CompletableFuture<Void> closeFuture) {
    log.info("[{}] [{}] Closed consumer", topic, subscription);
    setState(State.Closed);//from   w  w w .java2 s .  c o  m
    unAckedMessageTracker.close();
    if (possibleSendToDeadLetterTopicMessages != null) {
        possibleSendToDeadLetterTopicMessages.clear();
    }
    closeFuture.complete(null);
    client.cleanupConsumer(this);
    // fail all pending-receive futures to notify application
    failPendingReceive();
}