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:io.ventu.rpc.integration.rest.TestRestInvocationRoundtrip.java

@Test
public void invoke_basicRoundtrip_server500_error()
        throws InterruptedException, TimeoutException, ExecutionException {
    RemoteInvoker invoker = HttpRestInvoker.host("localhost").port(23332).header("APIKEY", "123").ssl(false)
            .build();/*from   w  ww  .  j a v  a  2 s .  co  m*/

    try {
        CompletableFuture<Res> future = invoker.invoke(new Unsupported(25), Res.class);
        exception.expect(ExecutionException.class);
        future.get(500, TimeUnit.MILLISECONDS);
    } catch (ExecutionException ex) {
        HttpException cause = (HttpException) ex.getCause();
        assertEquals(500, cause.getStatusCode());
        throw ex;
    } finally {
        invoker.close().get(500, TimeUnit.MILLISECONDS);
    }
}

From source file:io.fabric8.kubeflix.examples.loanbroker.broker.BrokerController.java

@RequestMapping("/quote")
public List<Quote> quote(@RequestParam("ssn") Long ssn, @RequestParam("amount") Double amount,
        @RequestParam("duration") Integer duration)
        throws InterruptedException, ExecutionException, TimeoutException {
    HystrixRequestContext context = HystrixRequestContext.initializeContext();
    try {/*from   w w  w  . jav a 2s  .c  om*/
        if (async) {
            //Broadcast requests async
            List<CompletableFuture<Quote>> futures = client.services()
                    .withLabel(PROJECT_NAME, LOADBALANCER_BANK).list().getItems().stream()
                    .map(s -> this.requestQuoteAsync(s, ssn, amount, duration)).collect(Collectors.toList());

            //Collect the results
            CompletableFuture<List<Quote>> result = CompletableFuture
                    .allOf(futures.toArray(new CompletableFuture[futures.size()]))
                    .thenApply(v -> futures.stream().map(CompletableFuture::join).collect(Collectors.toList()));

            return result.get(15, TimeUnit.SECONDS);
        }

        return client.services().withLabel(PROJECT_NAME, LOADBALANCER_BANK).list().getItems().stream()
                .map(s -> this.requestQuote(s, ssn, amount, duration)).collect(Collectors.toList());
    } finally {
        context.shutdown();
    }
}

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

@Test
@Ignore/*from www. java  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:org.apache.flink.yarn.YARNHighAvailabilityITCase.java

private void waitForJobTermination(final RestClusterClient<ApplicationId> restClusterClient, final JobID jobId)
        throws Exception {
    stopJobSignal.signal();/*from w w w.ja  v  a  2s.  c  om*/
    final CompletableFuture<JobResult> jobResult = restClusterClient.requestJobResult(jobId);
    jobResult.get(TIMEOUT.toMillis(), TimeUnit.MILLISECONDS);
}

From source file:org.onosproject.d.config.sync.impl.netconf.NetconfDeviceConfigSynchronizerProviderTest.java

@Test
public void testDeleteOperation() throws Exception {
    // plug drivers with assertions
    testYangRuntime = onEncode((data, context) -> {
        assertEquals("xml", context.getDataFormat());
        assertThat(context.getProtocolAnnotations(), hasItem(XC_ANNOTATION));

        //  assert CompositeData
        ResourceData rData = data.resourceData();
        List<AnnotatedNodeInfo> infos = data.annotatedNodesInfo();

        ResourceId interfacesRid = RID_INTERFACES;
        AnnotatedNodeInfo intfsAnnot = DefaultAnnotatedNodeInfo.builder().resourceId(interfacesRid)
                .addAnnotation(AN_XC_REMOVE_OPERATION).build();
        assertThat("interfaces has replace operation", infos, hasItem(intfsAnnot));

        // assertion for ResourceData.
        assertEquals(RID_INTERFACES, rData.resourceId());
        assertThat("has no child", rData.dataNodes(), hasSize(0));

        // FIXME it's unclear what URI is expected here
        String id = URI.create("netconf:testDevice").toString();

        String inXml = deviceConfigAsXml("remove");

        return toCompositeStream(id, inXml);
    });/*w ww.j a  v a  2s  . c om*/
    testNcSession = new TestEditNetconfSession();

    // building test data
    ResourceId interfacesId = RID_INTERFACES;
    SetRequest request = SetRequest.builder().delete(interfacesId).build();

    // test start
    CompletableFuture<SetResponse> f = sut.setConfiguration(DID, request);

    SetResponse response = f.get(5, TimeUnit.MINUTES);
    assertEquals(Code.OK, response.code());
    assertEquals(request.subjects(), response.subjects());
}

From source file:org.onosproject.d.config.sync.impl.netconf.NetconfDeviceConfigSynchronizerProviderTest.java

@Test
public void testReplaceOperation() throws Exception {
    // plug drivers with assertions
    testYangRuntime = onEncode((data, context) -> {
        assertEquals("xml", context.getDataFormat());
        assertThat(context.getProtocolAnnotations(), hasItem(XC_ANNOTATION));

        //  assert CompositeData
        ResourceData rData = data.resourceData();
        List<AnnotatedNodeInfo> infos = data.annotatedNodesInfo();

        ResourceId interfacesRid = RID_INTERFACES;
        AnnotatedNodeInfo intfsAnnot = DefaultAnnotatedNodeInfo.builder().resourceId(interfacesRid)
                .addAnnotation(AN_XC_REPLACE_OPERATION).build();
        assertThat("interfaces has replace operation", infos, hasItem(intfsAnnot));

        // assertion for ResourceData.
        assertEquals(RID_INTERFACES, rData.resourceId());
        assertThat("has 1 child", rData.dataNodes(), hasSize(1));
        assertThat("which is interface", rData.dataNodes().get(0).key().schemaId().name(), is("interface"));
        // todo: assert the rest of the tree if it make sense.

        // FIXME it's unclear what URI is expected here
        String id = URI.create("netconf:testDevice").toString();

        String inXml = deviceConfigAsXml("replace");

        return toCompositeStream(id, inXml);
    });/*w w w .  j a v  a  2  s . c om*/
    testNcSession = new TestEditNetconfSession();

    // building test data
    ResourceId interfacesId = RID_INTERFACES;
    DataNode interfaces = deviceConfigNode();
    SetRequest request = SetRequest.builder().replace(interfacesId, interfaces).build();

    // test start
    CompletableFuture<SetResponse> f = sut.setConfiguration(DID, request);
    SetResponse response = f.get(5, TimeUnit.MINUTES);

    assertEquals(Code.OK, response.code());
    assertEquals(request.subjects(), response.subjects());
}

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 -> {/*from w  ww  .  j  a 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:com.ikanow.aleph2.storm.harvest_technology.StormHarvestTechnologyModule.java

@Override
public CompletableFuture<BasicMessageBean> onUpdatedSource(DataBucketBean old_bucket, DataBucketBean new_bucket,
        boolean is_enabled, Optional<BucketDiffBean> diff, IHarvestContext context) {
    logger.info("received update source request");
    CompletableFuture<BasicMessageBean> stop_future = onDelete(old_bucket, context);
    try {//from  w w w .j  av a  2 s  . c om
        logger.info("waiting for stop to complete");
        stop_future.get(10L, TimeUnit.SECONDS);
    } catch (InterruptedException | ExecutionException | TimeoutException e) {
        //set failure in completable future
        logger.info("stop failed, returning that ", e);
        stop_future.complete(new BasicMessageBean(new Date(), false, null, "updateSource", null,
                ErrorUtils.getLongForm("{0}", e), null));
        return stop_future;
    }
    return onNewSource(new_bucket, context, is_enabled);
}

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

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

        @Override/*w w  w .j av  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<String> result = service.completable("flowCompletable");
    String reply = result.get(1, TimeUnit.SECONDS);
    assertEquals("SYNC_COMPLETABLE", reply);
    assertEquals(Thread.currentThread(), thread.get());
    assertNull(TestUtils.getPropertyValue(context.getBean("&completableNoAsync"), "asyncExecutor"));
}

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

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

        @Override/*from w  ww  . j  ava 2s  .com*/
        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<Message<?>> result = service.completableReturnsMessage("foo");
    Message<?> reply = result.get(1, TimeUnit.SECONDS);
    assertEquals("foo", reply.getPayload());
    assertThat(thread.get().getName(), startsWith("testExec-"));
    assertNotNull(TestUtils.getPropertyValue(context.getBean("&asyncCompletable"), "asyncExecutor"));
}