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:com.vmware.loginsightapi.LogInsightClientMockTest.java

@Test
public void testAggregateQueryFailure() {
    List<FieldConstraint> constraints = new ConstraintBuilder().eq("vclap_caseid", "1423244")
            .gt("timestamp", "0").build();
    AggregateQuery aqb = (AggregateQuery) new AggregateQuery().limit(100).setConstraints(constraints);
    testAggregateQueryUrlAndHeaders(aqb);
    HttpResponse response = mock(HttpResponse.class);
    HttpEntity httpEntity = mock(HttpEntity.class);
    when(response.getEntity()).thenReturn(httpEntity);

    doAnswer(new Answer<Future<HttpResponse>>() {
        @Override//from w  w  w . j  a va2  s .  c o  m
        public Future<HttpResponse> answer(InvocationOnMock invocation) {
            @SuppressWarnings("unchecked")
            FutureCallback<HttpResponse> responseCallback = invocation.getArgumentAt(1, FutureCallback.class);
            responseCallback.completed(response);
            return null;
        }
    }).when(asyncHttpClient).execute(any(HttpUriRequest.class), any(FutureCallback.class));

    try {
        InputStream inputStream = IOUtils.toInputStream(SERVER_EXPECTED_AGGREGATE_QUERY_RESPONSE, "UTF-8");
        when(httpEntity.getContent()).thenThrow(IOException.class);
        CompletableFuture<AggregateResponse> responseFuture = client.aggregateQuery(aqb.toUrlString());
        responseFuture.get(0, TimeUnit.MILLISECONDS);
    } catch (Exception e) {
        logger.error("Exception raised " + ExceptionUtils.getStackTrace(e));
        Assert.assertTrue(e.getCause() instanceof LogInsightApiException);
        Assert.assertEquals(e.getCause().getMessage(), "Unable to process the query response");
    }
}

From source file:com.vmware.loginsightapi.LogInsightClientMockTest.java

@Test
public void testAggregateQueryRuntimeFailure() {
    List<FieldConstraint> constraints = new ConstraintBuilder().eq("vclap_caseid", "1423244")
            .gt("timestamp", "0").build();
    AggregateQuery aqb = (AggregateQuery) new AggregateQuery().limit(100).setConstraints(constraints);
    testAggregateQueryUrlAndHeaders(aqb);
    HttpResponse response = mock(HttpResponse.class);
    HttpEntity httpEntity = mock(HttpEntity.class);
    when(response.getEntity()).thenReturn(httpEntity);

    doAnswer(new Answer<Future<HttpResponse>>() {
        @Override//from   w  w w.ja v a  2  s. co  m
        public Future<HttpResponse> answer(InvocationOnMock invocation) {
            @SuppressWarnings("unchecked")
            FutureCallback<HttpResponse> responseCallback = invocation.getArgumentAt(1, FutureCallback.class);
            responseCallback.completed(response);
            return null;
        }
    }).when(asyncHttpClient).execute(any(HttpUriRequest.class), any(FutureCallback.class));

    try {
        InputStream inputStream = IOUtils.toInputStream(SERVER_EXPECTED_AGGREGATE_QUERY_RESPONSE, "UTF-8");
        when(httpEntity.getContent()).thenThrow(Exception.class);
        CompletableFuture<AggregateResponse> responseFuture = client.aggregateQuery(aqb.toUrlString());
        responseFuture.get(0, TimeUnit.MILLISECONDS);
    } catch (Exception e) {
        logger.error("Exception raised " + ExceptionUtils.getStackTrace(e));
        Assert.assertTrue(e.getCause() instanceof LogInsightApiException);
        Assert.assertEquals(e.getCause().getMessage(), "Message query failed");
    }
}

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

@Override
public String browseEventLogRecords(int skip, int limit) {
    final CompletableFuture<GetEvents.Response> future = new CompletableFuture<>();
    vertx.eventBus().send(EventBusAddress.eventBusAddress(EventLogRepository.VERTICLE_ID, GetEvents.class),
            GetEvents.Request.newBuilder().setSkip(skip).setLimit(limit).build(),
            new DeliveryOptions().setSendTimeout(2000L), responseHandler(future, GetEvents.Response.class));
    try {//from w w w  .  j  a  v a2s. c o m
        final GetEvents.Response response = future.get(2, TimeUnit.SECONDS);
        return JsonUtils.toVertxJsonObject(Json.createObjectBuilder().add("count", response.getEventsCount())
                .add("records", ProtobufUtils.protobuMessageToJson(response)).build()).encodePrettily();
    } catch (final InterruptedException | ExecutionException | TimeoutException ex) {
        log.logp(SEVERE, getClass().getName(), "createEventLogRecord", "failed", ex);
        throw new RuntimeException("Failed to create event log record : " + ex.getMessage());
    }
}

From source file:com.vmware.loginsightapi.LogInsightClientMockTest.java

@Test
public void testMessageQueryFailure() {
    MessageQuery mqb = getMessageQueryForTest();
    testMessageQueryUrlAndHeaders(mqb);// w w w  .j a  v  a2  s . c  o m
    HttpResponse response = mock(HttpResponse.class);
    HttpEntity httpEntity = mock(HttpEntity.class);
    when(response.getEntity()).thenReturn(httpEntity);

    doAnswer(new Answer<Future<HttpResponse>>() {
        @Override
        public Future<HttpResponse> answer(InvocationOnMock invocation) {
            @SuppressWarnings("unchecked")
            FutureCallback<HttpResponse> responseCallback = invocation.getArgumentAt(1, FutureCallback.class);
            responseCallback.completed(response);
            return null;
        }
    }).when(asyncHttpClient).execute(any(HttpUriRequest.class), any(FutureCallback.class));

    try {
        when(httpEntity.getContent()).thenThrow(IOException.class);
        CompletableFuture<MessageQueryResponse> responseFuture = client.messageQuery(mqb.toUrlString());
        MessageQueryResponse messages = responseFuture.get(0, TimeUnit.MILLISECONDS);
    } catch (Exception e) {
        logger.error("Exception raised " + ExceptionUtils.getStackTrace(e));
        Assert.assertTrue(e.getCause() instanceof IOException);
    }
}

From source file:com.vmware.loginsightapi.LogInsightClientMockTest.java

@Test
public void testMessageQueryRuntimeFailure() {
    MessageQuery mqb = getMessageQueryForTest();
    testMessageQueryUrlAndHeaders(mqb);/*from w w w .ja v a2  s.  com*/
    HttpResponse response = mock(HttpResponse.class);
    HttpEntity httpEntity = mock(HttpEntity.class);
    when(response.getEntity()).thenReturn(httpEntity);

    doAnswer(new Answer<Future<HttpResponse>>() {
        @Override
        public Future<HttpResponse> answer(InvocationOnMock invocation) {
            @SuppressWarnings("unchecked")
            FutureCallback<HttpResponse> responseCallback = invocation.getArgumentAt(1, FutureCallback.class);
            responseCallback.completed(response);
            return null;
        }
    }).when(asyncHttpClient).execute(any(HttpUriRequest.class), any(FutureCallback.class));

    try {
        when(httpEntity.getContent()).thenThrow(Exception.class);
        CompletableFuture<MessageQueryResponse> responseFuture = client.messageQuery(mqb.toUrlString());
        MessageQueryResponse messages = responseFuture.get(0, TimeUnit.MILLISECONDS);
    } catch (ExecutionException e) {
        logger.error("Exception raised " + ExceptionUtils.getStackTrace(e));
        Assert.assertTrue(e.getCause() instanceof LogInsightApiException);
        Assert.assertEquals(e.getCause().getMessage(), "Message query failed");
    } catch (Exception e1) {
        Assert.assertTrue(false);
    }
}

From source file:com.vmware.loginsightapi.LogInsightClientMockTest.java

@Test
public void testAggregateQuery() {
    List<FieldConstraint> constraints = new ConstraintBuilder().eq("vclap_caseid", "1423244")
            .gt("timestamp", "0").build();
    AggregateQuery aqb = (AggregateQuery) new AggregateQuery().limit(100).setConstraints(constraints);
    testAggregateQueryUrlAndHeaders(aqb);
    HttpResponse response = mock(HttpResponse.class);
    HttpEntity httpEntity = mock(HttpEntity.class);
    when(response.getEntity()).thenReturn(httpEntity);

    doAnswer(new Answer<Future<HttpResponse>>() {
        @Override/*from  w  ww  .j  a  v  a2s. c  o  m*/
        public Future<HttpResponse> answer(InvocationOnMock invocation) {
            @SuppressWarnings("unchecked")
            FutureCallback<HttpResponse> responseCallback = invocation.getArgumentAt(1, FutureCallback.class);
            responseCallback.completed(response);
            return null;
        }
    }).when(asyncHttpClient).execute(any(HttpUriRequest.class), any(FutureCallback.class));

    try {
        InputStream inputStream = IOUtils.toInputStream(SERVER_EXPECTED_AGGREGATE_QUERY_RESPONSE, "UTF-8");
        when(httpEntity.getContent()).thenReturn(inputStream);
        CompletableFuture<AggregateResponse> responseFuture = client.aggregateQuery(aqb.toUrlString());

        AggregateResponse message = responseFuture.get(0, TimeUnit.MILLISECONDS);

        Assert.assertTrue("Invalid number of bins", message.getBins().size() <= 100);
        Assert.assertTrue("Invalid duration in the response", message.getDuration() > 0);
    } catch (Exception e) {
        logger.error("Exception raised " + ExceptionUtils.getStackTrace(e));
        Assert.assertTrue(false);
    }
}

From source file:com.vmware.loginsightapi.LogInsightClientMockTest.java

@Test
public void testMessageQuery() {
    MessageQuery mqb = getMessageQueryForTest();
    testMessageQueryUrlAndHeaders(mqb);/*www. ja va 2 s  . c o m*/
    HttpResponse response = mock(HttpResponse.class);
    HttpEntity httpEntity = mock(HttpEntity.class);
    when(response.getEntity()).thenReturn(httpEntity);

    doAnswer(new Answer<Future<HttpResponse>>() {
        @Override
        public Future<HttpResponse> answer(InvocationOnMock invocation) {
            @SuppressWarnings("unchecked")
            FutureCallback<HttpResponse> responseCallback = invocation.getArgumentAt(1, FutureCallback.class);
            responseCallback.completed(response);
            return null;
        }
    }).when(asyncHttpClient).execute(any(HttpUriRequest.class), any(FutureCallback.class));

    try {
        InputStream inputStream = IOUtils.toInputStream(SERVER_EXPECTED_QUERY_RESPONSE, "UTF-8");
        when(httpEntity.getContent()).thenReturn(inputStream);
        CompletableFuture<MessageQueryResponse> responseFuture = client.messageQuery(mqb.toUrlString());

        MessageQueryResponse messages = responseFuture.get(0, TimeUnit.MILLISECONDS);
        Assert.assertTrue("Invalid number of messages", messages.getEvents().size() <= 100);
    } catch (Exception e) {
        logger.error("Exception raised " + ExceptionUtils.getStackTrace(e));
        Assert.assertTrue(false);
    }
}

From source file:org.apache.tinkerpop.gremlin.server.GremlinServerIntegrateTest.java

@SuppressWarnings("ThrowableResultOfMethodCallIgnored")
@Test//ww w  .  j a  va  2  s .  c  o m
public void shouldBlockRequestWhenTooBig() throws Exception {
    final Cluster cluster = Cluster.open();
    final Client client = cluster.connect();

    try {
        final String fatty = IntStream.range(0, 1024).mapToObj(String::valueOf).collect(Collectors.joining());
        final CompletableFuture<ResultSet> result = client.submitAsync("'" + fatty + "';'test'");
        final ResultSet resultSet = result.get(10000, TimeUnit.MILLISECONDS);
        resultSet.all().get(10000, TimeUnit.MILLISECONDS);
        fail("Should throw an exception.");
    } catch (TimeoutException te) {
        // the request should not have timed-out - the connection should have been reset, but it seems that
        // timeout seems to occur as well on some systems (it's not clear why).  however, the nature of this
        // test is to ensure that the script isn't processed if it exceeds a certain size, so in this sense
        // it seems ok to pass in this case.
    } catch (Exception re) {
        final Throwable root = ExceptionUtils.getRootCause(re);
        assertEquals("Connection reset by peer", root.getMessage());

        // validate that we can still send messages to the server
        assertEquals(2, client.submit("1+1").all().join().get(0).getInt());
    } finally {
        cluster.close();
    }
}

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

@Override
public String createEventLogRecord(final String event) {
    Preconditions.checkArgument(isNotBlank(event));
    final CompletableFuture<CreateEvent.Response> createEventFuture = new CompletableFuture<>();
    vertx.eventBus().send(EventBusAddress.eventBusAddress(EventLogRepository.VERTICLE_ID, CreateEvent.class),
            CreateEvent.Request.newBuilder().setEvent(event).build(),
            new DeliveryOptions().setSendTimeout(2000L),
            responseHandler(createEventFuture, CreateEvent.Response.class));
    try {//from ww w . ja v a 2  s  .  c om
        final CreateEvent.Response createEventResponse = createEventFuture.get(2, TimeUnit.SECONDS);
        return ProtobufUtils.protobuMessageToJson(createEventResponse.getId()).toString();
    } catch (final InterruptedException | ExecutionException | TimeoutException ex) {
        log.logp(SEVERE, getClass().getName(), "createEventLogRecord", "failed", ex);
        throw new RuntimeException("Failed to create event log record : " + ex.getMessage());
    }
}

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

/**
 * Test of startUp method, of class OrientDBVerticle.
 *//* www .  j a  va2  s.c  o m*/
@Test
public void testVerticle() throws Exception {
    log.info("test_eventBus_GetVerticleDeployments");
    final Vertx vertx = vertxService.getVertx();

    final RunRightFastVerticleId verticleManagerId = RunRightFastVerticleManager.VERTICLE_ID;
    final CompletableFuture<GetVerticleDeployments.Response> getVerticleDeploymentsFuture = new CompletableFuture<>();
    final long timeout = 60000L;
    vertx.eventBus().send(EventBusAddress.eventBusAddress(verticleManagerId, "get-verticle-deployments"),
            GetVerticleDeployments.Request.newBuilder().build(), new DeliveryOptions().setSendTimeout(timeout),
            responseHandler(getVerticleDeploymentsFuture, GetVerticleDeployments.Response.class));
    final GetVerticleDeployments.Response getVerticleDeploymentsResponse = getVerticleDeploymentsFuture
            .get(timeout, TimeUnit.MILLISECONDS);
    final int totalHealthCheckCount = getVerticleDeploymentsResponse.getDeploymentsList().stream()
            .collect(Collectors.summingInt(VerticleDeployment::getHealthChecksCount));

    final CompletableFuture<RunVerticleHealthChecks.Response> future = new CompletableFuture<>();
    vertx.eventBus().send(EventBusAddress.eventBusAddress(verticleManagerId, "run-verticle-healthchecks"),
            RunVerticleHealthChecks.Request.newBuilder().build(),
            addRunRightFastHeaders(new DeliveryOptions().setSendTimeout(timeout)),
            responseHandler(future, RunVerticleHealthChecks.Response.class));

    final RunVerticleHealthChecks.Response response = future.get(timeout, TimeUnit.MILLISECONDS);
    assertThat(response.getResultsCount(), is(totalHealthCheckCount));

}