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:acmi.l2.clientmod.l2_version_switcher.Main.java

public static void main(String[] args) {
    if (args.length != 3 && args.length != 4) {
        System.out.println("USAGE: l2_version_switcher.jar host game version <--splash> <filter>");
        System.out.println("EXAMPLE: l2_version_switcher.jar " + L2.NCWEST_HOST + " " + L2.NCWEST_GAME
                + " 1 \"system\\*\"");
        System.out.println(/*from  ww  w . j a v a2s .  c om*/
                "         l2_version_switcher.jar " + L2.PLAYNC_TEST_HOST + " " + L2.PLAYNC_TEST_GAME + " 48");
        System.exit(0);
    }

    List<String> argsList = new ArrayList<>(Arrays.asList(args));
    String host = argsList.get(0);
    String game = argsList.get(1);
    int version = Integer.parseInt(argsList.get(2));
    Helper helper = new Helper(host, game, version);
    boolean available = false;

    try {
        available = helper.isAvailable();
    } catch (IOException e) {
        System.err.print(e.getClass().getSimpleName());
        if (e.getMessage() != null) {
            System.err.print(": " + e.getMessage());
        }

        System.err.println();
    }

    System.out.println(String.format("Version %d available: %b", version, available));
    if (!available) {
        System.exit(0);
    }

    List<FileInfo> fileInfoList = null;
    try {
        fileInfoList = helper.getFileInfoList();
    } catch (IOException e) {
        System.err.println("Couldn\'t get file info map");
        System.exit(1);
    }

    boolean splash = argsList.remove("--splash");
    if (splash) {
        Optional<FileInfo> splashObj = fileInfoList.stream()
                .filter(fi -> fi.getPath().contains("sp_32b_01.bmp")).findAny();
        if (splashObj.isPresent()) {
            try (InputStream is = new FilterInputStream(
                    Util.getUnzipStream(helper.getDownloadStream(splashObj.get().getPath()))) {
                @Override
                public int read() throws IOException {
                    int b = super.read();
                    if (b >= 0)
                        b ^= 0x36;
                    return b;
                }

                @Override
                public int read(byte[] b, int off, int len) throws IOException {
                    int r = super.read(b, off, len);
                    if (r >= 0) {
                        for (int i = 0; i < r; i++)
                            b[off + i] ^= 0x36;
                    }
                    return r;
                }
            }) {
                new DataInputStream(is).readFully(new byte[28]);
                BufferedImage bi = ImageIO.read(is);

                JFrame frame = new JFrame("Lineage 2 [" + version + "] " + splashObj.get().getPath());
                frame.setContentPane(new JComponent() {
                    {
                        setPreferredSize(new Dimension(bi.getWidth(), bi.getHeight()));
                    }

                    @Override
                    protected void paintComponent(Graphics g) {
                        g.drawImage(bi, 0, 0, null);
                    }
                });
                frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            System.out.println("Splash not found");
        }
        return;
    }

    String filter = argsList.size() > 3 ? separatorsToSystem(argsList.get(3)) : null;

    File l2Folder = new File(System.getProperty("user.dir"));
    List<FileInfo> toUpdate = fileInfoList.parallelStream().filter(fi -> {
        String filePath = separatorsToSystem(fi.getPath());

        if (filter != null && !wildcardMatch(filePath, filter, IOCase.INSENSITIVE))
            return false;
        File file = new File(l2Folder, filePath);

        try {
            if (file.exists() && file.length() == fi.getSize() && Util.hashEquals(file, fi.getHash())) {
                System.out.println(filePath + ": OK");
                return false;
            }
        } catch (IOException e) {
            System.out.println(filePath + ": couldn't check hash: " + e);
            return true;
        }

        System.out.println(filePath + ": need update");
        return true;
    }).collect(Collectors.toList());

    List<String> errors = Collections.synchronizedList(new ArrayList<>());
    ExecutorService executor = Executors.newFixedThreadPool(16);
    CompletableFuture[] tasks = toUpdate.stream().map(fi -> CompletableFuture.runAsync(() -> {
        String filePath = separatorsToSystem(fi.getPath());
        File file = new File(l2Folder, filePath);

        File folder = file.getParentFile();
        if (!folder.exists()) {
            if (!folder.mkdirs()) {
                errors.add(filePath + ": couldn't create parent dir");
                return;
            }
        }

        try (InputStream input = Util
                .getUnzipStream(new BufferedInputStream(helper.getDownloadStream(fi.getPath())));
                OutputStream output = new BufferedOutputStream(new FileOutputStream(file))) {
            byte[] buffer = new byte[Math.min(fi.getSize(), 1 << 24)];
            int pos = 0;
            int r;
            while ((r = input.read(buffer, pos, buffer.length - pos)) >= 0) {
                pos += r;
                if (pos == buffer.length) {
                    output.write(buffer, 0, pos);
                    pos = 0;
                }
            }
            if (pos != 0) {
                output.write(buffer, 0, pos);
            }
            System.out.println(filePath + ": OK");
        } catch (IOException e) {
            String msg = filePath + ": FAIL: " + e.getClass().getSimpleName();
            if (e.getMessage() != null) {
                msg += ": " + e.getMessage();
            }
            errors.add(msg);
        }
    }, executor)).toArray(CompletableFuture[]::new);
    CompletableFuture.allOf(tasks).thenRun(() -> {
        for (String err : errors)
            System.err.println(err);
        executor.shutdown();
    });
}

From source file:Main.java

public static <T> CompletableFuture<T> anyOfFutures(List<? extends CompletableFuture<? extends T>> futures) {
    CompletableFuture<T> cf = new CompletableFuture<>();
    CompletableFuture
            .allOf(futures.stream().map(f -> f.thenAccept(cf::complete)).toArray(CompletableFuture<?>[]::new))
            .exceptionally(ex -> {/* w ww . j ava  2  s.c o m*/
                cf.completeExceptionally(ex);
                return null;
            });
    return cf;
}

From source file:Main.java

public static <T> CompletableFuture<List<T>> allOfFutures(
        List<? extends CompletableFuture<? extends T>> futures) {
    List<T> result = new ArrayList<>(futures.size());
    CompletableFuture<List<T>> cf = new CompletableFuture<>();
    CompletableFuture
            .allOf(futures.stream().map(s -> s.thenAccept(result::add)).toArray(CompletableFuture<?>[]::new))
            .exceptionally(ex -> {/*ww  w. j a v a 2s .  c  om*/
                cf.completeExceptionally(ex);
                return null;
            }).thenAccept(v -> cf.complete(result));
    return cf;
}

From source file:Main.java

static public <T> CompletableFuture<List<T>> all(List<CompletableFuture<T>> cf) {
    return CompletableFuture.allOf(cf.toArray(new CompletableFuture[cf.size()]))
            .thenApply(v -> cf.stream().map(CompletableFuture::join).collect(toList()));
}

From source file:Main.java

/**
 * Collect the return values of all the futures provided
 *
 * @param futures/*from w  w  w .j ava 2s.  c om*/
 *            the futures the result is collected from
 * @return a future with the collected results
 */
@SafeVarargs
public static <T> CompletableFuture<List<T>> collect(CompletableFuture<T>... futures) {
    return CompletableFuture.allOf(futures)
            .thenApply(v -> Stream.of(futures).map(f -> f.join()).collect(Collectors.toList()));
}

From source file:Main.java

/**
 * Collect the return value of all the futures and apply the transformation
 * method on it//  w  w w  .  j  a v a  2s  .  c  om
 *
 * @param transformer
 *            the transformation to apply
 * @param futures
 *            the future
 * @return a future with the collected results
 */
@SafeVarargs
public static <T, O> CompletableFuture<List<T>> collect(Function<O, T> transformer,
        CompletableFuture<O>... futures) {
    return CompletableFuture.allOf(futures).thenApply(
            v -> Stream.of(futures).map(f -> f.join()).map(transformer::apply).collect(Collectors.toList()));
}

From source file:com.microsoft.azure.servicebus.samples.receiveloop.ReceiveLoop.java

public void run(String connectionString) throws Exception {

    QueueClient sendClient;/* w  ww  .  j av  a  2s  .  com*/
    IMessageReceiver receiver;
    CompletableFuture receiveTask;

    // Create a QueueClient instance using the connection string builder
    // We set the receive mode to "PeekLock", meaning the message is delivered
    // under a lock and must be acknowledged ("completed") to be removed from the queue

    sendClient = new QueueClient(new ConnectionStringBuilder(connectionString, "BasicQueue"),
            ReceiveMode.PEEKLOCK);
    this.sendMessagesAsync(sendClient).thenRunAsync(() -> sendClient.closeAsync());

    receiver = ClientFactory.createMessageReceiverFromConnectionStringBuilder(
            new ConnectionStringBuilder(connectionString, "BasicQueue"), ReceiveMode.PEEKLOCK);
    receiveTask = this.receiveMessagesAsync(receiver);

    waitForEnter(10);

    receiveTask.cancel(true);
    receiver.close();

    CompletableFuture.allOf(receiveTask.exceptionally(t -> {
        if (t instanceof CancellationException) {
            return null;
        }
        throw new RuntimeException((Throwable) t);
    })).join();

}

From source file:com.microsoft.azure.servicebus.samples.prefetch.Prefetch.java

long sendAndReceiveMessages(IMessageSender sender, IMessageReceiver receiver, int messageCount)
        throws Exception {
    // Now we can start sending messages.
    Random rnd = new Random();
    byte[] mockPayload = new byte[100]; // 100 random-byte payload

    rnd.nextBytes(mockPayload);/*from w ww.  java2s  .  co  m*/

    System.out.printf("\nSending %d messages to the queue\n", messageCount);
    ArrayList<CompletableFuture<Void>> sendOps = new ArrayList<>();
    for (int i = 0; i < messageCount; i++) {
        IMessage message = new Message(mockPayload);
        message.setTimeToLive(Duration.ofMinutes(5));
        sendOps.add(sender.sendAsync(message));
    }
    CompletableFuture.allOf(sendOps.toArray(new CompletableFuture<?>[sendOps.size()])).join();

    System.out.printf("Send completed\n");

    // Receive the messages
    System.out.printf("Receiving messages...\n");

    // Start stopwatch
    Stopwatch stopWatch = Stopwatch.createStarted();

    IMessage receivedMessage = receiver.receive(Duration.ofSeconds(5));
    while (receivedMessage != null) {
        // here's where you'd do any work

        // complete (round trips)
        receiver.complete(receivedMessage.getLockToken());

        if (--messageCount <= 0)
            break;

        // now get the next message
        receivedMessage = receiver.receive(Duration.ofSeconds(5));
    }
    // Stop the stopwatch
    stopWatch.stop();

    System.out.printf("Receive completed\n");

    long timeTaken = stopWatch.elapsed(TimeUnit.MILLISECONDS);
    System.out.printf("Time to receive and complete all messages = %d milliseconds\n", timeTaken);

    return timeTaken;
}

From source file:com.redhat.coolstore.api_gateway.ApiGatewayController.java

/**
 * This /api REST endpoint uses Java 8 concurrency to call two backend services to construct the result
 *
 * @return the list//from w ww . j a  v a2 s . co  m
 */
@CrossOrigin(maxAge = 3600)
@RequestMapping(method = RequestMethod.GET, value = "/products", produces = MediaType.APPLICATION_JSON_VALUE)
@ApiOperation("Get a list of products")
@ResponseBody
public List<Product> list() throws ExecutionException, InterruptedException {

    final CompletableFuture<List<Product>> productList = CompletableFuture
            .supplyAsync(() -> feignClientFactory.getPricingClient().getService().getProducts(), es);

    return productList.thenCompose((List<Product> products) -> {

        List<CompletableFuture<Product>> all = products.stream()
                .map(p -> productList.thenCombine(_getInventory(p.itemId), (pl, a) -> {
                    p.availability = a;
                    return p;
                })).collect(Collectors.toList());

        return CompletableFuture.allOf(all.toArray(new CompletableFuture[all.size()]))
                .thenApply(v -> all.stream().map(CompletableFuture::join).collect(Collectors.toList()));
    }).get();

}

From source file:io.fabric8.kubeflix.examples.loanbroker.broker.BrokerController.java

@RequestMapping("/quote")
public List<Quote> quote(@RequestParam("ssn") Long ssn, @RequestParam("amount") Double amount,
        @RequestParam("duration") Integer duration)
        throws InterruptedException, ExecutionException, TimeoutException {
    HystrixRequestContext context = HystrixRequestContext.initializeContext();
    try {/*from   w  ww.  ja v  a2s.  c  om*/
        if (async) {
            //Broadcast requests async
            List<CompletableFuture<Quote>> futures = client.services()
                    .withLabel(PROJECT_NAME, LOADBALANCER_BANK).list().getItems().stream()
                    .map(s -> this.requestQuoteAsync(s, ssn, amount, duration)).collect(Collectors.toList());

            //Collect the results
            CompletableFuture<List<Quote>> result = CompletableFuture
                    .allOf(futures.toArray(new CompletableFuture[futures.size()]))
                    .thenApply(v -> futures.stream().map(CompletableFuture::join).collect(Collectors.toList()));

            return result.get(15, TimeUnit.SECONDS);
        }

        return client.services().withLabel(PROJECT_NAME, LOADBALANCER_BANK).list().getItems().stream()
                .map(s -> this.requestQuote(s, ssn, amount, duration)).collect(Collectors.toList());
    } finally {
        context.shutdown();
    }
}