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:io.pravega.controller.server.ControllerService.java

/**
 * Controller Service API to create scope.
 *
 * @param scope Name of scope to be created.
 * @return Status of create scope.// www  . j a  v a  2  s.com
 */
public CompletableFuture<CreateScopeStatus> createScope(final String scope) {
    Exceptions.checkNotNullOrEmpty(scope, "scope");
    try {
        NameUtils.validateScopeName(scope);
    } catch (IllegalArgumentException | NullPointerException e) {
        log.warn("Create scope failed due to invalid scope name {}", scope);
        return CompletableFuture.completedFuture(
                CreateScopeStatus.newBuilder().setStatus(CreateScopeStatus.Status.INVALID_SCOPE_NAME).build());
    }
    return streamStore.createScope(scope);
}

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

@Override
public CompletableFuture<Optional<O>> getObjectBySpec(final QueryComponent<O> unique_spec,
        final List<String> field_list, final boolean include) {
    try {//from   ww w  .  j a  v a2 s  . com
        if (field_list.isEmpty()) {
            return CompletableFuture.completedFuture(Optional
                    .ofNullable(_state.coll.findOne(MongoDbUtils.convertToMongoQuery(unique_spec)._1())));
        } else {
            final BasicDBObject fields = getFields(field_list, include);
            return CompletableFuture.completedFuture(Optional.ofNullable(
                    _state.coll.findOne(MongoDbUtils.convertToMongoQuery(unique_spec)._1(), fields)));
        }
    } catch (Exception e) {
        return FutureUtils.<Optional<O>>returnError(e);
    }
}

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

@Override
public CompletableFuture<Map<Segment, Long>> getSegmentsAtTime(Stream stream, long timestamp) {
    return CompletableFuture
            .completedFuture(getSegmentsForStream(stream).stream().collect(Collectors.toMap(s -> s, s -> 0L)));
}

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

@Override
public CompletableFuture<StreamSegmentsWithPredecessors> getSuccessors(Segment segment) {
    return CompletableFuture.completedFuture(new StreamSegmentsWithPredecessors(Collections.emptyMap()));
}

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

@Override
public CompletableFuture<BasicMessageBean> onPeriodicPoll(DataBucketBean polled_bucket,
        IHarvestContext context) {/*  ww w . ja va2  s.  c o m*/

    // (If we're here then we're not suspended by definition)

    // Check if it's running
    final Optional<String> maybe_pid = Optional.ofNullable(FlumeLaunchUtils.getPid(polled_bucket));
    final boolean is_running = maybe_pid.map(Lambdas.wrap_u(pid -> FlumeLaunchUtils.isRunning(pid)))
            .orElse(false);
    if (!is_running) { // restart it if not
        return onNewSource(polled_bucket, context, true);
    } else {
        return CompletableFuture.completedFuture(new BasicMessageBean(new Date(), true, "onPeriodicPoll",
                "onPeriodicPoll", null, "No action taken", null));
    }
}

From source file:com.ikanow.aleph2.management_db.services.DataBucketStatusCrudService.java

@Override
public ManagementFuture<Boolean> updateObjectBySpec(final QueryComponent<DataBucketStatusBean> unique_spec,
        final Optional<Boolean> upsert, final UpdateComponent<DataBucketStatusBean> update) {
    final MethodNamingHelper<DataBucketStatusBean> helper = BeanTemplateUtils.from(DataBucketStatusBean.class);

    if (upsert.orElse(false)) {
        throw new RuntimeException("This method is not supported with upsert set and true");
    }//from ww  w  . j  a  va  2 s. c  om

    final Collection<BasicMessageBean> errors = validateUpdateCommand(update);
    if (!errors.isEmpty()) {
        return FutureUtils.createManagementFuture(CompletableFuture.completedFuture(false),
                CompletableFuture.completedFuture(errors));
    }

    // Now perform the update and based on the results we may need to send out instructions
    // to any listening buckets

    final CompletableFuture<Optional<DataBucketStatusBean>> update_reply = _underlying_data_bucket_status_db
            .get().updateAndReturnObjectBySpec(unique_spec, Optional.of(false), update, Optional.of(false),
                    Arrays.asList(helper.field(DataBucketStatusBean::_id),
                            helper.field(DataBucketStatusBean::confirmed_suspended),
                            helper.field(DataBucketStatusBean::confirmed_multi_node_enabled),
                            helper.field(DataBucketStatusBean::confirmed_master_enrichment_type),
                            helper.field(DataBucketStatusBean::suspended),
                            helper.field(DataBucketStatusBean::quarantined_until),
                            helper.field(DataBucketStatusBean::node_affinity)),
                    true);

    try {
        // What happens now depends on the contents of the message         

        // Maybe the user wanted to suspend/resume the bucket:

        final CompletableFuture<Collection<BasicMessageBean>> suspend_future = Lambdas
                .<CompletableFuture<Collection<BasicMessageBean>>>get(() -> {
                    if (update.getAll().containsKey(helper.field(DataBucketStatusBean::suspended))) {

                        // (note this handles suspending the bucket if no handlers are available)
                        return getOperationFuture(update_reply, sb -> sb.suspended(),
                                _underlying_data_bucket_db.get(), _underlying_data_bucket_status_db.get(),
                                _actor_context, _bucket_action_retry_store.get());
                    } else { // (this isn't an error, just nothing to do here)
                        return CompletableFuture.completedFuture(Collections.<BasicMessageBean>emptyList());
                    }
                });

        // Maybe the user wanted to set quarantine on/off:

        final CompletableFuture<Collection<BasicMessageBean>> quarantine_future = Lambdas
                .<CompletableFuture<Collection<BasicMessageBean>>>get(() -> {
                    if (update.getAll().containsKey(helper.field(DataBucketStatusBean::quarantined_until))) {

                        // (note this handles suspending the bucket if no handlers are available)
                        return getOperationFuture(update_reply, sb -> { // (this predicate is slightly more complex)
                            return (null != sb.quarantined_until())
                                    || (new Date().getTime() < sb.quarantined_until().getTime());
                        }, _underlying_data_bucket_db.get(), _underlying_data_bucket_status_db.get(),
                                _actor_context, _bucket_action_retry_store.get());
                    } else { // (this isn't an error, just nothing to do here)
                        return CompletableFuture.completedFuture(Collections.<BasicMessageBean>emptyList());
                    }
                });

        return FutureUtils.createManagementFuture(update_reply.thenApply(o -> o.isPresent()), // whether we updated
                suspend_future.thenCombine(quarantine_future,
                        (f1, f2) -> Stream.concat(f1.stream(), f2.stream()).collect(Collectors.toList())));
        //(+combine error messages from suspend/quarantine operations)
    } catch (Exception e) {
        // This is a serious enough exception that we'll just leave here
        return FutureUtils.createManagementFuture(FutureUtils.returnError(e));
    }
}

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

private CompletableFuture<Boolean> startTruncation(String scope, String stream, Map<Integer, Long> streamCut,
        OperationContext contextOpt) {/*from   w w w  . j  a  v  a2s  . c o  m*/
    final OperationContext context = contextOpt == null ? streamMetadataStore.createContext(scope, stream)
            : contextOpt;

    return streamMetadataStore.getTruncationProperty(scope, stream, true, context, executor)
            .thenCompose(property -> {
                if (!property.isUpdating()) {
                    // 2. post event with new stream cut if no truncation is ongoing
                    return writeEvent(new TruncateStreamEvent(scope, stream))
                            // 3. start truncation by updating the metadata
                            .thenCompose(x -> streamMetadataStore.startTruncation(scope, stream, streamCut,
                                    context, executor))
                            .thenApply(x -> true);
                } else {
                    log.warn("Another truncation in progress for {}/{}", scope, stream);
                    return CompletableFuture.completedFuture(false);
                }
            });
}

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

@Override
CompletableFuture<Void> removeActiveTxEntry(final int epoch, final UUID txId) {
    final String activePath = getActiveTxPath(epoch, txId.toString());
    // TODO: no need to check existence, just delete the path, if the path is already deleted, will get error
    return store.checkExists(activePath).thenCompose(x -> {
        if (x) {//  w  w w  . jav a 2  s  .co m
            return store.deletePath(activePath, false)
                    .whenComplete((r, e) -> cache.invalidateCache(activePath));
        } else {
            return CompletableFuture.completedFuture(null);
        }
    });
}

From source file:com.ikanow.aleph2.management_db.services.SharedLibraryCrudService.java

@Override
public ManagementFuture<Boolean> deleteObjectBySpec(QueryComponent<SharedLibraryBean> unique_spec) {
    return FutureUtils.createManagementFuture(
            _underlying_library_db.get().getObjectBySpec(unique_spec).thenCompose(lib -> {
                if (lib.isPresent()) {
                    try {
                        final FileContext fs = _storage_service.get()
                                .getUnderlyingPlatformDriver(FileContext.class, Optional.empty()).get();
                        fs.delete(fs.makeQualified(new Path(lib.get().path_name())), false);
                    } catch (Exception e) { // i suppose we don't really care if it fails..
                        // (maybe add a message?)
                        //DEBUG
                        //e.printStackTrace();
                    }// w w w  .  jav a 2s  . c  o  m
                    return _underlying_library_db.get().deleteObjectBySpec(unique_spec);
                } else {
                    return CompletableFuture.completedFuture(false);
                }
            }));
}

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

@Override
public CompletableFuture<PravegaNodeUri> getEndpointForSegment(String qualifiedSegmentName) {
    return CompletableFuture.completedFuture(new PravegaNodeUri(endpoint, port));
}