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:org.apache.pulsar.tests.DockerUtils.java

public static String runCommand(DockerClient docker, String containerId, String... cmd) {
    CompletableFuture<Boolean> future = new CompletableFuture<>();
    String execid = docker.execCreateCmd(containerId).withCmd(cmd).withAttachStderr(true).withAttachStdout(true)
            .exec().getId();/* w w  w.j  a  va 2  s . c  om*/
    String cmdString = Arrays.stream(cmd).collect(Collectors.joining(" "));
    StringBuffer output = new StringBuffer();
    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);
            output.append(new String(object.getPayload()));
        }

        @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();
    if (retCode != 0) {
        throw new RuntimeException(
                String.format("cmd(%s) failed on %s with exitcode %d", cmdString, containerId, retCode));
    } else {
        LOG.info("DOCKER.exec({}:{}): completed with {}", containerId, cmdString, retCode);
    }
    return output.toString();
}

From source file:org.apache.trafficcontrol.client.trafficops.TOSession.java

public CompletableFuture<Response.CollectionResponse> getDeliveryServices(final Map<String, ?> filterParams) {
    URI uri;// ww w.  j av a2  s . co m
    try {
        uri = this.newUriBuilder("deliveryservices.json").setParameters(this.toPairs(filterParams)).build();
    } catch (Throwable e) {
        final CompletableFuture<Response.CollectionResponse> f = new CompletableFuture<>();
        f.completeExceptionally(e);
        return f;
    }
    LOG.debug("getDeliveryService url {}", uri);
    return ResponseFuture.builder(Response.CollectionResponse.class).setMethod(ResponseFuture.Method.GET)
            .setUri(uri).setSession(this.restClient()).build();
}

From source file:org.apache.servicecomb.foundation.vertx.VertxUtils.java

public static CompletableFuture<Void> closeVertxByName(String name) {
    LOGGER.info("Closing vertx {}.", name);
    CompletableFuture<Void> future = new CompletableFuture<>();
    Vertx vertx = vertxMap.remove(name);
    if (vertx == null) {
        LOGGER.info("Vertx {} not exist.", name);
        future.complete(null);/*from   w w w  .j ava2s . co  m*/
        return future;
    }

    vertx.close(ar -> {
        if (ar.succeeded()) {
            LOGGER.info("Success to close vertx {}.", name);
            future.complete(null);
            return;
        }

        future.completeExceptionally(ar.cause());
    });
    return future;
}

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

@Test
public void testNotificationInsertAction() throws Exception {
    DeviceNotification notification = new DeviceNotification();
    notification.setNotification("test_notification");
    notification.setDeviceGuid(UUID.randomUUID().toString());
    NotificationInsertRequest insertRequest = new NotificationInsertRequest(notification);

    Request request = Request.newBuilder()
            .withPartitionKey(insertRequest.getDeviceNotification().getDeviceGuid()).withBody(insertRequest)
            .build();/*from   www  .j  av a2 s  . c o m*/
    CompletableFuture<Response> future = new CompletableFuture<>();
    client.call(request, future::complete);

    Response response = future.get(10, TimeUnit.SECONDS);
    NotificationInsertResponse responseBody = (NotificationInsertResponse) response.getBody();
    assertNotNull(responseBody.getDeviceNotification());
}

From source file:org.apache.servicecomb.foundation.vertx.http.ReadStreamPart.java

/**
 *
 * @param file/*from ww w . j a v  a 2 s  .c o  m*/
 * @param openOptions
 * @return future of save to file, future complete means write to file finished
 */
public CompletableFuture<File> saveToFile(File file, OpenOptions openOptions) {
    CompletableFuture<File> future = new CompletableFuture<>();

    context.runOnContext((v) -> {
        Vertx vertx = context.owner();
        vertx.fileSystem().open(file.getAbsolutePath(), openOptions, ar -> {
            onFileOpened(file, ar, future);
        });
    });

    return future;
}

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

private CompletableFuture<Response> insertNotification(DeviceNotification notification) {
    final CompletableFuture<Response> future = new CompletableFuture<>();
    client.call(Request.newBuilder().withBody(new NotificationInsertRequest(notification))
            .withPartitionKey(notification.getDeviceGuid()) // partitioning by guid
            .build(), future::complete);
    return future;
}

From source file:org.apache.bookkeeper.stream.storage.impl.sc.ZkStorageContainerManagerTest.java

/**
 * Test basic operations such as starting or stopping containers.
 *///from  w  ww  . j  a v  a2  s .co m
@Test
public void testBasicOps() throws Exception {
    // start the storage container manager
    scManager.start();

    long containerId = 11L;
    long containerId2 = 22L;

    // mock a container and start it in the registry
    CompletableFuture<StorageContainer> startFuture = new CompletableFuture<>();
    CompletableFuture<Void> stopFuture = new CompletableFuture<>();
    CompletableFuture<StorageContainer> startFuture2 = new CompletableFuture<>();
    CompletableFuture<Void> stopFuture2 = new CompletableFuture<>();

    StorageContainer mockSc = createStorageContainer(containerId, startFuture, stopFuture);
    when(mockScFactory.createStorageContainer(eq(containerId))).thenReturn(mockSc);

    StorageContainer mockSc2 = createStorageContainer(containerId2, startFuture2, stopFuture2);
    when(mockScFactory.createStorageContainer(eq(containerId2))).thenReturn(mockSc2);

    // update assignment map
    ClusterAssignmentData cad = ClusterAssignmentData.newBuilder()
            .putServers(NetUtils.endpointToString(myEndpoint),
                    ServerAssignmentData.newBuilder().addContainers(containerId).build())
            .build();
    clusterMetadataStore.updateClusterAssignmentData(cad);

    // notify the container to complete startup
    startFuture.complete(mockSc);
    verify(scRegistry, timeout(10000).times(1)).startStorageContainer(eq(containerId));
    MoreAsserts.assertUtil(ignored -> scManager.getLiveContainers().size() >= 1, () -> null);
    assertEquals(1, scManager.getLiveContainers().size());
    assertTrue(scManager.getLiveContainers().containsKey(containerId));

    // update assignment map to remove containerId and add containerId2
    ClusterAssignmentData newCad = ClusterAssignmentData.newBuilder()
            .putServers(NetUtils.endpointToString(myEndpoint),
                    ServerAssignmentData.newBuilder().addContainers(22L).build())
            .build();
    clusterMetadataStore.updateClusterAssignmentData(newCad);

    // notify the container1 to stop and container2 to start
    FutureUtils.complete(stopFuture, null);
    startFuture2.complete(mockSc2);
    verify(scRegistry, timeout(10000).times(1)).stopStorageContainer(eq(containerId), same(mockSc));
    verify(scRegistry, timeout(10000).times(1)).startStorageContainer(eq(containerId2));
    MoreAsserts.assertUtil(ignored -> !scManager.getLiveContainers().containsKey(containerId)
            && scManager.getLiveContainers().containsKey(containerId2), () -> null);
    assertEquals(1, scManager.getLiveContainers().size());
    assertFalse(scManager.getLiveContainers().containsKey(containerId));
    assertTrue(scManager.getLiveContainers().containsKey(containerId2));
}

From source file:com.hp.octane.integrations.services.vulnerabilities.VulnerabilitiesServiceImpl.java

@Override
public void shutdown() {
    workerExited = new CompletableFuture<>();
    vulnerabilitiesProcessingExecutor.shutdown();
    try {//www.j a v a2s.  c om
        NO_VULNERABILITIES_RESULTS_MONITOR.notify();
        workerExited.get(3000, TimeUnit.SECONDS);
    } catch (Exception e) {
        logger.warn("interrupted while waiting for the worker SHUT DOWN");
    }
}

From source file:com.adobe.acs.commons.mcp.impl.processes.renovator.RenovatorTest.java

@Test
public void testHaltingScenario() throws DeserializeException, LoginException, RepositoryException,
        InterruptedException, ExecutionException, PersistenceException {
    assertEquals("Renovator: relocator test", instance.getName());
    Map<String, Object> values = new HashMap<>();
    values.put("sourceJcrPath", "/content/dam/folderA");
    values.put("destinationJcrPath", "/content/dam/folderB");
    instance.init(rr, values);/*from   w w  w  . j  a  v  a2  s . com*/

    CompletableFuture<Boolean> f = new CompletableFuture<>();

    instance.defineAction("Halt", rr, am -> {
        instance.halt();
        try {
            assertTrue(instance.updateProgress() < 1.0);
            assertFalse(instance.getInfo().isIsRunning());
            f.complete(true);
        } catch (Throwable t) {
            f.completeExceptionally(t);
        }
    });
    instance.run(rr);
    assertTrue(f.get());
    verify(rr, atLeastOnce()).commit();
}

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

/**
 * Submits a job to the remote storm cluster.  Sends the input jar to the server and then
 * submits the supplied topology w/ the given job_name.
 * //from  ww  w  .j  a  v a2s. co m
 */
@Override
public CompletableFuture<BasicMessageBean> submitJob(String job_name, String input_jar_location,
        StormTopology topology, Map<String, Object> config_override) {
    final CompletableFuture<BasicMessageBean> future = new CompletableFuture<BasicMessageBean>();
    logger.info("Submitting job: " + job_name + " jar: " + input_jar_location);
    logger.info("submitting jar");

    final String remote_jar_location = StormSubmitter.submitJar(remote_config, input_jar_location);
    //      final String json_conf = JSONValue.toJSONString(ImmutableMap.builder()
    //               .putAll(remote_config)
    //               .putAll(config_override)
    //            .build());
    final String json_conf = JSONValue.toJSONString(mergeMaps(Arrays.asList(remote_config, config_override)));
    logger.info("submitting topology");
    try {
        synchronized (client) {
            client.submitTopology(job_name, remote_jar_location, json_conf, topology);
        }
        //verify job was assigned some executors
        final TopologyInfo info = getJobStats(job_name);
        logger.info("submitted job received: " + info.get_executors_size() + " executors");
        if (info.get_executors_size() == 0) {
            logger.info("received 0 executors, killing job, reporting failure");
            //no executors were available for this job, stop the job, throw an error
            stopJob(job_name);

            future.complete(ErrorUtils.buildErrorMessage(this, "submitJob",
                    "No executors were assigned to this job, typically this is because too many jobs are currently running, kill some other jobs and resubmit."));
            return future;
        }
    } catch (Exception ex) {
        logger.info(ErrorUtils.getLongForm("Error submitting job: " + job_name + ": {0}", ex));
        return FutureUtils.returnError(ex);
    }

    future.complete(
            ErrorUtils.buildSuccessMessage(this, "submitJob", "Submitted job successfully: " + job_name));
    return future;
}