Example usage for java.util.concurrent CompletableFuture CompletableFuture

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

Introduction

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

Prototype

public CompletableFuture() 

Source Link

Document

Creates a new incomplete CompletableFuture.

Usage

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

private boolean createSegment(String name, PravegaNodeUri uri) {
    CompletableFuture<Boolean> result = new CompletableFuture<>();
    FailingReplyProcessor replyProcessor = new FailingReplyProcessor() {

        @Override/* w w w  . j ava2s. c  o m*/
        public void connectionDropped() {
            result.completeExceptionally(new ConnectionClosedException());
        }

        @Override
        public void wrongHost(WireCommands.WrongHost wrongHost) {
            result.completeExceptionally(new NotImplementedException());
        }

        @Override
        public void segmentAlreadyExists(WireCommands.SegmentAlreadyExists segmentAlreadyExists) {
            result.complete(false);
        }

        @Override
        public void segmentCreated(WireCommands.SegmentCreated segmentCreated) {
            result.complete(true);
        }

        @Override
        public void processingFailure(Exception error) {
            result.completeExceptionally(error);
        }
    };
    CreateSegment command = new WireCommands.CreateSegment(idGenerator.get(), name,
            WireCommands.CreateSegment.NO_SCALE, 0);
    sendRequestOverNewConnection(command, replyProcessor, result);
    return getAndHandleExceptions(result, RuntimeException::new);
}

From source file:org.onosproject.incubator.store.meter.impl.DistributedMeterStore.java

@Override
public CompletableFuture<MeterStoreResult> storeMeter(Meter meter) {
    // Init steps
    CompletableFuture<MeterStoreResult> future = new CompletableFuture<>();
    MeterKey key = MeterKey.key(meter.deviceId(), meter.id());
    // Store the future related to the operation
    futures.put(key, future);//from   w  w w .  ja  v  a2 s.  c o m
    // Store the meter data
    MeterData data = new MeterData(meter, null, local);
    try {
        meters.put(key, data);
    } catch (StorageException e) {
        futures.remove(key);
        future.completeExceptionally(e);
    }
    // Done, return the future
    return future;
}

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

private CompletableFuture<Long> phaseTwoSeekThenLoop(RawReader reader, MessageId from, MessageId to,
        MessageId lastReadId, Map<String, MessageId> latestForKey, BookKeeper bk, LedgerHandle ledger) {
    CompletableFuture<Long> promise = new CompletableFuture<>();

    reader.seekAsync(from).thenCompose((v) -> {
        Semaphore outstanding = new Semaphore(MAX_OUTSTANDING);
        CompletableFuture<Void> loopPromise = new CompletableFuture<Void>();
        phaseTwoLoop(reader, to, latestForKey, ledger, outstanding, loopPromise);
        return loopPromise;
    }).thenCompose((v) -> closeLedger(ledger))
            .thenCompose((v) -> reader.acknowledgeCumulativeAsync(lastReadId,
                    ImmutableMap.of(COMPACTED_TOPIC_LEDGER_PROPERTY, ledger.getId())))
            .whenComplete((res, exception) -> {
                if (exception != null) {
                    deleteLedger(bk, ledger).whenComplete((res2, exception2) -> {
                        if (exception2 != null) {
                            log.warn("Cleanup of ledger {} for failed", ledger, exception2);
                        }//from w  ww  .jav  a 2 s .com
                        // complete with original exception
                        promise.completeExceptionally(exception);
                    });
                } else {
                    promise.complete(ledger.getId());
                }
            });
    return promise;
}

From source file:com.ikanow.aleph2.analytics.storm.services.RemoteStormController.java

/**
 * Attempts to stop the given job_name, if the job is not found it will throw an exception.
 * //from  w ww .  j  ava 2s. co  m
 */
@Override
public CompletableFuture<BasicMessageBean> stopJob(String job_name) {
    logger.info("Stopping job: " + job_name);
    CompletableFuture<BasicMessageBean> future = new CompletableFuture<BasicMessageBean>();

    try {
        String actual_job_name = getJobTopologySummaryFromJobPrefix(job_name).get_name();
        if (actual_job_name != null) {
            synchronized (client) {
                client.killTopology(actual_job_name);
            }
        }
    } catch (Exception ex) {
        //let die for now, usually happens when top doesn't exist
        logger.info(ErrorUtils.getLongForm(
                "Error stopping job: " + job_name
                        + "  this is typical with storm because the job may not exist that we try to kill {0}",
                ex));
        return FutureUtils.returnError(ex);
    }

    future.complete(ErrorUtils.buildSuccessMessage(this, "stopJob", "Stopped job successfully"));
    return future;
}

From source file:com.devicehive.rpcclient.RpcClientActionTest.java

@Test
public void testListDeviceAction() throws Exception {
    ListDeviceRequest deviceRequest = new ListDeviceRequest();
    deviceRequest.setName(UUID.randomUUID().toString()); // nonexistent name
    deviceRequest.setSortOrderAsc(false);

    Request request = Request.newBuilder().withBody(deviceRequest).build();
    CompletableFuture<Response> future = new CompletableFuture<>();
    client.call(request, future::complete);

    Response response = future.get(10, TimeUnit.SECONDS);
    ListDeviceResponse responseBody = (ListDeviceResponse) response.getBody();
    assertNotNull(responseBody.getDevices().isEmpty());
}

From source file:org.apache.pulsar.tests.integration.utils.DockerUtils.java

public static ContainerExecResult runCommand(DockerClient docker, String containerId, String... cmd)
        throws ContainerExecException {
    CompletableFuture<Boolean> future = new CompletableFuture<>();
    String execid = docker.execCreateCmd(containerId).withCmd(cmd).withAttachStderr(true).withAttachStdout(true)
            .exec().getId();//from   w w  w.  j  a v  a  2 s.com
    String cmdString = Arrays.stream(cmd).collect(Collectors.joining(" "));
    StringBuilder stdout = new StringBuilder();
    StringBuilder stderr = new StringBuilder();
    docker.execStartCmd(execid).withDetach(false).exec(new ResultCallback<Frame>() {
        @Override
        public void close() {
        }

        @Override
        public void onStart(Closeable closeable) {
            LOG.info("DOCKER.exec({}:{}): Executing...", containerId, cmdString);
        }

        @Override
        public void onNext(Frame object) {
            LOG.info("DOCKER.exec({}:{}): {}", containerId, cmdString, object);
            if (StreamType.STDOUT == object.getStreamType()) {
                stdout.append(new String(object.getPayload(), UTF_8));
            } else if (StreamType.STDERR == object.getStreamType()) {
                stderr.append(new String(object.getPayload(), UTF_8));
            }
        }

        @Override
        public void onError(Throwable throwable) {
            future.completeExceptionally(throwable);
        }

        @Override
        public void onComplete() {
            LOG.info("DOCKER.exec({}:{}): Done", containerId, cmdString);
            future.complete(true);
        }
    });
    future.join();

    InspectExecResponse resp = docker.inspectExecCmd(execid).exec();
    while (resp.isRunning()) {
        try {
            Thread.sleep(200);
        } catch (InterruptedException ie) {
            Thread.currentThread().interrupt();
            throw new RuntimeException(ie);
        }
        resp = docker.inspectExecCmd(execid).exec();
    }
    int retCode = resp.getExitCode();
    ContainerExecResult result = ContainerExecResult.of(retCode, stdout.toString(), stderr.toString());
    LOG.info("DOCKER.exec({}:{}): completed with {}", containerId, cmdString, retCode);

    if (retCode != 0) {
        throw new ContainerExecException(cmdString, containerId, result);
    }
    return result;
}

From source file:com.devicehive.handler.notification.NotificationSubscribeInsertIntegrationTest.java

@Test
@Ignore/*from  w w  w.  j a va 2  s .  c  om*/
public void shouldUnsubscribeFromNotifications() throws Exception {
    String device1 = randomUUID().toString();

    String subscriber1 = randomUUID().toString();
    String subscriber2 = randomUUID().toString();

    NotificationSubscribeRequest sr1 = new NotificationSubscribeRequest(subscriber1, device1, null, null);
    Request r1 = Request.newBuilder().withBody(sr1).withSingleReply(false).build();
    TestCallback c1 = new TestCallback();
    client.call(r1, c1);

    NotificationSubscribeRequest sr2 = new NotificationSubscribeRequest(subscriber2, device1, null, null);
    Request r2 = Request.newBuilder().withBody(sr2).withSingleReply(false).build();
    TestCallback c2 = new TestCallback();
    client.call(r2, c2);

    Stream.of(c1.subscribeFuture, c2.subscribeFuture).forEach(CompletableFuture::join);

    DeviceNotification notification = new DeviceNotification();
    notification.setId(0);
    notification.setNotification("temperature");
    notification.setDeviceGuid(device1);
    NotificationInsertRequest event = new NotificationInsertRequest(notification);
    CompletableFuture<Response> f1 = new CompletableFuture<>();
    client.call(Request.newBuilder().withBody(event).build(), f1::complete);

    f1.get(15, TimeUnit.SECONDS);

    assertThat(c1.notifications, hasSize(1));
    assertThat(c2.notifications, hasSize(1));

    NotificationUnsubscribeRequest ur = new NotificationUnsubscribeRequest(sr1.getSubscriptionId(), null);
    Request r3 = Request.newBuilder().withBody(ur).withSingleReply(false).build();
    client.call(r3, c1);

    c1.subscribeFuture.join();

    DeviceNotification notification2 = new DeviceNotification();
    notification2.setId(1);
    notification2.setNotification("temperature");
    notification2.setDeviceGuid(device1);
    NotificationInsertRequest event2 = new NotificationInsertRequest(notification2);
    CompletableFuture<Response> f2 = new CompletableFuture<>();
    client.call(Request.newBuilder().withBody(event2).build(), f2::complete);

    f2.join();

    assertThat(c1.notifications, hasSize(1));
    assertThat(c2.notifications, hasSize(2));
}

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(//from   w w  w.ja  va 2  s .  co  m
                    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);
        } 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:io.pravega.controller.store.stream.InMemoryStream.java

@Override
CompletableFuture<Void> setStateData(Data<Integer> newState) {
    Preconditions.checkNotNull(newState);

    CompletableFuture<Void> result = new CompletableFuture<>();
    synchronized (lock) {
        if (Objects.equals(this.state.getVersion(), newState.getVersion())) {
            this.state = new Data<>(newState.getData(), newState.getVersion() + 1);
            result.complete(null);//from w  w  w  .j a va 2s  .  c o m
        } else {
            result.completeExceptionally(StoreException.create(StoreException.Type.WRITE_CONFLICT, getName()));
        }
    }

    return result;
}

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

@Override
public CompletableFuture<BasicMessageBean> onPurge(DataBucketBean to_purge, IHarvestContext context) {
    //purge means that someone has dumped all the data from this harvest, nothing to do on
    //our end, just let the source keep running (e.g. like delete docs in the old harvester)
    CompletableFuture<BasicMessageBean> future = new CompletableFuture<BasicMessageBean>();
    future.complete(//from   w  w w  . j  ava 2  s  .  com
            new BasicMessageBean(new Date(), true, null, "onPurge", null, "Nothing to do for purge", null));
    return future;
}