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.opopov.cloud.image.service.ImageStitchingServiceImpl.java

@Override
public DeferredResult<ResponseEntity<?>> getStitchedImage(@RequestBody ImageStitchingConfiguration config) {

    validator.validateConfig(config);/*ww  w  .j a  va  2  s. co m*/

    List<ListenableFuture<ResponseEntity<byte[]>>> futures = config.getUrlList().stream()
            .map(url -> remoteResource.getForEntity(url, byte[].class)).collect(Collectors.toList());

    //wrap the listenable futures into the completable futures
    //writing loop in pre-8 style, since it would be more concise compared to stream api in this case
    CompletableFuture[] imageFutures = new CompletableFuture[futures.size()];
    int taskIndex = 0;
    IndexMap indexMap = new IndexMap(config.getRowCount() * config.getColumnCount());
    for (ListenableFuture<ResponseEntity<byte[]>> f : futures) {
        imageFutures[taskIndex] = imageDataFromResponse(taskIndex, indexMap, utils.fromListenableFuture(f));
        taskIndex++;
    }

    CompletableFuture<Void> allDownloadedAndDecompressed = CompletableFuture.allOf(imageFutures);

    //Synchronous part - start - writing decompressed bytes to the large image
    final int DOWNLOAD_AND_DECOMPRESS_TIMEOUT = 30; //30 seconds for each of the individual tasks
    DeferredResult<ResponseEntity<?>> response = new DeferredResult<>();
    boolean allSuccessful = false;
    byte[] imageBytes = null;
    try {
        Void finishResult = allDownloadedAndDecompressed.get(DOWNLOAD_AND_DECOMPRESS_TIMEOUT, TimeUnit.SECONDS);

        imageBytes = combineImagesIntoStitchedImage(config, indexMap);

        HttpHeaders headers = new HttpHeaders();
        headers.setCacheControl(CacheControl.noCache().getHeaderValue());
        headers.setContentType(MediaType.IMAGE_JPEG);
        allSuccessful = true;
    } catch (InterruptedException | ExecutionException e) {
        // basically either download or decompression of the source image failed
        // just skip it then, we have no image to show
        response.setErrorResult(
                new SourceImageLoadException("Unable to load and decode one or more source images", e));
    } catch (TimeoutException e) {
        //send timeout response, via ImageLoadTimeoutException
        response.setErrorResult(new ImageLoadTimeoutException(
                String.format("Some of the images were not loaded and decoded before timeout of %d seconds",
                        DOWNLOAD_AND_DECOMPRESS_TIMEOUT),
                e

        ));
    } catch (IOException e) {
        response.setErrorResult(new ImageWriteException("Error writing image into output buffer", e));
    }

    //Synchronous part - end

    if (!allSuccessful) {
        //shoud not get here, some unknown error
        response.setErrorResult(
                new ImageLoadTimeoutException("Unknown error", new RuntimeException("Something went wrong")

                ));

        return response;
    }

    ResponseEntity<?> successResult = ResponseEntity.ok(imageBytes);
    response.setResult(successResult);

    return response;

}

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

@Test
public void testIngestionCancelled() {
    Message msg1 = new Message("Testing the ingestion");
    msg1.addField("vclap_test_id", "11111");
    IngestionRequest request = new IngestionRequest();
    request.addMessage(msg1);//from   w  w w  .j a v a 2  s. c o m
    testIngestionQueryUrlAndHeaders(request);

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

    try {
        CompletableFuture<IngestionResponse> responseFuture = client.ingest(request);
        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(), "Ingestion cancelled");
    } catch (Exception e) {
        Assert.assertTrue(false);
    }
}

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

@Test
public void testIngestionFailedInCallback() {
    Message msg1 = new Message("Testing the ingestion");
    msg1.addField("vclap_test_id", "11111");
    IngestionRequest request = new IngestionRequest();
    request.addMessage(msg1);//from w  w  w  .  j  a  v  a 2 s .  co  m
    testIngestionQueryUrlAndHeaders(request);

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

    try {
        CompletableFuture<IngestionResponse> responseFuture = client.ingest(request);
        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(), "Ingestion failed");
    } catch (Exception e) {
        Assert.assertTrue(false);
    }
}

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

@Test
public void testIngestionRuntimeFailure() {
    Message msg1 = new Message("Testing the ingestion");
    msg1.addField("vclap_test_id", "11111");
    IngestionRequest request = new IngestionRequest();
    request.addMessage(msg1);//from   ww w  .  j a va  2 s.  c o  m
    testIngestionQueryUrlAndHeaders(request);

    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) {
            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<IngestionResponse> responseFuture = client.ingest(request);
        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(), "Ingestion failed");
    } catch (Exception e1) {
        Assert.assertTrue(false);
    }
}

From source file:org.eclipse.hono.service.AbstractApplication.java

/**
 * Starts up this application.//  w  ww .  jav a2 s.co  m
 * <p>
 * The start up process entails the following steps:
 * <ol>
 * <li>invoke <em>deployRequiredVerticles</em> to deploy the verticle(s) implementing the service's functionality</li>
 * <li>invoke <em>deployServiceVerticles</em> to deploy the protocol specific service endpoints</li>
 * <li>invoke <em>postRegisterServiceVerticles</em> to perform any additional post deployment steps</li>
 * <li>start the health check server</li>
 * </ol>
 * 
 * @param args The command line arguments provided to the application.
 */
public void run(final ApplicationArguments args) {

    if (vertx == null) {
        throw new IllegalStateException("no Vert.x instance has been configured");
    } else if (serviceFactories.isEmpty()) {
        throw new IllegalStateException("no service factory has been configured");
    }

    healthCheckServer = new HealthCheckServer(vertx, config);

    final Future<Void> future = deployRequiredVerticles(config.getMaxInstances())
            .compose(s -> deployServiceVerticles()).compose(s -> postRegisterServiceVerticles())
            .compose(s -> healthCheckServer.start());

    final CompletableFuture<Void> started = new CompletableFuture<>();
    future.setHandler(result -> {
        if (result.failed()) {
            started.completeExceptionally(result.cause());
        } else {
            started.complete(null);
        }
    });

    final int startupTimeoutSeconds = config.getStartupTimeout();

    try {
        log.debug("Waiting for {} seconds to start up", startupTimeoutSeconds);
        started.get(startupTimeoutSeconds, TimeUnit.SECONDS);
    } catch (TimeoutException e) {
        log.error("startup timed out after {} seconds, shutting down ...", startupTimeoutSeconds);
        shutdown();
    } catch (InterruptedException e) {
        log.error("startup process has been interrupted, shutting down ...");
        Thread.currentThread().interrupt();
        shutdown();
    } catch (ExecutionException e) {
        log.error("exception occurred during startup, shutting down ...", e);
        shutdown();
    }
}

From source file:org.trustedanalytics.platformoperations.service.PlatformOperationsScheduler.java

private Runnable platformSummary() {
    return () -> {

        if (flag.compareAndSet(false, true)) {
            try {
                LOGGER.info("Trigger Platform Summary");

                final CompletableFuture<ComponentSummary> componentSummary = CompletableFuture
                        .supplyAsync(new ComponentDiscoverTask(nats), executor)
                        .thenApply(messages -> new ComponentMetricsTask("DEA", messages).get())
                        .thenApply(ComponentSummary::new);

                final CompletableFuture<ControllerSummary> controllerSummary = CompletableFuture
                        .supplyAsync(new ControllerMetricsTask(client), executor);

                CompletableFuture.allOf(componentSummary, controllerSummary).get(10, TimeUnit.MINUTES);

                repository.save(new PlatformSummary(componentSummary.get(1, TimeUnit.MINUTES),
                        controllerSummary.get(1, TimeUnit.MINUTES)));
            } catch (TimeoutException | ExecutionException | InterruptedException ex) {
                LOGGER.error("Exception during fetching metrics: {}" + ex);
            } finally {
                flag.set(false);//  w  w w  .  j a  va 2 s  .  c o  m
            }
        } else {
            LOGGER.info("Request skipped, task already submitted!");
        }
    };
}

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

@Test
public void testMessageQueryCancelled() {
    MessageQuery mqb = getMessageQueryForTest();
    testMessageQueryUrlAndHeaders(mqb);//from   w w  w . ja v a 2 s .c o m

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

    try {
        CompletableFuture<MessageQueryResponse> responseFuture = client.messageQuery(mqb.toUrlString());
        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(), "Cancelled message Query");
    } catch (Exception e) {
        Assert.assertTrue(false);
    }
}

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

@Test
public void testMessageQueryFailedInCallback() {
    MessageQuery mqb = getMessageQueryForTest();
    testMessageQueryUrlAndHeaders(mqb);//from   w w  w. j ava  2  s.  c  om

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

    try {
        CompletableFuture<MessageQueryResponse> responseFuture = client.messageQuery(mqb.toUrlString());
        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(), "Failed message Query");
    } catch (Exception e) {
        Assert.assertTrue(false);
    }
}

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

@Test
public void testAggregateQueryCancelled() {
    List<FieldConstraint> constraints = new ConstraintBuilder().eq("vclap_caseid", "1423244")
            .gt("timestamp", "0").build();
    AggregateQuery aqb = (AggregateQuery) new AggregateQuery().limit(100).setConstraints(constraints);
    testAggregateQueryUrlAndHeaders(aqb);

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

    try {
        CompletableFuture<AggregateResponse> responseFuture = client.aggregateQuery(aqb.toUrlString());
        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(), "Cancelled message Query");
    } catch (Exception e) {
        Assert.assertTrue(false);
    }
}

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

@Test
public void testAggregateQueryFailedInCallback() {
    List<FieldConstraint> constraints = new ConstraintBuilder().eq("vclap_caseid", "1423244")
            .gt("timestamp", "0").build();
    AggregateQuery aqb = (AggregateQuery) new AggregateQuery().limit(100).setConstraints(constraints);
    testAggregateQueryUrlAndHeaders(aqb);

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

    try {
        CompletableFuture<AggregateResponse> responseFuture = client.aggregateQuery(aqb.toUrlString());
        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(), "Failed message Query");
    } catch (Exception e) {
        Assert.assertTrue(false);
    }
}