Example usage for java.util.concurrent CompletableFuture CompletableFuture

List of usage examples for java.util.concurrent CompletableFuture CompletableFuture

Introduction

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

Prototype

public CompletableFuture() 

Source Link

Document

Creates a new incomplete CompletableFuture.

Usage

From source file:org.springframework.integration.aggregator.AggregatorTests.java

@Test
public void testAggPerf() throws InterruptedException, ExecutionException, TimeoutException {
    AggregatingMessageHandler handler = new AggregatingMessageHandler(
            new DefaultAggregatingMessageGroupProcessor());
    handler.setCorrelationStrategy(message -> "foo");
    handler.setReleaseStrategy(new MessageCountReleaseStrategy(60000));
    handler.setExpireGroupsUponCompletion(true);
    handler.setSendPartialResultOnExpiry(true);
    DirectChannel outputChannel = new DirectChannel();
    handler.setOutputChannel(outputChannel);

    final CompletableFuture<Collection<?>> resultFuture = new CompletableFuture<>();
    outputChannel.subscribe(message -> {
        Collection<?> payload = (Collection<?>) message.getPayload();
        logger.warn("Received " + payload.size());
        resultFuture.complete(payload);//  w  w  w.  j a  va 2 s .com
    });

    SimpleMessageStore store = new SimpleMessageStore();

    SimpleMessageGroupFactory messageGroupFactory = new SimpleMessageGroupFactory(
            SimpleMessageGroupFactory.GroupType.BLOCKING_QUEUE);

    store.setMessageGroupFactory(messageGroupFactory);

    handler.setMessageStore(store);

    Message<?> message = new GenericMessage<String>("foo");
    StopWatch stopwatch = new StopWatch();
    stopwatch.start();
    for (int i = 0; i < 120000; i++) {
        if (i % 10000 == 0) {
            stopwatch.stop();
            logger.warn("Sent " + i + " in " + stopwatch.getTotalTimeSeconds() + " (10k in "
                    + stopwatch.getLastTaskTimeMillis() + "ms)");
            stopwatch.start();
        }
        handler.handleMessage(message);
    }
    stopwatch.stop();
    logger.warn("Sent " + 120000 + " in " + stopwatch.getTotalTimeSeconds() + " (10k in "
            + stopwatch.getLastTaskTimeMillis() + "ms)");

    Collection<?> result = resultFuture.get(10, TimeUnit.SECONDS);
    assertNotNull(result);
    assertEquals(60000, result.size());
}

From source file:org.apache.samza.table.remote.couchbase.CouchbaseTableReadFunction.java

@Override
public CompletableFuture<V> getAsync(String key) {
    Preconditions.checkArgument(StringUtils.isNotBlank(key), "key must not be null, empty or blank");
    CompletableFuture<V> future = new CompletableFuture<>();
    Single<? extends Document<?>> singleObservable = bucket.async()
            .get(key, documentType, timeout.toMillis(), TimeUnit.MILLISECONDS).toSingle();
    singleObservable.subscribe(new SingleSubscriber<Document<?>>() {
        @Override//from  ww w.  j av a  2s  .co  m
        public void onSuccess(Document<?> document) {
            if (document != null) {
                if (document instanceof BinaryDocument) {
                    handleGetAsyncBinaryDocument((BinaryDocument) document, future, key);
                } else {
                    // V is of type JsonObject
                    future.complete((V) document.content());
                }
            } else {
                // The Couchbase async client should not return null
                future.completeExceptionally(
                        new SamzaException(String.format("Got unexpected null value from key %s", key)));
            }
        }

        @Override
        public void onError(Throwable throwable) {
            if (throwable instanceof NoSuchElementException) {
                // There is no element returned by the observable, meaning the key doesn't exist.
                future.complete(null);
            } else {
                future.completeExceptionally(
                        new SamzaException(String.format("Failed to get key %s", key), throwable));
            }
        }
    });
    return future;
}

From source file:com.devicehive.handler.notification.NotificationSearchHandlerTest.java

@Test
public void shouldHandleNotificationInsertAndQueryByDeviceGuidAndNotificationName() throws Exception {
    NotificationSearchRequest searchRequest = new NotificationSearchRequest();
    searchRequest.setGuid(notifications.get(0).getDeviceGuid());
    searchRequest.setNames(Collections.singleton(notifications.get(0).getNotification()));

    Request request = Request.newBuilder().withBody(searchRequest).build();
    CompletableFuture<Response> future = new CompletableFuture<>();
    client.call(request, future::complete);

    Response response = future.get(10, TimeUnit.SECONDS);
    NotificationSearchResponse responseBody = (NotificationSearchResponse) response.getBody();
    assertEquals(1, responseBody.getNotifications().size());
    assertEquals(notifications.get(0), responseBody.getNotifications().get(0));
}

From source file:org.apache.hadoop.hbase.client.TestAsyncSingleRequestRpcRetryingCaller.java

private <T> CompletableFuture<T> failedFuture() {
    CompletableFuture<T> future = new CompletableFuture<>();
    future.completeExceptionally(new RuntimeException("Inject error!"));
    return future;
}

From source file:org.apache.trafficcontrol.client.trafficops.TOSession.java

public CompletableFuture<Response.CollectionResponse> getServers(final Map<String, ?> filterParams) {
    URI uri;/*from w ww .j  a v a 2 s . co m*/
    try {
        uri = this.newUriBuilder("servers.json").setParameters(this.toPairs(filterParams)).build();
    } catch (Throwable e) {
        final CompletableFuture<Response.CollectionResponse> f = new CompletableFuture<>();
        f.completeExceptionally(e);
        return f;
    }
    return ResponseFuture.builder(Response.CollectionResponse.class).setMethod(ResponseFuture.Method.GET)
            .setUri(uri).setSession(this.restClient()).build();
}

From source file:com.devicehive.handler.command.CommandSubscribeIntegrationTest.java

@Test
public void shouldSubscribeToDeviceCommands() throws Exception {
    String device1 = randomUUID().toString();
    String device2 = randomUUID().toString();

    String subscriber1 = randomUUID().toString();
    String subscriber2 = randomUUID().toString();
    String subscriber3 = randomUUID().toString();

    CommandSubscribeRequest sr1 = new CommandSubscribeRequest(subscriber1, device1, null, null);
    Request r1 = Request.newBuilder().withBody(sr1).withSingleReply(false).build();
    TestCallback c1 = new TestCallback();
    client.call(r1, c1);//from w  w  w . ja  va2  s  .c om

    CommandSubscribeRequest sr2 = new CommandSubscribeRequest(subscriber1, device2,
            Collections.singleton("increase_temperature"), null);
    Request r2 = Request.newBuilder().withBody(sr2).withSingleReply(false).build();
    TestCallback c2 = new TestCallback();
    client.call(r2, c2);

    CommandSubscribeRequest sr3 = new CommandSubscribeRequest(subscriber2, device2, null, null);
    Request r3 = Request.newBuilder().withBody(sr3).withSingleReply(false).build();
    TestCallback c3 = new TestCallback();
    client.call(r3, c3);

    CommandSubscribeRequest sr4 = new CommandSubscribeRequest(subscriber2, device1,
            Collections.singleton("toggle_lights"), null);
    Request r4 = Request.newBuilder().withBody(sr4).withSingleReply(false).build();
    TestCallback c4 = new TestCallback();
    client.call(r4, c4);

    CommandSubscribeRequest sr5 = new CommandSubscribeRequest(subscriber3, randomUUID().toString(), null, null);
    Request r5 = Request.newBuilder().withBody(sr5).withSingleReply(false).build();
    TestCallback c5 = new TestCallback();
    client.call(r5, c5);

    //wait for subscribers to subscribe
    Stream.of(c1.subscribeFuture, c2.subscribeFuture, c3.subscribeFuture, c4.subscribeFuture,
            c5.subscribeFuture).forEach(CompletableFuture::join);

    //devices send commands
    List<CompletableFuture<Response>> futures = Stream.of(device1, device2).flatMap(device -> {
        List<CompletableFuture<Response>> list = Stream.of("increase_temperature", "toggle_lights")
                .map(name -> {
                    DeviceCommand command = new DeviceCommand();
                    command.setId(0);
                    command.setCommand(name);
                    command.setDeviceGuid(device);
                    CommandInsertRequest event = new CommandInsertRequest(command);
                    CompletableFuture<Response> f = new CompletableFuture<>();
                    client.call(Request.newBuilder().withBody(event).build(), f::complete);
                    return f;
                }).collect(Collectors.toList());
        return list.stream();
    }).collect(Collectors.toList());

    //wait for commands to be delivered
    futures.forEach(CompletableFuture::join);

    assertThat(c1.commands, hasSize(2));
    c1.commands.forEach(event -> {
        assertNotNull(event.getCommand());
        assertEquals(event.getCommand().getDeviceGuid(), device1);
        assertEquals(event.getCommand().getId(), Long.valueOf(0));
    });
    Set<String> names = c1.commands.stream().map(n -> n.getCommand().getCommand()).collect(Collectors.toSet());
    assertThat(names, containsInAnyOrder("increase_temperature", "toggle_lights"));

    assertThat(c2.commands, hasSize(1));
    CommandEvent e = c2.commands.stream().findFirst().get();
    assertNotNull(e.getCommand());
    assertEquals(e.getCommand().getDeviceGuid(), device2);
    assertEquals(e.getCommand().getId(), Long.valueOf(0));
    assertEquals(e.getCommand().getCommand(), "increase_temperature");

    assertThat(c3.commands, hasSize(2));
    c3.commands.forEach(event -> {
        assertNotNull(event.getCommand());
        assertEquals(event.getCommand().getDeviceGuid(), device2);
        assertEquals(event.getCommand().getId(), Long.valueOf(0));
    });
    names = c3.commands.stream().map(n -> n.getCommand().getCommand()).collect(Collectors.toSet());
    assertThat(names, containsInAnyOrder("increase_temperature", "toggle_lights"));

    assertThat(c4.commands, hasSize(1));
    e = c4.commands.stream().findFirst().get();
    assertNotNull(e.getCommand());
    assertEquals(e.getCommand().getDeviceGuid(), device1);
    assertEquals(e.getCommand().getId(), Long.valueOf(0));
    assertEquals(e.getCommand().getCommand(), "toggle_lights");

    assertThat(c5.commands, is(empty()));
}

From source file:org.apache.samza.table.remote.couchbase.CouchbaseTableWriteFunction.java

/**
 * Helper method for putAsync and deleteAsync to convert Single to CompletableFuture.
 *///from   w w w . j  a va2  s  .c om
private CompletableFuture<Void> asyncWriteHelper(Single<? extends Document<?>> single, String errorMessage) {
    CompletableFuture<Void> future = new CompletableFuture<>();
    single.subscribe(new SingleSubscriber<Document>() {
        @Override
        public void onSuccess(Document v) {
            future.complete(null);
        }

        @Override
        public void onError(Throwable error) {
            future.completeExceptionally(new SamzaException(errorMessage, error));
        }
    });
    return future;
}

From source file:org.onosproject.store.primitives.impl.CopycatTransportConnection.java

@Override
public <T, U> CompletableFuture<U> send(T message) {
    ThreadContext context = ThreadContext.currentContextOrThrow();
    CompletableFuture<U> result = new CompletableFuture<>();
    try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
        new DataOutputStream(baos).writeLong(connectionId);
        context.serializer().writeObject(message, baos);
        if (message instanceof ReferenceCounted) {
            ((ReferenceCounted<?>) message).release();
        }// w w w  .  j  a  v  a 2 s.  co  m
        messagingService.sendAndReceive(CopycatTransport.toEndpoint(remoteAddress), outboundMessageSubject,
                baos.toByteArray(), context.executor()).whenComplete((r, e) -> {
                    Throwable wrappedError = e;
                    if (e != null) {
                        Throwable rootCause = Throwables.getRootCause(e);
                        if (MessagingException.class.isAssignableFrom(rootCause.getClass())) {
                            wrappedError = new TransportException(e);
                        }
                    }
                    handleResponse(r, wrappedError, result, context);
                });
    } catch (SerializationException | IOException e) {
        result.completeExceptionally(e);
    }
    return result;
}

From source file:com.devicehive.rpcclient.RpcClientActionTest.java

@Test
public void testCommandUpdateAction() throws Exception {
    DeviceCommand command = new DeviceCommand();
    command.setCommand("test_command");
    command.setResult(new JsonStringWrapper("{\"result\": \"OK\"}"));
    command.setDeviceGuid(UUID.randomUUID().toString());
    CommandUpdateRequest updateRequest = new CommandUpdateRequest(command);

    Request request = Request.newBuilder().withPartitionKey(updateRequest.getDeviceCommand().getDeviceGuid())
            .withBody(updateRequest).build();
    CompletableFuture<Response> future = new CompletableFuture<>();
    client.call(request, future::complete);

    Response response = future.get(10, TimeUnit.SECONDS);
    assertNotNull(response);/*w ww  .  jav  a 2s  .c  o m*/
}

From source file:com.vanillasource.gerec.httpclient.AsyncApacheHttpClient.java

private CompletableFuture<HttpResponse> execute(AsyncHttpRequest request) {
    CompletableFuture<HttpResponse> result = new CompletableFuture<>();
    logger.debug("making the async http request");
    httpClientSupplier.get().execute(request.getProducer(result), AsyncHttpResponse.getConsumer(result),
            new NopFutureCallback());
    return result;
}