Example usage for java.util.concurrent Future get

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

Introduction

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

Prototype

V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException;

Source Link

Document

Waits if necessary for at most the given time for the computation to complete, and then retrieves its result, if available.

Usage

From source file:pdf.ConvertHtmlToPDFTest.java

@Test
public void convertHtmlToPdf2() {
    try {/*from w  w  w  .  ja  v  a2s.c  o  m*/
        Html2PdfJob args = new Html2PdfJob();
        args.setHtml("<b>Hello World</b>");
        args.setHeaderHtml("header");
        args.setFooterHtml("footer");

        Future<Map> resultFuture = pdfHtmlGateway.convertHtmlToPdf(args);
        Object result = resultFuture.get(defaultTimeout, TimeUnit.MILLISECONDS);

        Assert.assertTrue(result != null);
        Assert.assertEquals(40432, ((Html2PdfJob) result).getPdfBytes().length);
    } catch (Exception ex) {
        ex.printStackTrace();
        Assert.fail(ex.getMessage());
    }
}

From source file:de.elomagic.mag.WebDAVTest.java

@Ignore
@Test/*from   www  .j  a v  a 2  s  .  c  o  m*/
public void testSendSuccessMail() throws Exception {

    Configuration.set(Configuration.ConfigurationKey.MailNotificationSuccessRecipient,
            "mailuser@localhost.com");

    greeUser.deliver(createMimeMessage("TestFile.pdf"));

    main.start();

    Future future = createPutServletFuture(putServlet);
    future.get(5, TimeUnit.SECONDS);

    Thread.sleep(2000);

    MimeMessage[] messages = greenMail.getReceivedMessages();
    Assert.assertEquals(1, messages.length);

    Assert.assertEquals("An attachment was successful uploaded.", messages[0].getSubject());
    Assert.assertEquals(Bundle.get(Bundle.BundleKey.MailNotificationSuccessBody),
            messages[0].getContent().toString().trim());
}

From source file:apiserver.services.pdf.controllers.ExtractController.java

@ApiOperation(value = "TODO")
@RequestMapping(value = "/extract/image", method = RequestMethod.POST, produces = "application/pdf")
public ResponseEntity<Object> extractImageFromPdf(
        @ApiParam(name = "file", required = true) @RequestPart("file") MultipartFile file)
        throws InterruptedException, ExecutionException, TimeoutException, IOException, Exception {
    ExtractImageJob job = new ExtractImageJob();
    job.setFile(new Document(file));

    Future<Map> future = imageGateway.extractImage(job);
    ObjectJob payload = (ObjectJob) future.get(defaultTimeout, TimeUnit.MILLISECONDS);

    Object result = payload.getResult();
    String contentType = MimeType.pdf.contentType;
    return ResponseEntityHelper.processObject(result);
}

From source file:com.teradata.benchto.driver.jdbc.ConnectionPoolTest.java

private void openGivenConnectionsAmountSimultaneously(String dataSourceName, int connectionsCount)
        throws SQLException, InterruptedException, TimeoutException {
    ExecutorService executorService = newFixedThreadPool(connectionsCount);
    ExecutorCompletionService<?> completionService = new ExecutorCompletionService(executorService);
    CountDownLatch countDownLatch = new CountDownLatch(connectionsCount);
    DataSource dataSource = applicationContext.getBean(dataSourceName, DataSource.class);

    range(0, connectionsCount).mapToObj(i -> createQueryRunnable(dataSource, countDownLatch))
            .forEach(completionService::submit);

    try {/*from   w w w . j  av a 2s.  c o  m*/
        for (int i = 0; i < connectionsCount; i++) {
            try {
                Future<?> future = completionService.take();
                future.get(1, MINUTES);
            } catch (ExecutionException e) {
                rethrowException(e.getCause());
            }
        }
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
    } finally {
        executorService.shutdownNow();
        executorService.awaitTermination(1, MINUTES);
    }
}

From source file:amqp.spring.camel.component.ContrivedLoadTest.java

@Test
public void testAsynchronous() throws Exception {
    final int messageCount = 1000;
    int received = 0;
    List<Future<String>> futures = new ArrayList<Future<String>>();

    long startTime = System.currentTimeMillis();
    for (int i = 0; i < messageCount; ++i)
        futures.add(this.template.asyncRequestBody("direct:sync", "HELLO WORLD", String.class));
    LOG.info("Time to submit asynchronous messages: {}", (System.currentTimeMillis() - startTime) / 1000.0f);

    startTime = System.currentTimeMillis();
    for (Future<String> future : futures) {
        String response = future.get(10000, TimeUnit.MILLISECONDS);
        if ("RESPONSE".equals(response))
            ++received;//from  w  w  w  .  j av  a 2 s  .co m
    }
    float elapsedTime = (System.currentTimeMillis() - startTime) / 1000.0f;
    int maxPoolSize = this.camelContext.getExecutorServiceManager().getDefaultThreadPoolProfile()
            .getMaxPoolSize();
    LOG.info("Time to receive asynchronous messages: {}", elapsedTime);

    Assert.assertEquals(messageCount, received);
    //Assuming 1 second delay per message, elapsed time shouldn't exceed the number of messages sent 
    //dividied by the number of messages that can be simultaneously consumed.
    Assert.assertTrue(
            String.format("Possible performance issue: %d messages took %f seconds with %d consumers",
                    messageCount, elapsedTime, maxPoolSize),
            elapsedTime < (messageCount / (double) maxPoolSize) + 1);
}

From source file:pdf.ConvertHtmlToPDFTest.java

@Test
public void convertHtmlToPdf() {
    try {/*from  w ww. j  av a  2  s . c o m*/
        Html2PdfJob args = new Html2PdfJob();
        args.setHtml("<b>Hello World</b>");
        args.setFontEmbed(true);
        args.setMarginBottom(2);
        args.setMarginTop(2);
        args.setMarginLeft(2);
        args.setMarginRight(2);

        CFDocumentJob.Permission[] permissions = new CFDocumentJob.Permission[] {
                CFDocumentJob.Permission.AllowCopy, CFDocumentJob.Permission.AllowPrinting,
                CFDocumentJob.Permission.AllowScreenReaders };
        args.setPermissions(permissions);

        Future<Map> resultFuture = pdfHtmlGateway.convertHtmlToPdf(args);
        Object result = resultFuture.get(defaultTimeout, TimeUnit.MILLISECONDS);

        Assert.assertTrue(result != null);
        Assert.assertEquals(38639, ((Html2PdfJob) result).getPdfBytes().length);
    } catch (Exception ex) {
        ex.printStackTrace();
        Assert.fail(ex.getMessage());
    }
}

From source file:amqp.spring.camel.component.ContrivedLoadTest.java

@Test
public void testSynchronous() throws Exception {
    final int messageCount = 1000;
    int received = 0;
    ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor(messageCount);
    List<Future<String>> futures = new ArrayList<Future<String>>();

    long startTime = System.currentTimeMillis();
    for (int i = 0; i < messageCount; ++i)
        futures.add(executorService.submit(new SynchronousRequestor(this.template)));
    LOG.info("Time to submit synchronous messages: {}", (System.currentTimeMillis() - startTime) / 1000.0f);

    startTime = System.currentTimeMillis();
    for (Future<String> future : futures) {
        String response = future.get(10000, TimeUnit.MILLISECONDS);
        if ("RESPONSE".equals(response))
            ++received;/*from w ww  .  ja v  a 2s  .  c  o  m*/
    }
    float elapsedTime = (System.currentTimeMillis() - startTime) / 1000.0f;
    int maxPoolSize = this.camelContext.getExecutorServiceManager().getDefaultThreadPoolProfile()
            .getMaxPoolSize();
    LOG.info("Time to receive synchronous messages: {}", elapsedTime);

    Assert.assertEquals(messageCount, received);
    //Assuming 1 second delay per message, elapsed time shouldn't exceed the number of messages sent 
    //dividied by the number of messages that can be simultaneously consumed.
    Assert.assertTrue(
            String.format("Possible performance issue: %d messages took %f seconds with %d consumers",
                    messageCount, elapsedTime, maxPoolSize),
            elapsedTime < (messageCount / (double) maxPoolSize) + 1);
}

From source file:io.hops.resolvingcache.PathMemcache.java

@Override
protected int[] getInternal(final MemcachedClient mc, String path) throws IOException {
    Object ce = null;// w w  w  . j a  va  2s  .c om
    Future<Object> f = mc.asyncGet(getKey(path));
    try {
        ce = f.get(1, TimeUnit.SECONDS);
    } catch (Exception ex) {
        LOG.error(ex);
        f.cancel(true);
    }
    if (ce != null && ce instanceof CacheEntry) {
        return ((CacheEntry) ce).getInodeIds();
    }
    return null;
}

From source file:com.cognifide.aet.job.common.collectors.source.SourceCollector.java

private byte[] getContent() throws ProcessingException {
    byte[] content;
    ExecutorService executor = Executors.newCachedThreadPool();
    Callable<Object> task = new Callable<Object>() {
        @Override/*from  w w w  . j  a  v a 2 s.c o  m*/
        public Object call() throws IOException {
            return httpRequestBuilder.executeRequest().getContent();
        }
    };
    Future<Object> future = executor.submit(task);
    try {
        content = (byte[]) future.get(timeoutValue, TimeUnit.MILLISECONDS);
    } catch (TimeoutException | InterruptedException | ExecutionException e) {
        throw new ProcessingException(e.getMessage(), e);
    } finally {
        future.cancel(true);
    }
    return content;
}

From source file:br.com.caelum.vraptor.ioc.spring.SpringProviderRegisteringComponentsTest.java

@Override
protected <T> T executeInsideRequest(final WhatToDo<T> execution) {
    Callable<T> task = new Callable<T>() {
        public T call() throws Exception {
            T result = null;/*w  w w . ja  v a2s. co  m*/
            HttpSessionMock session = new HttpSessionMock(context, "session" + ++counter);
            HttpServletRequestMock httpRequest = new HttpServletRequestMock(session,
                    mock(MutableRequest.class, "request" + counter));
            MutableResponse response = mock(MutableResponse.class, "response" + counter);

            RequestInfo request = new RequestInfo(context, null, httpRequest, response);
            VRaptorRequestHolder.setRequestForCurrentThread(request);

            RequestContextListener contextListener = new RequestContextListener();
            contextListener.requestInitialized(new ServletRequestEvent(context, httpRequest));
            result = execution.execute(request, counter);
            contextListener.requestDestroyed(new ServletRequestEvent(context, httpRequest));

            VRaptorRequestHolder.resetRequestForCurrentThread();
            return result;
        }
    };

    Future<T> future = Executors.newSingleThreadExecutor().submit(task);

    try {
        return future.get(60, TimeUnit.SECONDS);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}