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(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException 

Source Link

Document

Waits if necessary for at most the given time for this future to complete, and then returns its result, if available.

Usage

From source file:org.springframework.integration.config.xml.GatewayParserTests.java

@Test
public void testAsyncCompletable() throws Exception {
    QueueChannel requestChannel = (QueueChannel) context.getBean("requestChannel");
    final AtomicReference<Thread> thread = new AtomicReference<>();
    requestChannel.addInterceptor(new ChannelInterceptorAdapter() {

        @Override/*  w w  w . jav a2  s. co m*/
        public Message<?> preSend(Message<?> message, MessageChannel channel) {
            thread.set(Thread.currentThread());
            return super.preSend(message, channel);
        }

    });
    MessageChannel replyChannel = (MessageChannel) context.getBean("replyChannel");
    this.startResponder(requestChannel, replyChannel);
    TestService service = context.getBean("asyncCompletable", TestService.class);
    CompletableFuture<String> result = service.completable("foo").thenApply(String::toUpperCase);
    String reply = result.get(10, TimeUnit.SECONDS);
    assertEquals("FOO", reply);
    assertThat(thread.get().getName(), startsWith("testExec-"));
    assertNotNull(TestUtils.getPropertyValue(context.getBean("&asyncCompletable"), "asyncExecutor"));
}

From source file:org.springframework.integration.config.xml.GatewayParserTests.java

@Test
public void testAsyncCompletableNoAsyncMessage() throws Exception {
    QueueChannel requestChannel = (QueueChannel) context.getBean("requestChannel");
    final AtomicReference<Thread> thread = new AtomicReference<>();
    requestChannel.addInterceptor(new ChannelInterceptorAdapter() {

        @Override//from w ww .j a  v a 2  s  . c om
        public Message<?> preSend(Message<?> message, MessageChannel channel) {
            thread.set(Thread.currentThread());
            return super.preSend(message, channel);
        }

    });
    MessageChannel replyChannel = (MessageChannel) context.getBean("replyChannel");
    this.startResponder(requestChannel, replyChannel);
    TestService service = context.getBean("completableNoAsync", TestService.class);
    CompletableFuture<Message<?>> result = service.completableReturnsMessage("flowCompletableM");
    Message<?> reply = result.get(1, TimeUnit.SECONDS);
    assertEquals("flowCompletableM", reply.getPayload());
    assertEquals(Thread.currentThread(), thread.get());
    assertNull(TestUtils.getPropertyValue(context.getBean("&completableNoAsync"), "asyncExecutor"));
}

From source file:org.apache.samza.system.eventhub.producer.EventHubSystemProducer.java

@Override
public synchronized void stop() {
    LOG.info("Stopping producer.");
    streamPartitionSenders.values().forEach((streamPartitionSender) -> {
        List<CompletableFuture<Void>> futures = new ArrayList<>();
        streamPartitionSender.forEach((key, value) -> futures.add(value.close()));
        CompletableFuture<Void> future = CompletableFuture
                .allOf(futures.toArray(new CompletableFuture[futures.size()]));
        try {/*w ww  .  j a  v a  2s .  c  o m*/
            future.get(DEFAULT_SHUTDOWN_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
        } catch (ExecutionException | InterruptedException | TimeoutException e) {
            LOG.error("Closing the partition sender failed ", e);
        }
    });
    perStreamEventHubClientManagers.values().parallelStream()
            .forEach(ehClient -> ehClient.close(DEFAULT_SHUTDOWN_TIMEOUT_MILLIS));
    perStreamEventHubClientManagers.clear();
    if (config.getPerPartitionConnection(systemName)) {
        perPartitionEventHubClients.values().stream().flatMap(map -> map.values().stream())
                .forEach(ehClient -> ehClient.close(DEFAULT_SHUTDOWN_TIMEOUT_MILLIS));
        perPartitionEventHubClients.clear();
    }
    isStarted = false;
    isInitialized = false;
    LOG.info("EventHubSystemProducer stopped.");
}

From source file:co.runrightfast.vertx.core.impl.VertxServiceImpl.java

@Override
protected void shutDown() {
    if (vertx != null) {
        appEventLogger.accept(AppEvent.info(APP_STOPPING).build());
        final CompletableFuture<AsyncResult<Void>> closeResult = new CompletableFuture<>();
        vertx.close(closeResult::complete);
        while (true) {
            try {
                closeResult.get(10, TimeUnit.SECONDS);
                LOG.info("Vertx shutdown is complete.");
                appEventLogger.accept(AppEvent.info(APP_STOPPED).build());
                vertx = null;//  w ww .  j  ava2s .c  o  m
                vertxOptions = null;
                break;
            } catch (final ExecutionException ex) {
                appEventLogger.accept(AppEvent.info(APP_STOP_EXCEPTION).setException(ex).build());
                throw new RuntimeException("shutdown failed", ex);
            } catch (final TimeoutException ex) {
                LOG.logp(INFO, getClass().getName(), "shutDown", "Waiting for Vertx to shutdown");
            } catch (final InterruptedException ex) {
                appEventLogger.accept(AppEvent.info(APP_STOP_EXCEPTION).setException(ex).build());
                throw new RuntimeException(ex);
            }
        }
    }
}

From source file:ai.grakn.engine.controller.TasksController.java

private Json buildResponseForTasks(Response response, Json responseJson,
        CompletableFuture<List<Json>> completableFuture)
        throws InterruptedException, java.util.concurrent.ExecutionException, TimeoutException {
    List<Json> results = completableFuture.get(MAX_EXECUTION_TIME.getSeconds(), TimeUnit.SECONDS);
    boolean hasFailures = false;
    for (Json resultForTask : results) {
        responseJson.add(resultForTask);
        if (resultForTask.at("code").asInteger() != HttpStatus.SC_OK) {
            LOG.error("Could not add task {}", resultForTask);
            hasFailures = true;//  w w  w. j a  v  a2 s  . c om
        }
    }
    if (!hasFailures) {
        response.status(HttpStatus.SC_OK);
    } else if (responseJson.asJsonList().size() > 0) {
        response.status(HttpStatus.SC_ACCEPTED);
    } else {
        response.status(HttpStatus.SC_INTERNAL_SERVER_ERROR);
    }
    return responseJson;
}

From source file:co.runrightfast.vertx.core.impl.VertxServiceImpl.java

private void deployVerticleManager() throws InterruptedException {
    final CompletableFuture<AsyncResult<String>> deployVerticleResult = new CompletableFuture<>();
    vertx.deployVerticle(verticleManager, deployVerticleResult::complete);
    while (true) {
        try {//from  w ww . ja  v a  2s . c o m
            final AsyncResult<String> result = deployVerticleResult.get(10, TimeUnit.SECONDS);
            if (result.succeeded()) {
                LOG.logp(INFO, getClass().getName(), "deployVerticleManager", result.result());
            } else {
                throw new RuntimeException("Failed to deploy RunRightFastVerticleManager", result.cause());
            }
            break;
        } catch (final ExecutionException ex) {
            throw new RuntimeException("Failed to deploy RunRightFastVerticleManager", ex);
        } catch (final TimeoutException ex) {
            LOG.logp(INFO, getClass().getName(), "deployVerticleManager",
                    "Waiting for RunRightFastVerticleManager deployment to complete");
        } catch (final InterruptedException ex) {
            throw new RuntimeException(ex);
        }
    }
}

From source file:co.runrightfast.vertx.core.impl.VertxServiceImpl.java

private void initVertx() {
    if (this.vertxOptions.isClustered()) {
        final CompletableFuture<AsyncResult<Vertx>> clusteredVertxResult = new CompletableFuture<>();
        Vertx.clusteredVertx(vertxOptions, clusteredVertxResult::complete);
        while (true) {
            try {
                final AsyncResult<Vertx> result = clusteredVertxResult.get(10, TimeUnit.SECONDS);
                if (result.succeeded()) {
                    this.vertx = result.result();
                    LOG.logp(INFO, getClass().getName(), "initVertx",
                            "Vertx clustered instance has been created");
                } else {
                    throw new RuntimeException("Failed to start a clustered Vertx instance", result.cause());
                }/*from   w ww . ja  va2 s  .  c o  m*/
                break;
            } catch (final ExecutionException ex) {
                throw new RuntimeException("Failed to start a clustered Vertx instance", ex);
            } catch (final TimeoutException ex) {
                LOG.logp(INFO, getClass().getName(), "initVertx", "Waiting for Vertx to start");
            } catch (final InterruptedException ex) {
                throw new RuntimeException(ex);
            }
        }
    } else {
        this.vertx = Vertx.vertx(vertxOptions);
        LOG.logp(INFO, getClass().getName(), "initVertx", "Vertx instance has been created");
    }
}

From source file:co.runrightfast.vertx.orientdb.verticle.OrientDBVerticleTest.java

@Test
public void testEventLogRepository_getEventCount() throws Exception {
    final Vertx vertx = vertxService.getVertx();
    final RunRightFastVerticleId verticleId = EventLogRepository.VERTICLE_ID;

    final long timeout = 60000L;

    final ProtobufMessageProducer<GetEventCount.Request> getEventCountMessageProducer = new ProtobufMessageProducer<>(
            vertx.eventBus(), EventBusAddress.eventBusAddress(verticleId, GetEventCount.class),
            new ProtobufMessageCodec<>(GetEventCount.Request.getDefaultInstance()), metricRegistry);

    // because the verticles are deployed asynchronously, the EventLogRepository verticle may not yet be deployed yet
    // the message consumer for the Verticle only gets registered, while the verticle is starting. Thus, the message consumer may not yet be registered.
    while (true) {
        final CompletableFuture<GetEventCount.Response> getEventCountFuture = new CompletableFuture<>();
        getEventCountMessageProducer.send(GetEventCount.Request.getDefaultInstance(),
                responseHandler(getEventCountFuture, GetEventCount.Response.class));
        try {/*w w w  .java  2 s.com*/
            getEventCountFuture.get(timeout, TimeUnit.MILLISECONDS);
            break;
        } catch (final ExecutionException e) {
            if (e.getCause() instanceof ReplyException) {
                final ReplyException replyException = (ReplyException) e.getCause();
                if (replyException.failureType() == NO_HANDLERS) {
                    log.log(WARNING, "Waiting for EventLogRepository ... ", e);
                    Thread.sleep(5000L);
                    continue;
                }
            }
            throw e;
        }
    }
}

From source file:co.runrightfast.vertx.core.application.RunRightFastVertxApplicationLauncherTest.java

@Test
public void testRunApp() throws Exception {
    ForkJoinPool.commonPool().execute(() -> RunRightFastVertxApplicationLauncher.run(() -> app));

    final RunRightFastVerticleId verticleManagerId = RunRightFastVerticleManager.VERTICLE_ID;
    final CompletableFuture future = new CompletableFuture();
    final String address = EventBusAddress.eventBusAddress(verticleManagerId, "get-verticle-deployments");
    final Vertx vertx = app.vertxService().getVertx();
    vertx.eventBus().send(address, GetVerticleDeployments.Request.newBuilder().build(),
            new DeliveryOptions().setSendTimeout(2000L), getVerticleDeploymentsResponseHandler(future));
    final Object result = future.get(2000L, TimeUnit.MILLISECONDS);

    final ApplicationMXBean appMXBean = JMX.newMBeanProxy(ManagementFactory.getPlatformMBeanServer(),
            applicationMBeanObjectName(JmxUtils.RUNRIGHTFAST_JMX_DOMAIN, ApplicationMXBean.class),
            ApplicationMXBean.class);
    assertThat(appMXBean.getApplicationGroup(), is("co.runrightfast"));
    assertThat(appMXBean.getApplicationName(), is("test-app"));
    assertThat(appMXBean.getApplicationVersion(), is("1.0.0"));
    log.logp(INFO, getClass().getName(), "testRunApp", "{0}:\n{1}",
            new Object[] { "configAsHConf", appMXBean.configAsHConf() });
    log.logp(INFO, getClass().getName(), "testRunApp", "{0}:\n{1}",
            new Object[] { "configAsHJson", appMXBean.configAsJson() });
    log.logp(INFO, getClass().getName(), "testRunApp", "{0}:\n{1}",
            new Object[] { "configWithCommentsAndSourceInfo", appMXBean.configWithCommentsAndSourceInfo() });
    appMXBean.shutdown();/*w  ww.  ja  v a  2s .  c  om*/
    app.vertxService().awaitTerminated();
}

From source file:co.runrightfast.vertx.demo.testHarness.jmx.DemoMXBeanImpl.java

@Override
public long eventLogRecordCount() {
    if (this.getEventCountMessageProducer == null) {
        getEventCountMessageProducer = new ProtobufMessageProducer<>(vertx.eventBus(),
                EventBusAddress.eventBusAddress(EventLogRepository.VERTICLE_ID, GetEventCount.class),
                new ProtobufMessageCodec<>(GetEventCount.Request.getDefaultInstance()), metricRegistry);
    }/*w  ww .  j  a  va  2 s.com*/

    try {
        final CompletableFuture<GetEventCount.Response> getEventCountFuture = new CompletableFuture<>();
        getEventCountMessageProducer.send(GetEventCount.Request.getDefaultInstance(),
                responseHandler(getEventCountFuture, GetEventCount.Response.class));
        final GetEventCount.Response response = getEventCountFuture.get(2, TimeUnit.SECONDS);
        return response.getCount();
    } catch (final InterruptedException | ExecutionException | TimeoutException ex) {
        log.logp(SEVERE, getClass().getName(), "getEventLogRecordCount", "failed", ex);
        throw new RuntimeException("Failed to get event log record count: " + ex.getMessage());
    }
}