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:com.yahoo.pulsar.broker.service.ServerCnx.java

@Override
protected void handleSubscribe(final CommandSubscribe subscribe) {
    checkArgument(state == State.Connected);
    CompletableFuture<Boolean> authorizationFuture;
    if (service.isAuthorizationEnabled()) {
        authorizationFuture = service.getAuthorizationManager()
                .canConsumeAsync(DestinationName.get(subscribe.getTopic()), authRole);
    } else {//from  w w  w .  ja va  2s  .  co m
        authorizationFuture = CompletableFuture.completedFuture(true);
    }
    final String topicName = subscribe.getTopic();
    final String subscriptionName = subscribe.getSubscription();
    final long requestId = subscribe.getRequestId();
    final long consumerId = subscribe.getConsumerId();
    final SubType subType = subscribe.getSubType();
    final String consumerName = subscribe.getConsumerName();
    final boolean isDurable = subscribe.getDurable();
    final MessageIdImpl startMessageId = subscribe.hasStartMessageId()
            ? new MessageIdImpl(subscribe.getStartMessageId().getLedgerId(),
                    subscribe.getStartMessageId().getEntryId(), subscribe.getStartMessageId().getPartition())
            : null;

    final int priorityLevel = subscribe.hasPriorityLevel() ? subscribe.getPriorityLevel() : 0;

    authorizationFuture.thenApply(isAuthorized -> {
        if (isAuthorized) {
            if (log.isDebugEnabled()) {
                log.debug("[{}] Client is authorized to subscribe with role {}", remoteAddress, authRole);
            }

            log.info("[{}] Subscribing on topic {} / {}", remoteAddress, topicName, subscriptionName);

            CompletableFuture<Consumer> consumerFuture = new CompletableFuture<>();
            CompletableFuture<Consumer> existingConsumerFuture = consumers.putIfAbsent(consumerId,
                    consumerFuture);

            if (existingConsumerFuture != null) {
                if (existingConsumerFuture.isDone() && !existingConsumerFuture.isCompletedExceptionally()) {
                    Consumer consumer = existingConsumerFuture.getNow(null);
                    log.info("[{}] Consumer with the same id is already created: {}", remoteAddress, consumer);
                    ctx.writeAndFlush(Commands.newSuccess(requestId));
                    return null;
                } else {
                    // There was an early request to create a consumer with same consumerId. This can happen when
                    // client timeout is lower the broker timeouts. We need to wait until the previous consumer
                    // creation request either complete or fails.
                    log.warn("[{}][{}][{}] Consumer is already present on the connection", remoteAddress,
                            topicName, subscriptionName);
                    ServerError error = !existingConsumerFuture.isDone() ? ServerError.ServiceNotReady
                            : getErrorCode(existingConsumerFuture);
                    ctx.writeAndFlush(Commands.newError(requestId, error,
                            "Consumer is already present on the connection"));
                    return null;
                }
            }

            service.getTopic(topicName).thenCompose(topic -> topic.subscribe(ServerCnx.this, subscriptionName,
                    consumerId, subType, priorityLevel, consumerName, isDurable, startMessageId))
                    .thenAccept(consumer -> {
                        if (consumerFuture.complete(consumer)) {
                            log.info("[{}] Created subscription on topic {} / {}", remoteAddress, topicName,
                                    subscriptionName);
                            ctx.writeAndFlush(Commands.newSuccess(requestId), ctx.voidPromise());
                        } else {
                            // The consumer future was completed before by a close command
                            try {
                                consumer.close();
                                log.info("[{}] Cleared consumer created after timeout on client side {}",
                                        remoteAddress, consumer);
                            } catch (BrokerServiceException e) {
                                log.warn(
                                        "[{}] Error closing consumer created after timeout on client side {}: {}",
                                        remoteAddress, consumer, e.getMessage());
                            }
                            consumers.remove(consumerId, consumerFuture);
                        }

                    }) //
                    .exceptionally(exception -> {
                        log.warn("[{}][{}][{}] Failed to create consumer: {}", remoteAddress, topicName,
                                subscriptionName, exception.getCause().getMessage(), exception);

                        // If client timed out, the future would have been completed by subsequent close. Send error
                        // back to client, only if not completed already.
                        if (consumerFuture.completeExceptionally(exception)) {
                            ctx.writeAndFlush(Commands.newError(requestId,
                                    BrokerServiceException.getClientErrorCode(exception.getCause()),
                                    exception.getCause().getMessage()));
                        }
                        consumers.remove(consumerId, consumerFuture);

                        return null;

                    });
        } else {
            String msg = "Client is not authorized to subscribe";
            log.warn("[{}] {} with role {}", remoteAddress, msg, authRole);
            ctx.writeAndFlush(Commands.newError(requestId, ServerError.AuthorizationError, msg));
        }
        return null;
    });
}

From source file:com.ikanow.aleph2.example.flume_harvester.services.FlumeHarvestTechnology.java

@Override
public CompletableFuture<BasicMessageBean> onHarvestComplete(DataBucketBean completed_bucket,
        IHarvestContext context) {//from   w w  w  .  j ava 2 s.  c om
    return CompletableFuture.completedFuture(new BasicMessageBean(new Date(), true, "onHarvestComplete",
            "onHarvestComplete", null, "No action taken", null));
}

From source file:io.pravega.controller.task.Stream.StreamTransactionMetadataTasks.java

@SuppressWarnings("ReturnCount")
private CompletableFuture<Void> validate(long lease, long maxExecutionPeriod, long scaleGracePeriod) {
    if (lease <= 0) {
        return FutureHelpers.failedFuture(new IllegalArgumentException("lease should be a positive number"));
    }//  w  w w.  j av a2  s .c o  m
    if (maxExecutionPeriod <= 0) {
        return FutureHelpers
                .failedFuture(new IllegalArgumentException("maxExecutionPeriod should be a positive number"));
    }
    if (scaleGracePeriod <= 0) {
        return FutureHelpers
                .failedFuture(new IllegalArgumentException("scaleGracePeriod should be a positive number"));
    }
    // If scaleGracePeriod is larger than maxScaleGracePeriod return error
    if (scaleGracePeriod > timeoutService.getMaxScaleGracePeriod()) {
        return FutureHelpers.failedFuture(new IllegalArgumentException(
                "scaleGracePeriod too large, max value is " + timeoutService.getMaxScaleGracePeriod()));
    }
    // If lease value is too large return error
    if (lease > scaleGracePeriod || lease > maxExecutionPeriod || lease > timeoutService.getMaxLeaseValue()) {
        return FutureHelpers.failedFuture(new IllegalArgumentException("lease value too large, max value is "
                + Math.min(scaleGracePeriod, Math.min(maxExecutionPeriod, timeoutService.getMaxLeaseValue()))));
    }
    return CompletableFuture.completedFuture(null);
}

From source file:com.ikanow.aleph2.shared.crud.mongodb.services.MongoDbCrudService.java

@SuppressWarnings("unchecked")
@Override/*w w w.j a v a2s. c o m*/
public CompletableFuture<Optional<O>> getObjectById(final Object id, final List<String> field_list,
        final boolean include) {
    try {
        if (field_list.isEmpty()) {
            return CompletableFuture.completedFuture(Optional.ofNullable(_state.coll.findOneById((K) id)));
        } else {
            final BasicDBObject fields = getFields(field_list, include);
            return CompletableFuture
                    .completedFuture(Optional.ofNullable(_state.coll.findOneById((K) id, fields)));
        }
    } catch (Exception e) {
        return FutureUtils.<Optional<O>>returnError(e);
    }
}

From source file:io.pravega.client.stream.mock.MockController.java

@Override
public CompletableFuture<Boolean> isSegmentOpen(Segment segment) {
    return CompletableFuture.completedFuture(true);
}

From source file:io.pravega.controller.store.stream.InMemoryStream.java

@Override
CompletableFuture<Data<Integer>> getActiveTx(int epoch, UUID txId) {
    synchronized (txnsLock) {
        if (!activeTxns.containsKey(txId.toString())) {
            return FutureHelpers.failedFuture(StoreException.create(StoreException.Type.DATA_NOT_FOUND,
                    "Stream: " + getName() + " Transaction: " + txId.toString()));
        }/*from  w  ww. java2 s .com*/

        return CompletableFuture.completedFuture(copy(activeTxns.get(txId.toString())));
    }
}

From source file:io.flutter.inspector.DiagnosticsNode.java

/**
 * Returns a list of raw Dart property values of the Dart value of this
 * property that are useful for custom display of the property value.
 * For example, get the red, green, and blue components of color.
 * <p>/*from  ww  w  .  j a v a 2  s  .  c om*/
 * Unfortunately we cannot just use the list of fields from the Observatory
 * Instance object for the Dart value because much of the relevant
 * information to display good visualizations of Flutter values is stored
 * in properties not in fields.
 */
public CompletableFuture<Map<String, InstanceRef>> getValueProperties() {
    final InspectorInstanceRef valueRef = getValueRef();
    if (valueProperties == null) {
        if (getPropertyType() == null || valueRef == null || valueRef.getId() == null) {
            valueProperties = CompletableFuture.completedFuture(null);
            return valueProperties;
        }
        if (isEnumProperty()) {
            // Populate all the enum property values.
            valueProperties = inspectorService.getEnumPropertyValues(getValueRef());
            return valueProperties;
        }

        final String[] propertyNames;
        // Add more cases here as visual displays for additional Dart objects
        // are added.
        switch (getPropertyType()) {
        case "Color":
            propertyNames = new String[] { "red", "green", "blue", "alpha" };
            break;
        case "IconData":
            propertyNames = new String[] { "codePoint" };
            break;
        default:
            valueProperties = CompletableFuture.completedFuture(null);
            return valueProperties;
        }
        valueProperties = inspectorService.getDartObjectProperties(getValueRef(), propertyNames);
    }
    return valueProperties;
}

From source file:com.ikanow.aleph2.management_db.mongodb.services.IkanowV1SyncService_TestBuckets.java

/**
 * Checks if the number of objects in v2_output_db is at least
 * as many as we are looking for in test_spec.requested_num_objects
 * /*from   ww  w.  ja va  2s .c o m*/
 * if so: retire job
 * else: return back CF that we haven't reached our limit yet
 * 
 * @param v2_output_db
 * @param data_bucket
 * @param test_spec
 * @param old_test_source
 * @param source_test_db
 * @return
 */
private CompletableFuture<Boolean> checkTestHitRequestedNumResults(final ICrudService<JsonNode> v2_output_db,
        final DataBucketBean data_bucket, final ProcessingTestSpecBean test_spec,
        final TestQueueBean old_test_source, final ICrudService<TestQueueBean> source_test_db) {
    return v2_output_db.countObjects().thenCompose(num_results -> {
        _logger.debug("Found: " + num_results + "(" + test_spec.requested_num_objects() + ") for this test.");
        if (num_results >= test_spec.requested_num_objects()) {
            _logger.debug(
                    "Test job: " + data_bucket.full_name() + " reached requested num results, need to retire");
            return retireTestJob(data_bucket, old_test_source, source_test_db, v2_output_db);
        } else {
            _logger.debug("Test job: " + data_bucket.full_name()
                    + " haven't reached requested num results yet, let it continue");
            return CompletableFuture.completedFuture(true);
        }
    });
}

From source file:io.pravega.controller.task.Stream.StreamMetadataTasks.java

/**
 * Seal a stream.//from w  ww.  j  a va2 s. c o  m
 *
 * @param scope      scope.
 * @param stream     stream name.
 * @param contextOpt optional context
 * @return update status.
 */
public CompletableFuture<UpdateStreamStatus.Status> sealStream(String scope, String stream,
        OperationContext contextOpt) {
    final OperationContext context = contextOpt == null ? streamMetadataStore.createContext(scope, stream)
            : contextOpt;

    // 1. post event for seal.
    SealStreamEvent event = new SealStreamEvent(scope, stream);
    return writeEvent(event)
            // 2. set state to sealing
            .thenCompose(x -> streamMetadataStore.getState(scope, stream, false, context, executor))
            .thenCompose(state -> {
                if (state.equals(State.SEALED)) {
                    return CompletableFuture.completedFuture(true);
                } else {
                    return streamMetadataStore.setState(scope, stream, State.SEALING, context, executor);
                }
            })
            // 3. return with seal initiated.
            .thenCompose(result -> {
                if (result) {
                    return checkDone(() -> isSealed(scope, stream, context))
                            .thenApply(x -> UpdateStreamStatus.Status.SUCCESS);
                } else {
                    return CompletableFuture.completedFuture(UpdateStreamStatus.Status.FAILURE);
                }
            }).exceptionally(ex -> {
                log.warn("Exception thrown in trying to notify sealed segments {}", ex.getMessage());
                return handleUpdateStreamError(ex);
            });
}

From source file:io.pravega.controller.store.stream.AbstractStreamMetadataStore.java

@Override
public CompletableFuture<DeleteEpochResponse> tryDeleteEpochIfScaling(final String scope, final String name,
        final int epoch, final OperationContext context, final Executor executor) {
    Stream stream = getStream(scope, name, context);
    return withCompletion(stream.scaleTryDeleteEpoch(epoch), executor).thenCompose(deleted -> {
        if (deleted) {
            return stream.latestScaleData().thenCompose(pair -> {
                List<Integer> segmentsSealed = pair.getLeft();
                return FutureHelpers
                        .allOfWithResults(
                                pair.getRight().stream().map(stream::getSegment).collect(Collectors.toList()))
                        .thenApply(segmentsCreated -> new DeleteEpochResponse(true, segmentsSealed,
                                segmentsCreated));
            });/*from   www  . j a v  a 2 s  . c  om*/
        } else {
            return CompletableFuture.completedFuture(new DeleteEpochResponse(false, null, null));
        }
    });
}