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:com.devicehive.service.DeviceCommandService.java

public CompletableFuture<Pair<String, DeviceCommand>> sendSubscribeToUpdateRequest(final long commandId,
        final String guid, BiConsumer<DeviceCommand, String> callback) {
    CompletableFuture<Pair<String, DeviceCommand>> future = new CompletableFuture<>();
    final String subscriptionId = UUID.randomUUID().toString();
    Consumer<Response> responseConsumer = response -> {
        String resAction = response.getBody().getAction();
        if (resAction.equals(Action.COMMAND_UPDATE_SUBSCRIBE_RESPONSE.name())) {
            future.complete(
                    Pair.of(response.getBody().cast(CommandUpdateSubscribeResponse.class).getSubscriptionId(),
                            response.getBody().cast(CommandUpdateSubscribeResponse.class).getDeviceCommand()));
        } else if (resAction.equals(Action.COMMAND_UPDATE_EVENT.name())) {
            callback.accept(response.getBody().cast(CommandUpdateEvent.class).getDeviceCommand(),
                    subscriptionId);/*from   w  ww  . j av  a 2 s .c  om*/
        } else {
            logger.warn("Unknown action received from backend {}", resAction);
        }
    };
    rpcClient.call(Request.newBuilder()
            .withBody(new CommandUpdateSubscribeRequest(commandId, guid, subscriptionId)).build(),
            responseConsumer);
    return future;
}

From source file:com.ikanow.aleph2.storm.harvest_technology.StormHarvestTechnologyModule.java

@Override
public CompletableFuture<BasicMessageBean> onDelete(DataBucketBean to_delete, IHarvestContext context) {
    //TODO not sure what delete is suppose to do, stop this topology? I assume no
    //data is being stored in the harvest tech so nothing to delete? (see purge)
    CompletableFuture<BasicMessageBean> future = new CompletableFuture<BasicMessageBean>();
    try {//from   w w  w. java2  s.  c om
        StormControllerUtil.stopJob(storm_controller, getJobName(to_delete));
    } catch (Exception e) {
        logger.info("Stop completing exceptionally", e);
        future.complete(new BasicMessageBean(new Date(), false, null, "onDelete", null,
                ErrorUtils.getLongForm("{0}", e), null));
        return future;
    }
    logger.info("returning completed stop");
    future.complete(new BasicMessageBean(new Date(), true, null, "onDelete", null, null, null));
    return future;
}

From source file:com.devicehive.service.DeviceNotificationService.java

public Pair<String, CompletableFuture<List<DeviceNotification>>> subscribe(final Set<String> devices,
        final Set<String> names, final Date timestamp, final BiConsumer<DeviceNotification, String> callback) {

    final String subscriptionId = UUID.randomUUID().toString();
    Set<NotificationSubscribeRequest> subscribeRequests = devices.stream()
            .map(device -> new NotificationSubscribeRequest(subscriptionId, device, names, timestamp))
            .collect(Collectors.toSet());
    Collection<CompletableFuture<Collection<DeviceNotification>>> futures = new ArrayList<>();
    for (NotificationSubscribeRequest sr : subscribeRequests) {
        CompletableFuture<Collection<DeviceNotification>> future = new CompletableFuture<>();
        Consumer<Response> responseConsumer = response -> {
            String resAction = response.getBody().getAction();
            if (resAction.equals(Action.NOTIFICATION_SUBSCRIBE_RESPONSE.name())) {
                NotificationSubscribeResponse r = response.getBody().cast(NotificationSubscribeResponse.class);
                future.complete(r.getNotifications());
            } else if (resAction.equals(Action.NOTIFICATION_EVENT.name())) {
                NotificationEvent event = response.getBody().cast(NotificationEvent.class);
                callback.accept(event.getNotification(), subscriptionId);
            } else {
                logger.warn("Unknown action received from backend {}", resAction);
            }//from  w w w  .  j a v  a  2  s.c  o m
        };
        futures.add(future);
        Request request = Request.newBuilder().withBody(sr).withPartitionKey(sr.getDevice())
                .withSingleReply(false).build();
        rpcClient.call(request, responseConsumer);
    }

    CompletableFuture<List<DeviceNotification>> future = CompletableFuture
            .allOf(futures.toArray(new CompletableFuture[futures.size()])).thenApply(v -> futures.stream()
                    .map(CompletableFuture::join).flatMap(Collection::stream).collect(Collectors.toList()));
    return Pair.of(subscriptionId, future);
}

From source file:org.apache.pulsar.compaction.TwoPhaseCompactor.java

private CompletableFuture<Void> addToCompactedLedger(LedgerHandle lh, RawMessage m) {
    CompletableFuture<Void> bkf = new CompletableFuture<>();
    ByteBuf serialized = m.serialize();/*from   w ww. j a va 2 s .co  m*/
    lh.asyncAddEntry(serialized, (rc, ledger, eid, ctx) -> {
        if (rc != BKException.Code.OK) {
            bkf.completeExceptionally(BKException.create(rc));
        } else {
            bkf.complete(null);
        }
    }, null);
    return bkf;
}

From source file:com.ikanow.aleph2.storm.harvest_technology.StormHarvestTechnologyModule.java

@Override
public CompletableFuture<BasicMessageBean> onPeriodicPoll(DataBucketBean polled_bucket,
        IHarvestContext context) {//from   w  ww.  j a  va  2s. co m
    CompletableFuture<BasicMessageBean> future = new CompletableFuture<BasicMessageBean>();
    TopologyInfo top_info;
    try {
        top_info = StormControllerUtil.getJobStats(storm_controller, getJobName(polled_bucket));
    } catch (Exception ex) {
        //set failure in completable future
        future.complete(new BasicMessageBean(new Date(), false, null, "onPeriodicPoll", null,
                ErrorUtils.getLongForm("{0}", ex), null));
        return future;
    }
    //TODO see if there is any info on this buckets harvest stats, can we
    //see how many documents have been sent via the spout or something?
    future.complete(
            new BasicMessageBean(new Date(), true, null, "onPeriodicPoll", null, top_info.toString(), null));
    return future;
}

From source file:org.apache.bookkeeper.meta.MockLedgerManager.java

@Override
public CompletableFuture<Versioned<LedgerMetadata>> readLedgerMetadata(long ledgerId) {
    CompletableFuture<Versioned<LedgerMetadata>> promise = new CompletableFuture<>();
    executor.submit(() -> {//  w w  w  . java  2s  .  co m
        try {
            Versioned<LedgerMetadata> metadata = readMetadata(ledgerId);
            if (metadata == null) {
                executeCallback(
                        () -> promise.completeExceptionally(new BKException.BKNoSuchLedgerExistsException()));
            } else {
                executeCallback(() -> promise.complete(metadata));
            }
        } catch (Exception e) {
            LOG.error("Error reading metadata", e);
            executeCallback(() -> promise.completeExceptionally(new BKException.MetaStoreException()));
        }
    });
    return promise;
}

From source file:org.apache.tinkerpop.gremlin.driver.simple.AbstractClient.java

@Override
public CompletableFuture<List<ResponseMessage>> submitAsync(final RequestMessage requestMessage)
        throws Exception {
    final List<ResponseMessage> results = new ArrayList<>();
    final CompletableFuture<List<ResponseMessage>> f = new CompletableFuture<>();
    callbackResponseHandler.callback = response -> {
        if (f.isDone())
            throw new RuntimeException(
                    "A terminating message was already encountered - no more messages should have been received");

        results.add(response);/*from w w  w.  j  a v a2s.c  o m*/

        // check if the current message is terminating - if it is then we can mark complete
        if (!response.getStatus().getCode().equals(ResponseStatusCode.PARTIAL_CONTENT)) {
            f.complete(results);
        }
    };

    writeAndFlush(requestMessage);

    return f;
}

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

private static <RESP> CompletableFuture<RESP> mutateRow(HBaseRpcController controller, HRegionLocation loc,
        ClientService.Interface stub, RowMutations mutation,
        Converter<MultiRequest, byte[], RowMutations> reqConvert, Function<Result, RESP> respConverter) {
    CompletableFuture<RESP> future = new CompletableFuture<>();
    try {//from ww w .ja va 2s .c o m
        byte[] regionName = loc.getRegionInfo().getRegionName();
        MultiRequest req = reqConvert.convert(regionName, mutation);
        stub.multi(controller, req, new RpcCallback<MultiResponse>() {

            @Override
            public void run(MultiResponse resp) {
                if (controller.failed()) {
                    future.completeExceptionally(controller.getFailed());
                } else {
                    try {
                        org.apache.hadoop.hbase.client.MultiResponse multiResp = ResponseConverter
                                .getResults(req, resp, controller.cellScanner());
                        Throwable ex = multiResp.getException(regionName);
                        if (ex != null) {
                            future.completeExceptionally(ex instanceof IOException ? ex
                                    : new IOException(
                                            "Failed to mutate row: " + Bytes.toStringBinary(mutation.getRow()),
                                            ex));
                        } else {
                            future.complete(respConverter
                                    .apply((Result) multiResp.getResults().get(regionName).result.get(0)));
                        }
                    } catch (IOException e) {
                        future.completeExceptionally(e);
                    }
                }
            }
        });
    } catch (IOException e) {
        future.completeExceptionally(e);
    }
    return future;
}

From source file:com.canoo.dolphin.client.impl.ClientContextImpl.java

@Override
public synchronized CompletableFuture<Void> disconnect() {
    checkForInitializedState();// w  w w.ja va2s.  co  m
    state = State.DESTROYING;
    clientDolphin.stopPushListening();
    final CompletableFuture<Void> result = new CompletableFuture<>();

    Executors.newSingleThreadExecutor().execute(() -> {
        state = State.DESTROYED;
        dolphinCommandHandler.invokeDolphinCommand(PlatformConstants.DESTROY_CONTEXT_COMMAND_NAME)
                .handle((v, t) -> {
                    if (t != null) {
                        result.completeExceptionally(new DolphinRemotingException("Can't disconnect", t));
                    } else {
                        result.complete(null);
                    }
                    return null;
                });
        //TODO: Stop communication in client connector
    });

    return result;
}

From source file:org.apache.hadoop.hbase.client.example.AsyncClientExample.java

private CompletableFuture<AsyncConnection> getConn() {
    CompletableFuture<AsyncConnection> f = future.get();
    if (f != null) {
        return f;
    }/*  ww w  .  j a v a 2 s. c  o  m*/
    for (;;) {
        if (future.compareAndSet(null, new CompletableFuture<>())) {
            CompletableFuture<AsyncConnection> toComplete = future.get();
            addListener(ConnectionFactory.createAsyncConnection(getConf()), (conn, error) -> {
                if (error != null) {
                    toComplete.completeExceptionally(error);
                    // we need to reset the future holder so we will get a chance to recreate an async
                    // connection at next try.
                    future.set(null);
                    return;
                }
                toComplete.complete(conn);
            });
            return toComplete;
        } else {
            f = future.get();
            if (f != null) {
                return f;
            }
        }
    }
}