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:com.hortonworks.hbase.BufferedMutatorExample.java

@Override
public int run(String[] args) throws InterruptedException, ExecutionException, TimeoutException {

    /** a callback invoked when an asynchronous write fails. */
    final BufferedMutator.ExceptionListener listener = new BufferedMutator.ExceptionListener() {
        @Override// www  . j  ava 2 s .  com
        public void onException(RetriesExhaustedWithDetailsException e, BufferedMutator mutator) {
            for (int i = 0; i < e.getNumExceptions(); i++) {
                LOG.info("Failed to send put " + e.getRow(i) + ".");
            }
        }
    };
    BufferedMutatorParams params = new BufferedMutatorParams(TABLE).listener(listener);

    //
    // step 1: create a single Connection and a BufferedMutator, shared by all worker threads.
    //
    Configuration conf = new Configuration();
    try (final Connection conn = ConnectionFactory.createConnection(conf);
            final BufferedMutator mutator = conn.getBufferedMutator(params)) {

        conf.set("hbase.zookeeper.quorum", "sandbox.hortonworks.com");
        conf.set("hbase.zookeeper.property.clientPort", "2181");
        conf.set("zookeeper.znode.parent", "/hbase-unsecure");

        //        conf.set("hbase.zookeeper.quorum", "jetmaster2.jetnetname.artem.com,jetslave5.jetnetname.artem.com,jetslave1.jetnetname.artem.com");
        //        conf.set("hbase.zookeeper.property.clientPort", "2181");
        //        conf.set("zookeeper.znode.parent", "/hbase-unsecure");

        /** worker pool that operates on BufferedTable instances */
        final ExecutorService workerPool = Executors.newFixedThreadPool(POOL_SIZE);
        List<Future<Void>> futures = new ArrayList<>(TASK_COUNT);

        for (int i = 0; i < TASK_COUNT; i++) {
            futures.add(workerPool.submit(new Callable<Void>() {
                @Override
                public Void call() throws Exception {
                    //
                    // step 2: each worker sends edits to the shared BufferedMutator instance. They all use
                    // the same backing buffer, call-back "listener", and RPC executor pool.
                    //
                    Put p = new Put(Bytes.toBytes("someRow"));
                    p.addColumn(FAMILY, Bytes.toBytes("someQualifier"), Bytes.toBytes("some value"));
                    mutator.mutate(p);
                    // do work... maybe you want to call mutator.flush() after many edits to ensure any of
                    // this worker's edits are sent before exiting the Callable
                    return null;
                }
            }));
        }

        //
        // step 3: clean up the worker pool, shut down.
        //
        for (Future<Void> f : futures) {
            f.get(5, TimeUnit.MINUTES);
        }
        workerPool.shutdown();
    } catch (IOException e) {
        // exception while creating/destroying Connection or BufferedMutator
        LOG.info("exception while creating/destroying Connection or BufferedMutator", e);
    } // BufferedMutator.close() ensures all work is flushed. Could be the custom listener is
      // invoked from here.
    return 0;
}

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

/**
 * Merge two pdf files into one.//from   ww w.  ja v  a2 s.  com
 * @param file1
 * @param file2
 * @return
 * @throws InterruptedException
 * @throws java.util.concurrent.ExecutionException
 * @throws java.util.concurrent.TimeoutException
 * @throws java.io.IOException
 * @throws Exception
 */
@ApiOperation(value = "Merge two pdf files into one.")
@RequestMapping(value = "/merge", method = RequestMethod.POST, produces = "application/pdf")
public ResponseEntity<byte[]> mergePdfDocuments(
        @ApiParam(name = "file1", required = true) @RequestPart("file1") MultipartFile file1,
        @ApiParam(name = "file2", required = true) @RequestPart("file2") MultipartFile file2)
        throws InterruptedException, ExecutionException, TimeoutException, IOException, Exception {
    MergePdfJob job = new MergePdfJob();
    job.setFile1(new Document(file1));
    job.setFile2(new Document(file2));

    Future<Map> future = gateway.mergePdf(job);
    BinaryJob payload = (BinaryJob) future.get(defaultTimeout, TimeUnit.MILLISECONDS);

    byte[] fileBytes = payload.getPdfBytes();
    String contentType = "application/pdf";
    ResponseEntity<byte[]> result = ResponseEntityHelper.processFile(fileBytes, contentType, false);
    return result;
}

From source file:io.seldon.memcache.ExceptionSwallowingMemcachedClient.java

@Override
public Object get(String key) {
    Object myObj = null;//from   w ww. j  a  va  2  s .co  m
    Future<Object> f = super.asyncGet(hashKey(key));
    try {
        myObj = f.get(500, TimeUnit.MILLISECONDS);
    } catch (TimeoutException e) {
        logger.warn("Timeout exception in get ", e);
        f.cancel(false);
    } catch (InterruptedException e) {
        logger.error("Interrupted in get ", e);
        f.cancel(false);
    } catch (ExecutionException e) {
        logger.error("Execution exception in get ", e);
        f.cancel(false);
    }
    return myObj;
}

From source file:unitTests.v1_0.pdf.ConvertUrlToPDFTest.java

@Test
public void convertUrlToPdf() {
    try {//from   www. j a  va  2 s  .  co  m
        Url2PdfJob args = new Url2PdfJob();
        args.setPath("http://www.mikenimer.com");
        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 = pdfUrlGateway.convertUrlToPdf(args);
        Object result = resultFuture.get(defaultTimeout, TimeUnit.MILLISECONDS);

        Assert.assertTrue(result != null);
        Assert.assertTrue(((Url2PdfJob) result).getPdfBytes().length > 500000);
    } catch (Exception ex) {
        ex.printStackTrace();
        Assert.fail(ex.getMessage());
    }
}

From source file:com.dnastack.bob.service.parser.impl.JsonResponseResponseParser.java

@Asynchronous
@Override//from www .  jav  a 2s .co  m
public synchronized Future<Boolean> parseQueryResponse(Beacon b, Future<String> response) {
    Boolean res = null;
    try {
        res = parseUtils.parseYesNoFromJson(response.get(REQUEST_TIMEOUT, TimeUnit.SECONDS), "response");
    } catch (InterruptedException | ExecutionException | JSONException | TimeoutException ex) {
        // ignore
    }

    return new AsyncResult<>(res);
}

From source file:com.dnastack.bob.service.parser.impl.JsonExistsResponseParser.java

@Asynchronous
@Override/*from w ww .  j a va2s . c om*/
public synchronized Future<Boolean> parseQueryResponse(Beacon b, Future<String> response) {
    Boolean res = null;
    try {
        res = parseUtils.parseBooleanFromJson(response.get(REQUEST_TIMEOUT, TimeUnit.SECONDS), "exists");
    } catch (InterruptedException | ExecutionException | JSONException | TimeoutException ex) {
        // ignore
    }

    return new AsyncResult<>(res);
}

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

@Test
public void testMain() throws Exception {

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

    main.start();//  ww w  . j a  va2 s. co m

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

    InputStream in = getClass().getResourceAsStream("/TestFile.pdf");
    int fileSize = in.available();
    byte[] send = IOUtils.readFully(in, fileSize);

    Assert.assertEquals(fileSize, putServlet.lastContentLength);
    Assert.assertArrayEquals(send, putServlet.lastContent);
    Assert.assertTrue("Put filename doesn't match.",
            putServlet.requestedUri.startsWith("/inbox/unsorted/TestFile")
                    && putServlet.requestedUri.endsWith(".pdf"));
    Assert.assertNotEquals("/inbox/unsorted/TestFile", putServlet.requestedUri);
}

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

@Test
@Ignore/*from w ww  .jav  a  2  s.c  o  m*/
public void testSendFailedMail() throws Exception {

    Configuration.set(Configuration.ConfigurationKey.MailNotificationFailedRecipient, "mailuser@localhost.com");
    Configuration.set(Configuration.ConfigurationKey.MailSMTPHostname, "localhost:3026");

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

    main.start();

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

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

    Assert.assertEquals("An error during processing of an email occur!", messages[0].getSubject());
    Assert.assertEquals(Bundle.get(Bundle.BundleKey.MailNotificationFailedBody),
            messages[0].getContent().toString());
}

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

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

    Future<Map> future = textGateway.extractText(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:apiserver.services.pdf.ConvertHtmlToPdfGatewayTest.java

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

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

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

        Assert.assertTrue(result != null);
        Assert.assertTrue(((Html2PdfResult) result).getResult().length > 10000);
        PdfTestBase.saveFileToLocalDisk("test-htmlToPdf2.pdf", ((Html2PdfResult) result).getResult());
    } catch (Exception ex) {
        ex.printStackTrace();
        Assert.fail(ex.getMessage());
    }
}