Example usage for java.util.concurrent CompletableFuture get

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

Introduction

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

Prototype

@SuppressWarnings("unchecked")
public T get() throws InterruptedException, ExecutionException 

Source Link

Document

Waits if necessary for this future to complete, and then returns its result.

Usage

From source file:de.urszeidler.ethereum.licencemanager1.deployer.ContractsDeployer.java

/**
 * Deploys a 'LicenseIssuer' on the blockchain and wrapps the contract proxy.
 *  /* w  ww.  j  a v a  2s. co m*/
 * @param sender the sender address
 * @param itemName 
 * @param textHash 
 * @param url 
 * @param lifeTime 
 * @param price 
 * @param _pa 
 * @return the contract interface
 */
public DeployDuo<LicenseIssuer> createLicenseIssuer(EthAccount sender, String itemName, String textHash,
        String url, Integer lifeTime, Integer price, org.adridadou.ethereum.propeller.values.EthAddress _pa)
        throws IOException, InterruptedException, ExecutionException {
    CompletableFuture<EthAddress> address = deployLicenseIssuer(sender, itemName, textHash, url, lifeTime,
            price, _pa);
    return new EthereumInstance.DeployDuo<LicenseIssuer>(address.get(),
            createLicenseIssuerProxy(sender, address.get()));
}

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

@Test
public void sendPart_succ(@Mocked Part part, @Mocked InputStream inputStream)
        throws IOException, InterruptedException, ExecutionException {
    new Expectations() {
        {//from ww w.j  a va2  s . c  o  m
            part.getInputStream();
            result = inputStream;
            inputStream.read((byte[]) any);
            result = -1;
        }
    };

    CompletableFuture<Void> future = response.sendPart(part);

    Assert.assertNull(future.get());
}

From source file:org.apache.pulsar.broker.namespace.NamespaceServiceTest.java

@Test
public void testSplitAndOwnBundles() throws Exception {

    OwnershipCache MockOwnershipCache = spy(pulsar.getNamespaceService().getOwnershipCache());
    doNothing().when(MockOwnershipCache).disableOwnership(any(NamespaceBundle.class));
    Field ownership = NamespaceService.class.getDeclaredField("ownershipCache");
    ownership.setAccessible(true);/*from w ww. ja  v a  2s .co  m*/
    ownership.set(pulsar.getNamespaceService(), MockOwnershipCache);
    NamespaceService namespaceService = pulsar.getNamespaceService();
    NamespaceName nsname = new NamespaceName("pulsar/global/ns1");
    DestinationName dn = DestinationName.get("persistent://pulsar/global/ns1/topic-1");
    NamespaceBundles bundles = namespaceService.getNamespaceBundleFactory().getBundles(nsname);
    NamespaceBundle originalBundle = bundles.findBundle(dn);

    // Split bundle and take ownership of split bundles
    CompletableFuture<Void> result = namespaceService.splitAndOwnBundle(originalBundle);

    try {
        result.get();
    } catch (Exception e) {
        // make sure: no failure
        fail("split bundle faild", e);
    }
    NamespaceBundleFactory bundleFactory = this.pulsar.getNamespaceService().getNamespaceBundleFactory();
    NamespaceBundles updatedNsBundles = bundleFactory.getBundles(nsname);

    // new updated bundles shouldn't be null
    assertNotNull(updatedNsBundles);
    List<NamespaceBundle> bundleList = updatedNsBundles.getBundles();
    assertNotNull(bundles);

    NamespaceBundleFactory utilityFactory = NamespaceBundleFactory.createFactory(Hashing.crc32());

    // (1) validate bundleFactory-cache has newly split bundles and removed old parent bundle
    Pair<NamespaceBundles, List<NamespaceBundle>> splitBundles = splitBundles(utilityFactory, nsname, bundles,
            originalBundle);
    assertNotNull(splitBundles);
    Set<NamespaceBundle> splitBundleSet = new HashSet<>(splitBundles.getRight());
    splitBundleSet.removeAll(bundleList);
    assertTrue(splitBundleSet.isEmpty());

    // (2) validate LocalZookeeper policies updated with newly created split
    // bundles
    String path = joinPath(LOCAL_POLICIES_ROOT, nsname.toString());
    byte[] content = this.pulsar.getLocalZkCache().getZooKeeper().getData(path, null, new Stat());
    Policies policies = ObjectMapperFactory.getThreadLocal().readValue(content, Policies.class);
    NamespaceBundles localZkBundles = bundleFactory.getBundles(nsname, policies.bundles);
    assertTrue(updatedNsBundles.equals(localZkBundles));
    log.info("Policies: {}", policies);

    // (3) validate ownership of new split bundles by local owner
    bundleList.stream().forEach(b -> {
        try {
            byte[] data = this.pulsar.getLocalZkCache().getZooKeeper().getData(ServiceUnitZkUtils.path(b), null,
                    new Stat());
            NamespaceEphemeralData node = ObjectMapperFactory.getThreadLocal().readValue(data,
                    NamespaceEphemeralData.class);
            Assert.assertEquals(node.getNativeUrl(), this.pulsar.getBrokerServiceUrl());
        } catch (Exception e) {
            fail("failed to setup ownership", e);
        }
    });

}

From source file:org.apache.pulsar.functions.runtime.ProcessRuntime.java

/**
 * The core logic that initialize the thread container and executes the function
 *//*  w ww  . j a v  a2 s  . com*/
@Override
public void start() {
    java.lang.Runtime.getRuntime().addShutdownHook(new Thread(() -> process.destroy()));

    // Note: we create the expected log folder before the function process logger attempts to create it
    // This is because if multiple instances are launched they can encounter a race condition creation of the dir.

    log.info("Creating function log directory {}", funcLogDir);

    try {
        Files.createDirectories(Paths.get(funcLogDir));
    } catch (IOException e) {
        log.info("Exception when creating log folder : {}", funcLogDir, e);
        throw new RuntimeException("Log folder creation error");
    }

    log.info("Created or found function log directory {}", funcLogDir);

    startProcess();
    if (channel == null && stub == null) {
        channel = ManagedChannelBuilder.forAddress("127.0.0.1", instancePort).usePlaintext(true).build();
        stub = InstanceControlGrpc.newFutureStub(channel);

        timer = InstanceCache.getInstanceCache().getScheduledExecutorService().scheduleAtFixedRate(() -> {
            CompletableFuture<InstanceCommunication.HealthCheckResult> result = healthCheck();
            try {
                result.get();
            } catch (Exception e) {
                log.error("Health check failed for {}-{}", instanceConfig.getFunctionDetails().getName(),
                        instanceConfig.getInstanceId(), e);
            }
        }, expectedHealthCheckInterval, expectedHealthCheckInterval, TimeUnit.SECONDS);
    }
}

From source file:org.eclipse.languageserver.ProjectSpecificLanguageServerWrapper.java

private void start() throws IOException {
    if (this.languageClient != null) {
        if (stillActive()) {
            return;
        } else {//  w w  w.  j av a 2  s  .c o m
            stop();
        }
    }
    try {
        ExecutorService executorService = Executors.newCachedThreadPool();
        this.languageClient = new LanguageClientEndpoint(executorService);
        this.languageClient.setMessageTracer(new MessageTracer() {
            @Override
            public void onWrite(Message message, String json) {
                if (json.contains("telemetry/event")) {
                    return;
                }
                System.out.println("WRITE: ");
                System.out.println(json);
                System.out.println(message);
                System.out.println("");
            }

            @Override
            public void onRead(Message message, String json) {
                if (json.contains("telemetry/event")) {
                    return;
                }
                System.out.println("READ: ");
                System.out.println(json);
                System.out.println(message);
                System.out.println("");
            }

            @Override
            public void onError(String message, Throwable throwable) {
                System.err.println("ERR:");
                System.err.println("message: " + message);
                System.err.println("ex: ");
                if (throwable != null) {
                    throwable.printStackTrace(System.err);
                }
                if (throwable instanceof InvalidMessageException) {
                    //System.err.println("json unavailable, see https://github.com/TypeFox/ls-api/issues/51");
                    System.err.println("json: " + ((InvalidMessageException) throwable).getJson());
                }
            }
        });
        this.lspStreamProvider.start();
        MessageJsonHandler jsonHandler = new MessageJsonHandler();
        jsonHandler.setMethodResolver(this.languageClient);
        StreamMessageReader baseMessageReader = new StreamMessageReader(this.lspStreamProvider.getInputStream(),
                jsonHandler);
        ConcurrentMessageReader multiThreadReader = new ConcurrentMessageReader(baseMessageReader,
                executorService);
        MessageWriter writer = new StreamMessageWriter(this.lspStreamProvider.getOutputStream(), jsonHandler);
        languageClient.connect(multiThreadReader, writer);
        this.initializeJob = new Job("Initialize language server") {
            protected IStatus run(IProgressMonitor monitor) {
                InitializeParamsImpl initParams = new InitializeParamsImpl();
                initParams.setRootPath(project.getLocation().toFile().getAbsolutePath());
                String name = "Eclipse IDE";
                if (Platform.getProduct() != null) {
                    name = Platform.getProduct().getName();
                }
                initParams.setClientName(name);
                initParams.setCapabilities(new ClientCapabilitiesImpl());
                connectDiagnostics();
                CompletableFuture<InitializeResult> result = languageClient.initialize(initParams);
                try {
                    initializeResult = result.get();
                } catch (InterruptedException | ExecutionException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                return Status.OK_STATUS;
            }
        };
        this.initializeJob.setUser(true);
        this.initializeJob.setSystem(false);
        this.initializeJob.schedule();
    } catch (Exception ex) {
        ex.printStackTrace();
        stop();
    }
}

From source file:de.thingweb.servient.ServientTestHttp.java

@Test
public void attachListenerAndsetDirectly() throws Exception {
    CompletableFuture<Integer> future = new CompletableFuture<>();
    thing.onActionInvoke("testaction", (nv) -> {
        Integer newVal = ContentHelper.ensureClass(nv, Integer.class);
        future.complete(newVal);//from w w w .  ja va2 s .co  m
        return null;
    });

    TestTools.postHttpJson("http://localhost:8080/things/simplething/testaction", "42");

    assertThat("value is 42", future.get(), is(42));
}

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

public static String runCommand(DockerClient docker, String containerId, boolean ignoreError, String... cmd)
        throws Exception {
    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 .  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(), 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.get();

    InspectExecResponse resp = docker.inspectExecCmd(execid).exec();
    while (resp.isRunning()) {
        Thread.sleep(200);
        resp = docker.inspectExecCmd(execid).exec();
    }
    int retCode = resp.getExitCode();
    if (retCode != 0) {
        LOG.error("DOCKER.exec({}:{}): failed with {} : {}", containerId, cmdString, retCode, output);
        if (!ignoreError) {
            throw new Exception(
                    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.flink.yarn.YARNHighAvailabilityITCase.java

private JobID submitJob(RestClusterClient<ApplicationId> restClusterClient)
        throws InterruptedException, java.util.concurrent.ExecutionException {
    final CompletableFuture<JobSubmissionResult> jobSubmissionResultCompletableFuture = restClusterClient
            .submitJob(job);//from  w  ww .  j av a2  s .  c  o  m

    final JobSubmissionResult jobSubmissionResult = jobSubmissionResultCompletableFuture.get();
    return jobSubmissionResult.getJobID();
}

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;//ww  w  .j  a va  2s  .  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.tinkerpop.gremlin.driver.ResultQueueTest.java

@Test
public void shouldAwaitToExpectedValueAndDrainOnAwait() throws Exception {
    resultQueue.add(new Result("test1"));
    resultQueue.add(new Result("test2"));
    resultQueue.add(new Result("test3"));

    final CompletableFuture<List<Result>> future = resultQueue.await(3);
    assertThat(future.isDone(), is(true));

    final List<Result> results = future.get();
    assertEquals("test1", results.get(0).getString());
    assertEquals("test2", results.get(1).getString());
    assertEquals("test3", results.get(2).getString());
    assertEquals(3, results.size());/*from   w w w . java  2 s.  c  om*/

    assertThat(resultQueue.isEmpty(), is(true));
}