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

Source Link

Document

Waits if necessary for this future to complete, and then returns its result.

Usage

From source file:io.ventu.rpc.amqp.AmqpInvokerimplTest.java

@Test
public void invoke_onNokRequest_onEncodingEx_futureCompletesExceptionally()
        throws IOException, TimeoutException, ExecutionException, InterruptedException {
    String instanceId = "123456789";

    Req req = new Req();

    Channel channel = mock(Channel.class);

    CompletableFuture<Res> answer = new CompletableFuture<>();
    ResponseReceiver receiver = mock(ResponseReceiver.class);
    doReturn(answer).when(receiver).put(anyString(), any());

    ChannelProvider channelProvider = mock(ChannelProvider.class);
    doReturn(channel).when(channelProvider).provide(instanceId, receiver);

    ObjectMapper mapper = mock(ObjectMapper.class);
    doThrow(JsonProcessingException.class).when(mapper).writeValueAsBytes(any());

    RemoteInvoker invoker = new AmqpInvokerImpl(instanceId, channelProvider, receiver,
            new DefaultRequestRouter(), new UidGenerator() {
            }, new DefaultSerializer(mapper), Maps.newHashMap());
    CompletableFuture<Res> actual = invoker.invoke(req, Res.class);

    assertSame(answer, actual);// ww  w.  j a  v  a2  s  . c  o m
    assertTrue(actual.isDone());
    assertTrue(actual.isCompletedExceptionally());

    exception.expect(ExecutionException.class);
    try {
        actual.get();
    } catch (ExecutionException ex) {
        assertTrue(ex.getCause() instanceof EncodingException);
        throw ex;
    }
}

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

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

    HttpResponse response = mock(HttpResponse.class);
    HttpEntity httpEntity = mock(HttpEntity.class);
    when(response.getEntity()).thenReturn(httpEntity);
    StatusLine statusLine = mock(StatusLine.class);
    when(response.getStatusLine()).thenReturn(statusLine);
    when(statusLine.getStatusCode()).thenReturn(200);

    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 {
        InputStream inputStream = IOUtils.toInputStream(SERVER_EXPECTED_RESPONSE_FOR_INGESTION, "UTF-8");
        when(httpEntity.getContent()).thenReturn(inputStream);
        CompletableFuture<IngestionResponse> responseFuture = client.ingest(request);
        Assert.assertTrue("Invalid status in ingestion response",
                "ok".equals(responseFuture.get().getStatus()));
    } catch (Exception e) {
        logger.error("Exception raised " + ExceptionUtils.getStackTrace(e));
        Assert.assertTrue(false);
    }
}

From source file:com.ikanow.aleph2.data_import_manager.analytics.actors.DataBucketAnalyticsChangeActor.java

/** Wraps the communications with the tech module so that calls to completeExceptionally are handled
 * @param bucket//  w  w  w .  j  av a  2  s.co  m
 * @param m
 * @param source
 * @param context
 * @param err_or_tech_module - the tech module (is ignored unless the user code got called ie implies err_or_tech_module.isRight)
 * @param return_value - either the user return value or a wrap of the exception
 * @return
 */
public static final CompletableFuture<BucketActionReplyMessage> handleTechnologyErrors(
        final DataBucketBean bucket, final BucketActionMessage m, final String source,
        final Validation<BasicMessageBean, Tuple2<IAnalyticsTechnologyModule, ClassLoader>> err_or_tech_module,
        final CompletableFuture<BucketActionReplyMessage> return_value // "pipeline element"
) {
    if (return_value.isCompletedExceptionally()) { // Harvest Tech developer called completeExceptionally, ugh
        try {
            return_value.get(); // (causes an exception)
        } catch (Throwable t) { // e.getCause() is the exception we want
            // Note if we're here then err_or_tech_module must be "right"
            return CompletableFuture.completedFuture(new BucketActionHandlerMessage(source,
                    SharedErrorUtils.buildErrorMessage(source, m,
                            ErrorUtils.getLongForm(AnalyticsErrorUtils.NO_TECHNOLOGY_NAME_OR_ID, t.getCause(),
                                    m.bucket().full_name(), err_or_tech_module.success()._1().getClass()))));
        }
    }
    //(else fall through to...)
    return return_value;
}

From source file:io.ventu.rpc.amqp.AmqpInvokerimplTest.java

@Test
public void closingInvoker_onIOException_exception()
        throws IOException, TimeoutException, ExecutionException, InterruptedException {
    String instanceId = "123456789";

    Channel channel = mock(Channel.class);
    doThrow(new IOException("boom")).when(channel).close();
    ResponseReceiver receiver = mock(ResponseReceiver.class);
    ChannelProvider channelProvider = mock(ChannelProvider.class);
    doReturn(channel).when(channelProvider).provide(instanceId, receiver);

    RemoteInvoker invoker = new AmqpInvokerImpl(instanceId, channelProvider, receiver);

    CompletableFuture<Void> actual = invoker.close();

    verify(channel).close();/*from w w  w. ja v  a2 s .  co  m*/
    verifyNoMoreInteractions(channel);

    assertTrue(actual.isDone());
    assertTrue(actual.isCompletedExceptionally());

    exception.expect(ExecutionException.class);
    try {
        actual.get();
    } catch (ExecutionException ex) {
        assertTrue(ex.getCause() instanceof IOException);
        throw ex;
    }
}

From source file:org.pentaho.di.ui.repo.controller.RepositoryConnectController.java

public boolean deleteDatabaseConnection(String database) {
    CompletableFuture<Boolean> future = new CompletableFuture<>();
    spoonSupplier.get().getShell().getDisplay().asyncExec(() -> {
        removeDatabase(database);//  w  w  w.  j a  v  a 2  s .co m
        future.complete(true);
    });
    try {
        return future.get();
    } catch (Exception e) {
        return false;
    }
}

From source file:org.apache.tinkerpop.gremlin.driver.ResultQueueTest.java

@Test
public void shouldAwaitMultipleToExpectedValueAndDrainOnAdd() throws Exception {
    final CompletableFuture<List<Result>> future1 = resultQueue.await(3);
    final CompletableFuture<List<Result>> future2 = resultQueue.await(1);
    resultQueue.add(new Result("test1"));
    resultQueue.add(new Result("test2"));

    // shouldn't complete the first future until the third item is in play
    assertThat(future1.isDone(), is(false));
    assertThat(future2.isDone(), is(false));

    resultQueue.add(new Result("test3"));

    final List<Result> results1 = future1.get();
    assertEquals("test1", results1.get(0).getString());
    assertEquals("test2", results1.get(1).getString());
    assertEquals("test3", results1.get(2).getString());
    assertEquals(3, results1.size());/*from   www  .j av  a2  s. c om*/
    assertThat(future1.isDone(), is(true));
    assertThat(future2.isDone(), is(false));

    resultQueue.add(new Result("test4"));
    assertThat(future1.isDone(), is(true));
    assertThat(future2.isDone(), is(true));

    final List<Result> results2 = future2.get();
    assertEquals("test4", results2.get(0).getString());
    assertEquals(1, results2.size());

    assertThat(resultQueue.isEmpty(), is(true));
}

From source file:com.ikanow.aleph2.storage_service_hdfs.services.TestHdfsDataWriteService.java

public void test_writerService_end2end(Optional<String> secondary, boolean is_transient)
        throws InterruptedException, ExecutionException {
    final String temp_dir = System.getProperty("java.io.tmpdir") + File.separator;
    HfdsDataWriteService<TestBean> write_service = getWriter(
            "/test/writer/end2end/" + secondary.orElse("current") + "/", secondary, is_transient);

    //(Tidy up)/*from   w w  w. ja  v a2  s. c o  m*/
    try {
        FileUtils.deleteDirectory(new File(temp_dir + "/data/" + write_service._bucket.full_name()));
    } catch (Exception e) {
    }

    // Check lazy initialization only kicks in once      
    Optional<IBatchSubservice<TestBean>> x = write_service.getBatchWriteSubservice();
    assertEquals(x.get(), write_service._writer.get());
    Optional<IBatchSubservice<TestBean>> y = write_service.getBatchWriteSubservice();
    assertEquals(x.get(), y.get());

    IBatchSubservice<TestBean> batch = x.get();

    // Set up properties for testing:
    batch.setBatchProperties(Optional.of(1000), Optional.of(1000L), Optional.of(Duration.ofSeconds(2L)),
            Optional.of(3));

    Thread.sleep(1000L);
    // Check there are now 3 threads
    assertEquals(3, write_service._writer.get()._state._workers.getActiveCount());

    for (int i = 0; i < 20; ++i) {
        TestBean emit = new TestBean("id" + i, "val" + i);
        if (0 == (i % 2)) {
            if (0 == ((i / 2) % 2)) {
                batch.storeObject(emit);
            } else {
                CompletableFuture<Supplier<Object>> cf = write_service.storeObject(emit);
                assertEquals(null, cf.get().get());
            }
        } else {
            if (0 == ((i / 2) % 2)) {
                batch.storeObjects(Arrays.asList(emit));
            } else {
                CompletableFuture<Tuple2<Supplier<List<Object>>, Supplier<Long>>> cf = write_service
                        .storeObjects(Arrays.asList(emit));
                assertEquals(Collections.emptyList(), cf.get()._1().get());
                assertEquals(1L, cf.get()._2().get().longValue());
            }
        }
    }
    final String infix = is_transient ? IStorageService.TRANSIENT_DATA_SUFFIX_SECONDARY
            : IStorageService.STORED_DATA_SUFFIX_PROCESSED_SECONDARY;
    final String infix_name = is_transient ? "testj-testm" : "";

    // Check that initially the files are stored locally
    File init_dir = new File((temp_dir + "/data/" + write_service._bucket.full_name() + infix
            + secondary.orElse("current") + "/" + infix_name + "/.spooldir/").replace("/", File.separator));
    File final_dir = new File((temp_dir + "/data/" + write_service._bucket.full_name() + infix
            + secondary.orElse("current") + "/" + infix_name + "/all_time/").replace("/", File.separator));

    {
        int ii = 1;
        for (; ii <= 50; ++ii) {
            Thread.sleep(250L);
            if (6 == init_dir.list().length) {
                break;
            }
        }
        System.out.println("(exited from file system check after " + ii * 2.5 + " s)");
    }

    assertEquals("Needs to have 6 files, including 3x .crc: " + Arrays.toString(init_dir.list()), 6,
            init_dir.list().length); //*2 because CRC
    assertTrue(
            "Nothing in final dir: " + (final_dir.exists() ? Arrays.toString(final_dir.list()) : "(non-exist)"),
            !final_dir.exists() || final_dir.list().length == 0);

    {
        int ii = 1;
        for (; ii <= 50; ++ii) {
            Thread.sleep(2500L);
            if (0 == init_dir.list().length) {
                break;
            }
        }
        System.out.println("(exited from file system check after " + ii * 2.5 + " s)");
    }

    assertEquals(0, init_dir.list().length); //*2 because CRC
    assertEquals(6, final_dir.list().length); //*2 because CRC      

    // Change batch properties so that will segment (also check number of threads reduces)
    batch.setBatchProperties(Optional.of(10), Optional.of(1000L), Optional.of(Duration.ofSeconds(5L)),
            Optional.of(1));
    List<TestBean> l1 = IntStream.range(0, 8).boxed().map(i -> new TestBean("id" + i, "val" + i))
            .collect(Collectors.toList());
    List<TestBean> l2 = IntStream.range(8, 15).boxed().map(i -> new TestBean("id" + i, "val" + i))
            .collect(Collectors.toList());

    batch.storeObjects(l1);
    Thread.sleep(750L);
    assertEquals(6, final_dir.list().length); //*2 because CRC      
    System.out.println("Found: 6 files: " + Arrays.stream(final_dir.list()).collect(Collectors.joining(";")));

    batch.storeObjects(l2);
    System.out.println("Added 7 more objects at " + new Date());
    for (int jj = 0; jj < 5; ++jj) {
        Thread.sleep(1500L);
        if (final_dir.list().length > 6)
            break;
    }
    System.out.println("(Check init dir cleared: "
            + Arrays.stream(init_dir.list()).collect(Collectors.joining(";")) + ")");
    assertEquals("Should have 8 files: " + Arrays.stream(final_dir.list()).collect(Collectors.joining(";")), 8,
            final_dir.list().length); //*2 because CRC   

    System.out.println("(Deleting datastore and checking it's empty)");
    assertTrue("Deleted datastore: ", write_service.deleteDatastore().get()); // (just quick test since this uses handleBucketDeletion which is tested elsewhere...)
    String[] final_dir_list = Optional.ofNullable(final_dir.list()).orElse(new String[0]);
    assertEquals("Should have 0 files: " + Arrays.stream(final_dir_list).collect(Collectors.joining(";")), 0,
            final_dir_list.length); //*2 because CRC   
}

From source file:com.yahoo.pulsar.broker.service.BrokerService.java

public Topic getTopicReference(String topic) throws Exception {
    CompletableFuture<Topic> future = topics.get(topic);
    if (future != null && future.isDone() && !future.isCompletedExceptionally()) {
        return future.get();
    } else {/* w  ww.j a  v  a2  s .  co m*/
        return null;
    }
}

From source file:io.ventu.rpc.amqp.AmqpInvokerimplTest.java

@Test
public void responseReceiver_handleDelivery_onEncodingException_exception()
        throws EncodingException, IOException, InterruptedException, ExecutionException, TimeoutException {
    ResponseReceiverImpl receiver = new ResponseReceiverImpl(serializer, new Validator() {
    }, 1, TimeUnit.MINUTES);/*from   ww  w  .  j  a  v  a  2 s. c o m*/

    String correlationId = "987654321";
    CompletableFuture<Res> answer = receiver.put(correlationId, Res.class);
    assertFalse(answer.isDone());
    assertFalse(answer.isCompletedExceptionally());

    receiver.handleDelivery(correlationId, new byte[] {});
    assertTrue(answer.isDone());
    assertTrue(answer.isCompletedExceptionally());

    exception.expect(ExecutionException.class);
    try {
        answer.get();
    } catch (ExecutionException ex) {
        assertTrue(ex.getCause() instanceof EncodingException);
        assertEquals("failed to decode JSON", ex.getCause().getMessage());
        throw ex;
    }
}

From source file:com.ikanow.aleph2.harvest.script.services.TestScriptHarvestService.java

@Test
public void testRunResource() throws InterruptedException, ExecutionException {
    //create a file in this package, send as a bucket param, see if it works (dunno if this one is possible)
    //save a file to /tmp/somescript.sh and send that as a bucket param, test it works
    final ScriptHarvestService harvester = new ScriptHarvestService();
    harvester.onInit(getFakeContext());//from  www . j a v a 2 s  .  c o  m

    final String tmp_dir = System.getProperty("java.io.tmpdir");
    final String file_path = tmp_dir + File.separator + "test2";
    final File file = new File(file_path);
    try {
        file.delete();
    } catch (Exception e) {
    } //cleanup if the file exists from previous test                        

    //have to put quotes around the path on windows systems      
    final CompletableFuture<BasicMessageBean> future = harvester.onTestSource(
            getTestbucket("/test/script4", Optional.empty(), Optional.empty(), Optional.of("resource_test.sh"),
                    new HashMap<String, String>(), new ArrayList<String>()),
            new ProcessingTestSpecBean(10L, 10L), getFakeContext());
    final BasicMessageBean response = future.get();
    assertTrue(response.message(), response.success());

    //test if file was created
    final long curr_time = System.currentTimeMillis();
    while (System.currentTimeMillis() < curr_time + 5000) {
        if (file.exists())
            break;
        Thread.sleep(300);
    }
    assertTrue(file.exists());

    //cleanup
    file.delete();
}