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() throws InterruptedException, ExecutionException;

Source Link

Document

Waits if necessary for the computation to complete, and then retrieves its result.

Usage

From source file:com.aerofs.baseline.json.TestJSONHandling.java

@Test
public void shouldSuccessfullyProcessJson() throws ExecutionException, InterruptedException, IOException {
    JsonObject value = new JsonObject("unhappy", "allen");

    String serialized = mapper.writeValueAsString(value);
    ByteArrayInputStream contentInputStream = new ByteArrayInputStream(serialized.getBytes(Charsets.US_ASCII));
    BasicHttpEntity entity = new BasicHttpEntity();
    entity.setContent(contentInputStream);

    HttpPost post = new HttpPost(ServiceConfiguration.SERVICE_URL + "/consumer");
    post.setHeader(new BasicHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON));
    post.setEntity(entity);/*  www. jav  a 2s  .  c o  m*/

    Future<HttpResponse> future = client.getClient().execute(post, null);
    HttpResponse response = future.get();
    assertThat(response.getStatusLine().getStatusCode(), equalTo(HttpStatus.SC_OK));
    assertThat(HttpUtils.readStreamToString(response.getEntity().getContent()),
            equalTo(getResponseValue(value)));
}

From source file:com.asakusafw.runtime.util.cache.HadoopFileCacheRepositoryTest.java

/**
 * Conflict cache creation.// w  ww.  j  a  v  a 2  s . c o m
 * @throws Exception if failed
 */
@Test
public void conflict() throws Exception {
    File source = folder.newFile();
    byte[] bytes = new byte[1024 * 1024];
    try (OutputStream output = new FileOutputStream(source)) {
        for (int i = 0, n = 50; i < n; i++) {
            output.write(bytes);
        }
    }

    Path path = path(source);
    File cacheRepo = folder.newFolder();
    Configuration configuration = new ConfigurationProvider().newInstance();
    LockProvider<Path> locks = new LocalFileLockProvider<>(folder.newFolder());
    RetryStrategy retrier = new ConstantRetryStrategy(30, 100, 200);
    FileCacheRepository cache = new HadoopFileCacheRepository(configuration, path(cacheRepo), locks, retrier);

    List<Future<Path>> futures = new ArrayList<>();
    int count = 10;
    CountDownLatch latch = new CountDownLatch(count);
    ExecutorService executor = Executors.newFixedThreadPool(count);
    try {
        for (int i = 0; i < count; i++) {
            String label = String.format("thread-%d", i);
            futures.add(executor.submit(() -> {
                LOG.info("Wait: resolve @" + label);
                latch.countDown();
                if (latch.await(5, TimeUnit.SECONDS) == false) {
                    throw new TimeoutException();
                }
                LOG.info("Start: resolve @" + label);
                Path result = cache.resolve(path);

                LOG.info("Finish: resolve @" + label);
                return result;
            }));
        }
        executor.shutdown();
        if (executor.awaitTermination(30, TimeUnit.SECONDS) == false) {
            throw new TimeoutException();
        }
    } finally {
        executor.shutdownNow();
    }
    for (Future<Path> future : futures) {
        future.get();
    }
}

From source file:gateway.test.UtilTests.java

/**
 * Initialize mock objects./*from  ww w . jav  a2  s.co m*/
 */
@Before
public void setup() {
    MockitoAnnotations.initMocks(this);

    // Mock the Kafka response that Producers will send. This will always
    // return a Future that completes immediately and simply returns true.
    when(producer.send(isA(ProducerRecord.class))).thenAnswer(new Answer<Future<Boolean>>() {
        @Override
        public Future<Boolean> answer(InvocationOnMock invocation) throws Throwable {
            Future<Boolean> future = mock(FutureTask.class);
            when(future.isDone()).thenReturn(true);
            when(future.get()).thenReturn(true);
            return future;
        }
    });
}

From source file:de.zib.gndms.infra.tests.FileTransferActionTest.java

@Test(groups = { "net", "db", "sys", "action", "task" })
public void testIt() throws ResourceException, ExecutionException, InterruptedException {

    EntityManager em = null;//from  ww  w.j  ava 2 s  .c  om
    try {
        em = getSys().getEntityManagerFactory().createEntityManager();
        em.getTransaction().begin();
        em.persist(task);
        em.getTransaction().commit();
        FileTransferTaskAction action = new FileTransferTaskAction(em, task);
        Future<AbstractTask> serializableFuture = getSys().submitAction(action, log);
        assert serializableFuture.get().getState().equals(TaskState.FINISHED);
        FileTransferResult ftr = (FileTransferResult) task.getData();
        for (String s : Arrays.asList(ftr.getFiles()))
            System.out.println(s);

    } finally {
        if (em != null && em.isOpen())
            em.close();
    }
}

From source file:com.alibaba.cobar.client.merger.ConcurrentSortMerger.java

public List<E> merge(List<List<E>> entities) {
    List<E> resultList = new ArrayList<E>();
    if (CollectionUtils.isNotEmpty(entities)) {
        if (entities.size() == 1) {
            resultList.addAll(entities.get(0));
        } else {/*from   www. j  a v  a2  s. co  m*/
            List<List<E>> partialResult = new ArrayList<List<E>>();
            int pairs = entities.size() / 2;
            List<Future<List<E>>> futures = new ArrayList<Future<List<E>>>();

            for (int i = 0; i < pairs; i++) {
                final List<E> llst = entities.get(i * 2);
                final List<E> rlst = entities.get(i * 2 + 1);
                futures.add(getExecutor().submit(new Callable<List<E>>() {
                    public List<E> call() throws Exception {
                        return partialSortMerge(llst, rlst);
                    }
                }));
            }

            for (Future<List<E>> f : futures) {
                try {
                    partialResult.add(f.get());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (ExecutionException e) {
                    e.printStackTrace();
                }
            }

            if (entities.size() % 2 == 1) {
                partialResult.add(entities.get(pairs * 2));
            }

            resultList.addAll(merge(partialResult));
        }
    }
    return resultList;
}

From source file:com.github.trask.sandbox.mail.ElasticEmailServiceTest.java

@Test
public void shouldThrowException() throws Exception {
    // given//  ww  w.  j  a  v  a  2s.c  o  m
    MailService mailService = new ElasticEmailService("fail", "fail", asyncHttpClient);
    String from = "unit.test.from@example.com";
    String to = "unit.test.to@example.com";
    String subject = getClass().getSimpleName();
    String htmlBody = "<html><body>click <a href=\"http://google.com\">here</a>";
    String textBody = "go to http://google.com";
    // when
    Future<Void> future = mailService.sendMail(from, to, subject, htmlBody, textBody);
    boolean exceptionThrown = false;
    try {
        future.get();
    } catch (Exception e) {
        // TODO be more specific about exception
        exceptionThrown = true;
    }
    // then
    assertThat(exceptionThrown, is(true));
}

From source file:net.sf.jabref.JabRefExecutorService.java

public void executeAndWait(Runnable command) {
    if (command == null) {
        //TODO logger
        return;/*from w  w w. j av  a  2  s.  c  o  m*/
    }

    Future<?> future = executorService.submit(command);
    while (true) {
        try {
            future.get();
            return;
        } catch (InterruptedException ignored) {
            // Ignored
        } catch (ExecutionException e) {
            LOGGER.error("Problem executing command", e);
        }
    }
}

From source file:io.undertow.server.handlers.RequestLimitingHandlerTestCase.java

@Test
public void testRateLimitingHandler() throws ExecutionException, InterruptedException {
    latch.countDown();/*  w ww .  java  2  s  . c om*/
    latch = new CountDownLatch(1);
    ExecutorService executor = Executors.newFixedThreadPool(N_THREADS);
    try {
        final List<Future<?>> futures = new ArrayList<>();
        for (int i = 0; i < N_THREADS; ++i) {
            futures.add(executor.submit(new Callable<String>() {
                @Override
                public String call() {
                    TestHttpClient client = new TestHttpClient();
                    try {
                        HttpGet get = new HttpGet(DefaultServer.getDefaultServerURL());
                        HttpResponse result = client.execute(get);
                        Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
                        return HttpClientUtils.readResponse(result);
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    } finally {
                        client.getConnectionManager().shutdown();
                    }
                }
            }));
        }
        Thread.sleep(300);
        latch.countDown();
        for (Future<?> future : futures) {
            String res = (String) future.get();
            Assert.assertTrue(res, res.equals("1") || res.equals("2"));
        }
    } finally {
        executor.shutdown();
    }

}

From source file:com.github.trask.sandbox.mail.GmailServiceTest.java

@Test
public void shouldThrowException() throws Exception {
    // given/*from   ww  w . j  a  v a2  s  .c  om*/
    MailService mailService = new GmailService("fail", "fail", executorService);
    String from = "unit.test.from@example.com";
    String to = "unit.test.to@example.com";
    String subject = getClass().getSimpleName();
    String htmlBody = "<html><body>click <a href=\"http://google.com\">here</a>";
    String textBody = "go to http://google.com";
    // when
    Future<Void> future = mailService.sendMail(from, to, subject, htmlBody, textBody);
    boolean exceptionThrown = false;
    try {
        future.get();
    } catch (Exception e) {
        // TODO be more specific about exception
        exceptionThrown = true;
    }
    // then
    assertThat(exceptionThrown, is(true));
}

From source file:de.zib.gndms.infra.system.DummyTaskActionTest.java

@Test(groups = { "db", "sys", "action", "task" })
public void runSuccesfulDummyAction() throws ExecutionException, InterruptedException, ResourceException {
    synchronized (lock) {
        eraseDatabase();//from w  ww.  j  av a 2s. c  om
        runDatabase();
        final EntityManager em = getSys().getEntityManagerFactory().createEntityManager();
        final DummyTaskAction action = new DummyTaskAction(em, createInitialTask(nextUUID()));
        action.setSuccessRate(1.0d);
        final Future<AbstractTask> serializableFuture = getSys().submitAction(action, log);
        assert serializableFuture.get().getState().equals(TaskState.FINISHED);
        shutdownDatabase();
    }
}