Example usage for java.util.concurrent CompletableFuture completedFuture

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

Introduction

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

Prototype

public static <U> CompletableFuture<U> completedFuture(U value) 

Source Link

Document

Returns a new CompletableFuture that is already completed with the given value.

Usage

From source file:org.apache.james.sieve.cassandra.CassandraSieveRepository.java

private CompletableFuture<Boolean> updateScriptActivation(String user, String scriptName, boolean active) {
    if (!scriptName.equals(SieveRepository.NO_SCRIPT_NAME)) {
        return cassandraSieveDAO.updateScriptActivation(user, scriptName, active);
    }/*from  w  ww. ja v a 2s  .  c o  m*/
    return CompletableFuture.completedFuture(true);
}

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

/**
 * Check if the specified role has permission to send messages to the specified fully qualified topic name.
 *
 * @param topicName//from  w w  w .  ja va 2 s  .  c  o  m
 *            the fully qualified topic name associated with the topic.
 * @param role
 *            the app id used to send messages to the topic.
 */
public CompletableFuture<Boolean> canProduceAsync(TopicName topicName, String role,
        AuthenticationDataSource authenticationData) {

    if (!this.conf.isAuthorizationEnabled()) {
        return CompletableFuture.completedFuture(true);
    }
    if (provider != null) {
        return provider.isSuperUser(role, conf).thenComposeAsync(isSuperUser -> {
            if (isSuperUser) {
                return CompletableFuture.completedFuture(true);
            } else {
                return provider.canProduceAsync(topicName, role, authenticationData);
            }
        });
    }
    return FutureUtil.failedFuture(new IllegalStateException("No authorization provider configured"));
}

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

/**
 * Check if the specified role has permission to receive messages from the specified fully qualified topic name.
 *
 * @param topicName/*from  w  w w. j  a va2s . c  o  m*/
 *            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
 */
public CompletableFuture<Boolean> canConsumeAsync(TopicName topicName, String role,
        AuthenticationDataSource authenticationData, String subscription) {
    if (!this.conf.isAuthorizationEnabled()) {
        return CompletableFuture.completedFuture(true);
    }
    if (provider != null) {
        return provider.isSuperUser(role, conf).thenComposeAsync(isSuperUser -> {
            if (isSuperUser) {
                return CompletableFuture.completedFuture(true);
            } else {
                return provider.canConsumeAsync(topicName, role, authenticationData, subscription);
            }
        });
    }
    return FutureUtil.failedFuture(new IllegalStateException("No authorization provider configured"));
}

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

@Override
public CompletableFuture<Void> checkReplication() {
    TopicName name = TopicName.get(topic);
    if (!name.isGlobal()) {
        return CompletableFuture.completedFuture(null);
    }//  w w w .ja  v a  2  s.  com

    if (log.isDebugEnabled()) {
        log.debug("[{}] Checking replication status", name);
    }

    Policies policies = null;
    try {
        policies = brokerService.pulsar().getConfigurationCache().policiesCache()
                .get(AdminResource.path(POLICIES, name.getNamespace()))
                .orElseThrow(() -> new KeeperException.NoNodeException());
    } catch (Exception e) {
        CompletableFuture<Void> future = new CompletableFuture<>();
        future.completeExceptionally(new ServerMetadataException(e));
        return future;
    }

    final int newMessageTTLinSeconds = policies.message_ttl_in_seconds;

    Set<String> configuredClusters;
    if (policies.replication_clusters != null) {
        configuredClusters = Sets.newTreeSet(policies.replication_clusters);
    } else {
        configuredClusters = Collections.emptySet();
    }

    String localCluster = brokerService.pulsar().getConfiguration().getClusterName();

    // if local cluster is removed from global namespace cluster-list : then delete topic forcefully because pulsar
    // doesn't serve global topic without local repl-cluster configured.
    if (TopicName.get(topic).isGlobal() && !configuredClusters.contains(localCluster)) {
        log.info("Deleting topic [{}] because local cluster is not part of global namespace repl list {}",
                configuredClusters);
        return deleteForcefully();
    }

    List<CompletableFuture<Void>> futures = Lists.newArrayList();

    // Check for missing replicators
    for (String cluster : configuredClusters) {
        if (cluster.equals(localCluster)) {
            continue;
        }

        if (!replicators.containsKey(cluster)) {
            futures.add(startReplicator(cluster));
        }
    }

    // Check for replicators to be stopped
    replicators.forEach((cluster, replicator) -> {
        // Update message TTL
        ((PersistentReplicator) replicator).updateMessageTTL(newMessageTTLinSeconds);

        if (!cluster.equals(localCluster)) {
            if (!configuredClusters.contains(cluster)) {
                futures.add(removeReplicator(cluster));
            }
        }

    });

    return FutureUtil.waitForAll(futures);
}

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

@Override
public CompletableFuture<SchemaVersion> addSchema(SchemaData schema) {
    if (schema == null) {
        return CompletableFuture.completedFuture(SchemaVersion.Empty);
    }/*from w w w  .j  a v  a2 s.c  o  m*/

    String base = TopicName.get(getName()).getPartitionedTopicName();
    String id = TopicName.get(base).getSchemaName();
    return brokerService.pulsar().getSchemaRegistryService().putSchemaIfAbsent(id, schema,
            schemaCompatibilityStrategy);
}

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

public static CompletableFuture<ClusterData> checkLocalOrGetPeerReplicationCluster(PulsarService pulsarService,
        NamespaceName namespace) {//w  ww  .j  ava  2 s . co 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.pulsar.client.impl.ConsumerImpl.java

@Override
protected CompletableFuture<Void> doAcknowledge(MessageId messageId, AckType ackType,
        Map<String, Long> properties) {
    checkArgument(messageId instanceof MessageIdImpl);
    if (getState() != State.Ready && getState() != State.Connecting) {
        stats.incrementNumAcksFailed();/*  w ww .  ja va  2  s.c om*/
        PulsarClientException exception = new PulsarClientException("Consumer not ready. State: " + getState());
        if (AckType.Individual.equals(ackType)) {
            onAcknowledge(messageId, exception);
        } else if (AckType.Cumulative.equals(ackType)) {
            onAcknowledgeCumulative(messageId, exception);
        }
        return FutureUtil.failedFuture(exception);
    }

    if (messageId instanceof BatchMessageIdImpl) {
        if (markAckForBatchMessage((BatchMessageIdImpl) messageId, ackType, properties)) {
            // all messages in batch have been acked so broker can be acked via sendAcknowledge()
            if (log.isDebugEnabled()) {
                log.debug("[{}] [{}] acknowledging message - {}, acktype {}", subscription, consumerName,
                        messageId, ackType);
            }
        } else {
            // other messages in batch are still pending ack.
            return CompletableFuture.completedFuture(null);
        }
    }
    return sendAcknowledge(messageId, ackType, properties);
}

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

private CompletableFuture<Void> sendAcknowledge(MessageId messageId, AckType ackType,
        Map<String, Long> properties) {
    MessageIdImpl msgId = (MessageIdImpl) messageId;

    if (ackType == AckType.Individual) {
        if (messageId instanceof BatchMessageIdImpl) {
            BatchMessageIdImpl batchMessageId = (BatchMessageIdImpl) messageId;

            stats.incrementNumAcksSent(batchMessageId.getBatchSize());
            unAckedMessageTracker.remove(new MessageIdImpl(batchMessageId.getLedgerId(),
                    batchMessageId.getEntryId(), batchMessageId.getPartitionIndex()));
            if (possibleSendToDeadLetterTopicMessages != null) {
                possibleSendToDeadLetterTopicMessages.remove(new MessageIdImpl(batchMessageId.getLedgerId(),
                        batchMessageId.getEntryId(), batchMessageId.getPartitionIndex()));
            }//w w w  .j a va2  s. c om
        } else {
            // increment counter by 1 for non-batch msg
            unAckedMessageTracker.remove(msgId);
            if (possibleSendToDeadLetterTopicMessages != null) {
                possibleSendToDeadLetterTopicMessages.remove(msgId);
            }
            stats.incrementNumAcksSent(1);
        }
        onAcknowledge(messageId, null);
    } else if (ackType == AckType.Cumulative) {
        onAcknowledgeCumulative(messageId, null);
        stats.incrementNumAcksSent(unAckedMessageTracker.removeMessagesTill(msgId));
    }

    acknowledgmentsGroupingTracker.addAcknowledgment(msgId, ackType, properties);

    // Consumer acknowledgment operation immediately succeeds. In any case, if we're not able to send ack to broker,
    // the messages will be re-delivered
    return CompletableFuture.completedFuture(null);
}

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

@Override
public CompletableFuture<Void> closeAsync() {
    if (getState() == State.Closing || getState() == State.Closed) {
        unAckedMessageTracker.close();//from   w w  w  .  j  a  v  a  2 s .co  m
        if (possibleSendToDeadLetterTopicMessages != null) {
            possibleSendToDeadLetterTopicMessages.clear();
        }
        return CompletableFuture.completedFuture(null);
    }

    if (!isConnected()) {
        log.info("[{}] [{}] Closed Consumer (not connected)", topic, subscription);
        setState(State.Closed);
        unAckedMessageTracker.close();
        if (possibleSendToDeadLetterTopicMessages != null) {
            possibleSendToDeadLetterTopicMessages.clear();
        }
        client.cleanupConsumer(this);
        return CompletableFuture.completedFuture(null);
    }

    stats.getStatTimeout().ifPresent(Timeout::cancel);

    setState(State.Closing);

    acknowledgmentsGroupingTracker.close();

    long requestId = client.newRequestId();

    CompletableFuture<Void> closeFuture = new CompletableFuture<>();
    ClientCnx cnx = cnx();
    if (null == cnx) {
        cleanupAtClose(closeFuture);
    } else {
        ByteBuf cmd = Commands.newCloseConsumer(consumerId, requestId);
        cnx.sendRequestWithId(cmd, requestId).handle((v, exception) -> {
            cnx.removeConsumer(consumerId);
            if (exception == null || !cnx.ctx().channel().isActive()) {
                cleanupAtClose(closeFuture);
            } else {
                closeFuture.completeExceptionally(exception);
            }
            return null;
        });
    }

    return closeFuture;
}

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

/**
 * Calls http-lookup api to find broker-service address which can serve a given topic.
 *
 * @param topicName topic-name/*  w w  w  .j  a  v  a 2  s  .  c  o  m*/
 * @return broker-socket-address that serves given topic
 */
@SuppressWarnings("deprecation")
public CompletableFuture<Pair<InetSocketAddress, InetSocketAddress>> getBroker(TopicName topicName) {
    String basePath = topicName.isV2() ? BasePathV2 : BasePathV1;

    return httpClient.get(basePath + topicName.getLookupName(), LookupData.class).thenCompose(lookupData -> {
        // Convert LookupData into as SocketAddress, handling exceptions
        URI uri = null;
        try {
            if (useTls) {
                uri = new URI(lookupData.getBrokerUrlTls());
            } else {
                String serviceUrl = lookupData.getBrokerUrl();
                if (serviceUrl == null) {
                    serviceUrl = lookupData.getNativeUrl();
                }
                uri = new URI(serviceUrl);
            }

            InetSocketAddress brokerAddress = InetSocketAddress.createUnresolved(uri.getHost(), uri.getPort());
            return CompletableFuture.completedFuture(Pair.of(brokerAddress, brokerAddress));
        } catch (Exception e) {
            // Failed to parse url
            log.warn("[{}] Lookup Failed due to invalid url {}, {}", topicName, uri, e.getMessage());
            return FutureUtil.failedFuture(e);
        }
    });
}