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:org.apache.bookkeeper.tests.integration.utils.DockerUtils.java

public static void dumpContainerLogToTarget(DockerClient docker, String containerId) {
    File output = new File(getTargetDirectory(containerId), "docker.log");
    try (FileOutputStream os = new FileOutputStream(output)) {
        CompletableFuture<Boolean> future = new CompletableFuture<>();
        docker.logContainerCmd(containerId).withStdOut(true).withStdErr(true).withTimestamps(true)
                .exec(new ResultCallback<Frame>() {
                    @Override//w w  w  . j  av a  2 s.  c  om
                    public void close() {
                    }

                    @Override
                    public void onStart(Closeable closeable) {
                    }

                    @Override
                    public void onNext(Frame object) {
                        try {
                            os.write(object.getPayload());
                        } catch (IOException e) {
                            onError(e);
                        }
                    }

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

                    @Override
                    public void onComplete() {
                        future.complete(true);
                    }
                });
        future.get();
    } catch (RuntimeException | ExecutionException | IOException e) {
        LOG.error("Error dumping log for {}", containerId, e);
    } catch (InterruptedException ie) {
        Thread.currentThread().interrupt();
        LOG.info("Interrupted dumping log from container {}", containerId, ie);
    }
}

From source file:org.jnode.net.NServerSocket.java

private CompletableFuture<ServerSocketChannel> createServerChannel(int port) {
    CompletableFuture cf = new CompletableFuture<>();
    try {//from  w w w  .ja v  a2s . c  o  m
        ServerSocketChannel ssc = ServerSocketChannel.open();
        ssc.configureBlocking(false);
        ssc.socket().bind(new InetSocketAddress(port));
        cf.complete(ssc);
    } catch (Exception e) {
        cf.completeExceptionally(e);
    }
    return cf;
}

From source file:com.devicehive.websockets.WebSocketApiInfoHandlerTest.java

@Test
public void shouldReturnApiInfo() throws Exception {
    final String requestId = "62345vxgsa5";

    CompletableFuture<TextMessage> future = new CompletableFuture<>();
    new StandardWebSocketClient().doHandshake(new TextWebSocketHandler() {
        @Override/*  w  ww  .  ja  v a2s.c o m*/
        protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
            future.complete(message);
        }
    }, wsBaseUri() + "/websocket/client").addCallback(session -> {
        JsonObject apiInfoRequest = JsonFixture.createWsCommand("server/info", requestId);
        try {
            session.sendMessage(new TextMessage(gson.toJson(apiInfoRequest)));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }, future::completeExceptionally);

    future.thenAccept(response -> {
        JsonObject jsonResp = gson.fromJson(response.getPayload(), JsonObject.class);

        assertThat(jsonResp.get("action").getAsString(), is("server/info"));
        assertThat(jsonResp.get("requestId").getAsString(), is(requestId));
        assertThat(jsonResp.get("status").getAsString(), is("success"));
    }).exceptionally(e -> {
        fail(e.getMessage());
        return null;
    }).get(5, TimeUnit.SECONDS);
}

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(
            new BasicMessageBean(new Date(), true, null, "onPurge", null, "Nothing to do for purge", null));
    return future;
}

From source file:org.apache.pulsar.broker.web.PulsarWebResource.java

protected static CompletableFuture<ClusterData> getClusterDataIfDifferentCluster(PulsarService pulsar,
        String cluster, String clientAppId) {

    CompletableFuture<ClusterData> clusterDataFuture = new CompletableFuture<>();

    if (!isValidCluster(pulsar, cluster)) {
        try {// ww  w  .ja  va  2 s .co m
            // this code should only happen with a v1 namespace format prop/cluster/namespaces
            if (!pulsar.getConfiguration().getClusterName().equals(cluster)) {
                // redirect to the cluster requested
                pulsar.getConfigurationCache().clustersCache().getAsync(path("clusters", cluster))
                        .thenAccept(clusterDataResult -> {
                            if (clusterDataResult.isPresent()) {
                                clusterDataFuture.complete(clusterDataResult.get());
                            } else {
                                log.warn("[{}] Cluster does not exist: requested={}", clientAppId, cluster);
                                clusterDataFuture.completeExceptionally(new RestException(Status.NOT_FOUND,
                                        "Cluster does not exist: cluster=" + cluster));
                            }
                        }).exceptionally(ex -> {
                            clusterDataFuture.completeExceptionally(ex);
                            return null;
                        });
            } else {
                clusterDataFuture.complete(null);
            }
        } catch (Exception e) {
            clusterDataFuture.completeExceptionally(e);
        }
    } else {
        clusterDataFuture.complete(null);
    }
    return clusterDataFuture;
}

From source file:org.pac4j.vertx.cas.VertxSharedDataLogoutHandler.java

@Override
public void destroySession(WebContext context) {
    final String logoutRequest = context.getRequestParameter("logoutRequest");
    LOG.debug("logoutRequest: {}", logoutRequest);
    final String ticket = StringUtils.substringBetween(logoutRequest, "SessionIndex>", "</");
    LOG.debug("extract ticket: {}", ticket);
    // get the session id first, then remove the pac4j profile from that session
    // TODO:        ALSO MODIFY TO REMOVE VERTX USER
    final CompletableFuture<Void> userLogoutFuture = new CompletableFuture<>();
    final String sessionId = getSessionId(ticket);
    sessionStore.getObservable(sessionId).map(session -> session.remove(SESSION_USER_HOLDER_KEY))
            .doOnError(e -> {// w  ww  .ja v a 2 s  .  co m
                e.printStackTrace();
            }).subscribe(s -> userLogoutFuture.complete(null));
    try {
        userLogoutFuture.get(blockingTimeoutSeconds, TimeUnit.SECONDS);
    } catch (InterruptedException | ExecutionException | TimeoutException e) {
        userLogoutFuture.completeExceptionally(new TechnicalException(e));
    }

    doDestroySession(ticket);
}

From source file:org.apache.pulsar.client.impl.HttpLookupService.java

@Override
public CompletableFuture<Optional<SchemaInfo>> getSchema(TopicName topicName) {
    CompletableFuture<Optional<SchemaInfo>> future = new CompletableFuture<>();

    String schemaName = topicName.getSchemaName();
    String path = String.format("admin/v2/schemas/%s/schema", schemaName);

    httpClient.get(path, GetSchemaResponse.class).thenAccept(response -> {
        future.complete(Optional.of(SchemaInfoUtil.newSchemaInfo(schemaName, response)));
    }).exceptionally(ex -> {// w w w.j a v  a  2 s  .  c o m
        if (ex.getCause() instanceof NotFoundException) {
            future.complete(Optional.empty());
        } else {
            log.warn("Failed to get schema for topic {} : {}", topicName, ex.getCause().getClass());
            future.completeExceptionally(ex);
        }
        return null;
    });
    return future;
}

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

public static void dumpContainerLogToTarget(DockerClient dockerClient, String containerId) {
    InspectContainerResponse inspectContainerResponse = dockerClient.inspectContainerCmd(containerId).exec();
    // docker api returns names prefixed with "/", it's part of it's legacy design,
    // this removes it to be consistent with what docker ps shows.
    final String containerName = inspectContainerResponse.getName().replace("/", "");
    File output = new File(getTargetDirectory(containerName), "docker.log");
    int i = 0;//from w w  w.j  a va  2 s . c o m
    while (output.exists()) {
        LOG.info("{} exists, incrementing", output);
        output = new File(getTargetDirectory(containerName), "docker." + i++ + ".log");
    }
    try (FileOutputStream os = new FileOutputStream(output)) {
        CompletableFuture<Boolean> future = new CompletableFuture<>();
        dockerClient.logContainerCmd(containerName).withStdOut(true).withStdErr(true).withTimestamps(true)
                .exec(new ResultCallback<Frame>() {
                    @Override
                    public void close() {
                    }

                    @Override
                    public void onStart(Closeable closeable) {
                    }

                    @Override
                    public void onNext(Frame object) {
                        try {
                            os.write(object.getPayload());
                        } catch (IOException e) {
                            onError(e);
                        }
                    }

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

                    @Override
                    public void onComplete() {
                        future.complete(true);
                    }
                });
        future.get();
    } catch (RuntimeException | ExecutionException | IOException e) {
        LOG.error("Error dumping log for {}", containerName, e);
    } catch (InterruptedException ie) {
        Thread.currentThread().interrupt();
        LOG.info("Interrupted dumping log from container {}", containerName, ie);
    }
}

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();//from   w w w .j  a v a 2  s .co  m
    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.onlab.nio.service.IOLoopMessaging.java

protected CompletableFuture<Void> sendAsync(Endpoint ep, DefaultMessage message) {
    CompletableFuture<Void> future = new CompletableFuture<>();
    if (ep.equals(localEp)) {
        dispatchLocally(message);//  w ww  .j  av  a  2s  .c om
        future.complete(null);
        return future;
    }

    DefaultMessageStream stream = null;
    try {
        stream = streams.borrowObject(ep);
        stream.write(message);
        future.complete(null);
    } catch (Exception e) {
        future.completeExceptionally(e);
    } finally {
        try {
            streams.returnObject(ep, stream);
        } catch (Exception e) {
            log.warn("Failed to return stream to pool");
        }
    }
    return future;
}