Example usage for java.util.concurrent CompletableFuture allOf

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

Introduction

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

Prototype

public static CompletableFuture<Void> allOf(CompletableFuture<?>... cfs) 

Source Link

Document

Returns a new CompletableFuture that is completed when all of the given CompletableFutures complete.

Usage

From source file:com.microsoft.azure.servicebus.samples.partitionedqueues.PartitionedQueues.java

CompletableFuture<Void> sendMessagesAsync(QueueClient sendClient) {

    List<HashMap<String, String>> data = GSON.fromJson("[" + "{'name' = 'Einstein', 'firstName' = 'Albert'},"
            + "{'name' = 'Heisenberg', 'firstName' = 'Werner'}," + "{'name' = 'Curie', 'firstName' = 'Marie'},"
            + "{'name' = 'Hawking', 'firstName' = 'Steven'}," + "{'name' = 'Newton', 'firstName' = 'Isaac'},"
            + "{'name' = 'Bohr', 'firstName' = 'Niels'}," + "{'name' = 'Faraday', 'firstName' = 'Michael'},"
            + "{'name' = 'Galilei', 'firstName' = 'Galileo'},"
            + "{'name' = 'Kepler', 'firstName' = 'Johannes'},"
            + "{'name' = 'Kopernikus', 'firstName' = 'Nikolaus'}" + "]",
            new TypeToken<List<HashMap<String, String>>>() {
            }.getType());/*from w w w .ja  v a  2s .  c  o m*/

    List<CompletableFuture> tasks = new ArrayList<>();
    for (int i = 0; i < data.size(); i++) {
        final String messageId = Integer.toString(i);
        Message message = new Message(GSON.toJson(data.get(i), Map.class).getBytes(UTF_8));
        message.setContentType("application/json");
        message.setLabel("Scientist");
        message.setMessageId(messageId);
        message.setTimeToLive(Duration.ofMinutes(2));
        message.setPartitionKey(data.get(i).get("name").substring(0, 1));

        tasks.add(sendClient.sendAsync(message).thenRunAsync(() -> {
            System.out.printf("Message sent: Id = %s\n", message.getMessageId());
        }));
    }
    return CompletableFuture.allOf(tasks.toArray(new CompletableFuture<?>[tasks.size()]));
}

From source file:com.microsoft.azure.servicebus.samples.messagebrowse.MessageBrowse.java

CompletableFuture<Void> sendMessagesAsync(QueueClient sendClient) {

    List<HashMap<String, String>> data = GSON.fromJson("[" + "{'name' = 'Einstein', 'firstName' = 'Albert'},"
            + "{'name' = 'Heisenberg', 'firstName' = 'Werner'}," + "{'name' = 'Curie', 'firstName' = 'Marie'},"
            + "{'name' = 'Hawking', 'firstName' = 'Steven'}," + "{'name' = 'Newton', 'firstName' = 'Isaac'},"
            + "{'name' = 'Bohr', 'firstName' = 'Niels'}," + "{'name' = 'Faraday', 'firstName' = 'Michael'},"
            + "{'name' = 'Galilei', 'firstName' = 'Galileo'},"
            + "{'name' = 'Kepler', 'firstName' = 'Johannes'},"
            + "{'name' = 'Kopernikus', 'firstName' = 'Nikolaus'}" + "]",
            new TypeToken<List<HashMap<String, String>>>() {
            }.getType());//  w  ww.j  a  v  a 2  s.c  o m

    List<CompletableFuture> tasks = new ArrayList<>();
    for (int i = 0; i < data.size(); i++) {
        final String messageId = Integer.toString(i);
        Message message = new Message(GSON.toJson(data.get(i), Map.class).getBytes(UTF_8));
        message.setContentType("application/json");
        message.setLabel("Scientist");
        message.setMessageId(messageId);
        message.setTimeToLive(Duration.ofMinutes(2));

        tasks.add(sendClient.sendAsync(message).thenRunAsync(() -> {
            System.out.printf("Message sent: Id = %s\n", message.getMessageId());
        }));
    }
    return CompletableFuture.allOf(tasks.toArray(new CompletableFuture<?>[tasks.size()]));
}

From source file:com.microsoft.azure.servicebus.samples.scheduledmessages.ScheduledMessages.java

CompletableFuture<Void> sendMessagesAsync(QueueClient sendClient) {

    List<HashMap<String, String>> data = GSON.fromJson("[" + "{'name' = 'Einstein', 'firstName' = 'Albert'},"
            + "{'name' = 'Heisenberg', 'firstName' = 'Werner'}," + "{'name' = 'Curie', 'firstName' = 'Marie'},"
            + "{'name' = 'Hawking', 'firstName' = 'Steven'}," + "{'name' = 'Newton', 'firstName' = 'Isaac'},"
            + "{'name' = 'Bohr', 'firstName' = 'Niels'}," + "{'name' = 'Faraday', 'firstName' = 'Michael'},"
            + "{'name' = 'Galilei', 'firstName' = 'Galileo'},"
            + "{'name' = 'Kepler', 'firstName' = 'Johannes'},"
            + "{'name' = 'Kopernikus', 'firstName' = 'Nikolaus'}" + "]",
            new TypeToken<List<HashMap<String, String>>>() {
            }.getType());/*  ww  w .  j  av a 2s  . c o m*/

    List<CompletableFuture> tasks = new ArrayList<>();
    for (int i = 0; i < data.size(); i++) {
        final String messageId = Integer.toString(i);
        Message message = new Message(GSON.toJson(data.get(i), Map.class).getBytes(UTF_8));
        message.setContentType("application/json");
        message.setLabel("Scientist");
        message.setMessageId(messageId);
        message.setTimeToLive(Duration.ofMinutes(2));
        message.setScheduledEnqueueTimeUtc(Clock.systemUTC().instant().plusSeconds(120));
        System.out.printf("Message sending: Id = %s\n", message.getMessageId());
        tasks.add(sendClient.sendAsync(message).thenRunAsync(() -> {
            System.out.printf("\tMessage acknowledged: Id = %s\n", message.getMessageId());
        }));
    }
    return CompletableFuture.allOf(tasks.toArray(new CompletableFuture<?>[tasks.size()]));
}

From source file:com.microsoft.azure.servicebus.samples.queuesgettingstarted.QueuesGettingStarted.java

CompletableFuture<Void> sendMessagesAsync(QueueClient sendClient) {
    List<HashMap<String, String>> data = GSON.fromJson("[" + "{'name' = 'Einstein', 'firstName' = 'Albert'},"
            + "{'name' = 'Heisenberg', 'firstName' = 'Werner'}," + "{'name' = 'Curie', 'firstName' = 'Marie'},"
            + "{'name' = 'Hawking', 'firstName' = 'Steven'}," + "{'name' = 'Newton', 'firstName' = 'Isaac'},"
            + "{'name' = 'Bohr', 'firstName' = 'Niels'}," + "{'name' = 'Faraday', 'firstName' = 'Michael'},"
            + "{'name' = 'Galilei', 'firstName' = 'Galileo'},"
            + "{'name' = 'Kepler', 'firstName' = 'Johannes'},"
            + "{'name' = 'Kopernikus', 'firstName' = 'Nikolaus'}" + "]",
            new TypeToken<List<HashMap<String, String>>>() {
            }.getType());/*from   www  .j  a  v a 2s . c o m*/

    List<CompletableFuture> tasks = new ArrayList<>();
    for (int i = 0; i < data.size(); i++) {
        final String messageId = Integer.toString(i);
        Message message = new Message(GSON.toJson(data.get(i), Map.class).getBytes(UTF_8));
        message.setContentType("application/json");
        message.setLabel("Scientist");
        message.setMessageId(messageId);
        message.setTimeToLive(Duration.ofMinutes(2));
        System.out.printf("\nMessage sending: Id = %s", message.getMessageId());
        tasks.add(sendClient.sendAsync(message).thenRunAsync(() -> {
            System.out.printf("\n\tMessage acknowledged: Id = %s", message.getMessageId());
        }));
    }
    return CompletableFuture.allOf(tasks.toArray(new CompletableFuture<?>[tasks.size()]));
}

From source file:com.microsoft.azure.servicebus.samples.timetolive.TimeToLive.java

CompletableFuture<Void> sendMessagesAsync(IMessageSender sendClient) {
    List<HashMap<String, String>> data = GSON.fromJson("[" + "{'name' = 'Einstein', 'firstName' = 'Albert'},"
            + "{'name' = 'Heisenberg', 'firstName' = 'Werner'}," + "{'name' = 'Curie', 'firstName' = 'Marie'},"
            + "{'name' = 'Hawking', 'firstName' = 'Steven'}," + "{'name' = 'Newton', 'firstName' = 'Isaac'},"
            + "{'name' = 'Bohr', 'firstName' = 'Niels'}," + "{'name' = 'Faraday', 'firstName' = 'Michael'},"
            + "{'name' = 'Galilei', 'firstName' = 'Galileo'},"
            + "{'name' = 'Kepler', 'firstName' = 'Johannes'},"
            + "{'name' = 'Kopernikus', 'firstName' = 'Nikolaus'}" + "]",
            new TypeToken<List<HashMap<String, String>>>() {
            }.getType());/*  ww w  .  jav  a 2s.co m*/

    List<CompletableFuture> tasks = new ArrayList<>();
    for (int i = 0; i < data.size(); i++) {
        final String messageId = Integer.toString(i);
        Message message = new Message(GSON.toJson(data.get(i), Map.class).getBytes(UTF_8));
        message.setContentType("application/json");
        message.setLabel(i % 2 == 0 ? "Scientist" : "Physicist");
        message.setMessageId(messageId);
        message.setTimeToLive(Duration.ofSeconds(15));
        System.out.printf("Message sending: Id = %s\n", message.getMessageId());
        tasks.add(sendClient.sendAsync(message).thenRunAsync(() -> {
            System.out.printf("\tMessage acknowledged: Id = %s\n", message.getMessageId());
        }));
    }
    return CompletableFuture.allOf(tasks.toArray(new CompletableFuture<?>[tasks.size()]));
}

From source file:com.devicehive.service.DeviceCommandService.java

public CompletableFuture<List<DeviceCommand>> find(Collection<String> guids, Collection<String> names,
        Date timestampSt, Date timestampEnd, String status) {
    List<CompletableFuture<Response>> futures = guids.stream().map(guid -> {
        CommandSearchRequest searchRequest = new CommandSearchRequest();
        searchRequest.setGuid(guid);/*from w ww  .  j a va  2  s.  c  o  m*/
        if (names != null) {
            searchRequest.setNames(new HashSet<>(names));
        }
        searchRequest.setTimestampStart(timestampSt);
        searchRequest.setTimestampEnd(timestampEnd);
        searchRequest.setStatus(status);
        return searchRequest;
    }).map(searchRequest -> {
        CompletableFuture<Response> future = new CompletableFuture<>();
        rpcClient.call(
                Request.newBuilder().withBody(searchRequest).withPartitionKey(searchRequest.getGuid()).build(),
                new ResponseConsumer(future));
        return future;
    }).collect(Collectors.toList());

    // List<CompletableFuture<Response>> => CompletableFuture<List<DeviceCommand>>
    return CompletableFuture.allOf(futures.toArray(new CompletableFuture[futures.size()]))
            .thenApply(v -> futures.stream().map(CompletableFuture::join) // List<CompletableFuture<Response>> => CompletableFuture<List<Response>>
                    .map(r -> ((CommandSearchResponse) r.getBody()).getCommands()) // CompletableFuture<List<Response>> => CompletableFuture<List<List<DeviceCommand>>>
                    .flatMap(Collection::stream) // CompletableFuture<List<List<DeviceCommand>>> => CompletableFuture<List<DeviceCommand>>
                    .collect(Collectors.toList()));
}

From source file:com.microsoft.azure.servicebus.samples.deadletterqueue.DeadletterQueue.java

CompletableFuture<Void> sendMessagesAsync(IMessageSender sendClient, int maxMessages) {
    List<HashMap<String, String>> data = GSON.fromJson("[" + "{'name' = 'Einstein', 'firstName' = 'Albert'},"
            + "{'name' = 'Heisenberg', 'firstName' = 'Werner'}," + "{'name' = 'Curie', 'firstName' = 'Marie'},"
            + "{'name' = 'Hawking', 'firstName' = 'Steven'}," + "{'name' = 'Newton', 'firstName' = 'Isaac'},"
            + "{'name' = 'Bohr', 'firstName' = 'Niels'}," + "{'name' = 'Faraday', 'firstName' = 'Michael'},"
            + "{'name' = 'Galilei', 'firstName' = 'Galileo'},"
            + "{'name' = 'Kepler', 'firstName' = 'Johannes'},"
            + "{'name' = 'Kopernikus', 'firstName' = 'Nikolaus'}" + "]",
            new TypeToken<List<HashMap<String, String>>>() {
            }.getType());//from  w w  w.  ja va 2s  .  c o  m

    List<CompletableFuture> tasks = new ArrayList<>();
    for (int i = 0; i < Math.min(data.size(), maxMessages); i++) {
        final String messageId = Integer.toString(i);
        Message message = new Message(GSON.toJson(data.get(i), Map.class).getBytes(UTF_8));
        message.setContentType("application/json");
        message.setLabel(i % 2 == 0 ? "Scientist" : "Physicist");
        message.setMessageId(messageId);
        message.setTimeToLive(Duration.ofMinutes(2));
        System.out.printf("Message sending: Id = %s\n", message.getMessageId());
        tasks.add(sendClient.sendAsync(message).thenRunAsync(() -> {
            System.out.printf("\tMessage acknowledged: Id = %s\n", message.getMessageId());
        }));
    }
    return CompletableFuture.allOf(tasks.toArray(new CompletableFuture<?>[tasks.size()]));
}

From source file:com.microsoft.azure.servicebus.samples.topicsgettingstarted.TopicsGettingStarted.java

CompletableFuture<Void> sendMessagesAsync(TopicClient sendClient) {
    List<HashMap<String, String>> data = GSON.fromJson("[" + "{'name' = 'Einstein', 'firstName' = 'Albert'},"
            + "{'name' = 'Heisenberg', 'firstName' = 'Werner'}," + "{'name' = 'Curie', 'firstName' = 'Marie'},"
            + "{'name' = 'Hawking', 'firstName' = 'Steven'}," + "{'name' = 'Newton', 'firstName' = 'Isaac'},"
            + "{'name' = 'Bohr', 'firstName' = 'Niels'}," + "{'name' = 'Faraday', 'firstName' = 'Michael'},"
            + "{'name' = 'Galilei', 'firstName' = 'Galileo'},"
            + "{'name' = 'Kepler', 'firstName' = 'Johannes'},"
            + "{'name' = 'Kopernikus', 'firstName' = 'Nikolaus'}" + "]",
            new TypeToken<List<HashMap<String, String>>>() {
            }.getType());//from   w  w w. j a  va  2  s  . c  om

    List<CompletableFuture> tasks = new ArrayList<>();
    for (int i = 0; i < data.size(); i++) {
        final String messageId = Integer.toString(i);
        Message message = new Message(GSON.toJson(data.get(i), Map.class).getBytes(UTF_8));
        message.setContentType("application/json");
        message.setLabel("Scientist");
        message.setMessageId(messageId);
        message.setTimeToLive(Duration.ofMinutes(2));
        System.out.printf("Message sending: Id = %s\n", message.getMessageId());
        tasks.add(sendClient.sendAsync(message).thenRunAsync(() -> {
            System.out.printf("\tMessage acknowledged: Id = %s\n", message.getMessageId());
        }));
    }
    return CompletableFuture.allOf(tasks.toArray(new CompletableFuture<?>[tasks.size()]));
}

From source file:com.devicehive.service.DeviceNotificationService.java

@SuppressWarnings("unchecked")
public CompletableFuture<List<DeviceNotification>> find(Set<String> guids, Set<String> names, Date timestampSt,
        Date timestampEnd) {//  www  .  j  a  v  a2 s  . co m
    List<CompletableFuture<Response>> futures = guids.stream().map(guid -> {
        NotificationSearchRequest searchRequest = new NotificationSearchRequest();
        searchRequest.setGuid(guid);
        searchRequest.setNames(names);
        searchRequest.setTimestampStart(timestampSt);
        searchRequest.setTimestampEnd(timestampEnd);
        return searchRequest;
    }).map(searchRequest -> {
        CompletableFuture<Response> future = new CompletableFuture<>();
        rpcClient.call(
                Request.newBuilder().withBody(searchRequest).withPartitionKey(searchRequest.getGuid()).build(),
                new ResponseConsumer(future));
        return future;
    }).collect(Collectors.toList());

    // List<CompletableFuture<Response>> => CompletableFuture<List<DeviceNotification>>
    return CompletableFuture.allOf(futures.toArray(new CompletableFuture[futures.size()]))
            .thenApply(v -> futures.stream().map(CompletableFuture::join) // List<CompletableFuture<Response>> => CompletableFuture<List<Response>>
                    .map(r -> r.getBody().cast(NotificationSearchResponse.class).getNotifications()) // CompletableFuture<List<Response>> => CompletableFuture<List<List<DeviceNotification>>>
                    .flatMap(Collection::stream) // CompletableFuture<List<List<DeviceNotification>>> => CompletableFuture<List<DeviceNotification>>
                    .collect(Collectors.toList()));
}

From source file:com.spotify.scio.util.RemoteFileUtil.java

/**
 * Download a batch of remote {@link URI}s in parallel.
 * @return {@link Path}s to the downloaded local files.
 *//*from w  w w.j av a2s .c om*/
public List<Path> download(List<URI> srcs) {
    // Blocks on globally shared ConcurrentMap with concurrency determined by CONCURRENCY_LEVEL
    synchronized (paths) {
        List<URI> missing = srcs.stream().filter(src -> !paths.containsKey(src)).collect(Collectors.toList());

        List<CompletableFuture<Path>> futures = missing.stream()
                .map(uri -> CompletableFuture.supplyAsync(() -> downloadImpl(uri), executorService))
                .collect(Collectors.toList());

        try {
            CompletableFuture.allOf(futures.toArray(new CompletableFuture[futures.size()])).get();
            List<Path> result = futures.stream().map(CompletableFuture::join).collect(Collectors.toList());

            Iterator<URI> i = missing.iterator();
            Iterator<Path> j = result.iterator();
            while (i.hasNext() && j.hasNext()) {
                paths.put(i.next(), j.next());
            }
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            throw new RuntimeException("Interrupted while executing batch download request", e);
        } catch (ExecutionException e) {
            throw new RuntimeException("Error executing batch download request", e);
        }
    }

    return srcs.stream().map(paths::get).collect(Collectors.toList());
}