Example usage for java.util.concurrent CompletableFuture supplyAsync

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

Introduction

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

Prototype

public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier, Executor executor) 

Source Link

Document

Returns a new CompletableFuture that is asynchronously completed by a task running in the given executor with the value obtained by calling the given Supplier.

Usage

From source file:de.ks.text.view.AsciiDocViewer.java

@Override
public void initialize(URL location, ResourceBundle resources) {
    CompletableFuture.supplyAsync(() -> new WebView(), controller.getJavaFXExecutor()).thenAccept(view -> {
        webView = view;/*from   ww w.j a v  a 2  s . c o m*/
        webView.setMinSize(100, 100);
        webView.setPrefSize(Control.USE_COMPUTED_SIZE, Control.USE_COMPUTED_SIZE);
        root.getChildren().add(webView);
    });

    Iterator<AsciiDocPreProcessor> iterator = preProcessorProvider.iterator();
    while (iterator.hasNext()) {
        AsciiDocPreProcessor next = iterator.next();
        addPreProcessor(next);
    }
}

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

@CrossOrigin(maxAge = 3600)
@RequestMapping(method = RequestMethod.POST, value = "/cart/checkout/{cartId}", produces = MediaType.APPLICATION_JSON_VALUE)
@ApiOperation("Cart checkout")
@ResponseBody//from  ww w .ja v a 2  s  .  c o m
public ShoppingCart checkout(@PathVariable String cartId) throws ExecutionException, InterruptedException {

    final CompletableFuture<ShoppingCart> cart = CompletableFuture
            .supplyAsync(() -> feignClientFactory.getCartClient().getService().checkout(cartId), es);

    return cart.get();
}

From source file:edu.berkeley.ground.postgres.controllers.GraphController.java

@BodyParser.Of(BodyParser.Json.class)
public final CompletionStage<Result> addGraph() {
    return CompletableFuture.supplyAsync(() -> {
        JsonNode json = request().body().asJson();
        Graph graph = Json.fromJson(json, Graph.class);

        try {/*from  w w w . j  a v a 2  s. c  om*/
            graph = this.postgresGraphDao.create(graph);
        } catch (GroundException e) {
            throw new CompletionException(e);
        }

        return Json.toJson(graph);
    }, PostgresUtils.getDbSourceHttpContext(actorSystem)).thenApply(Results::created)
            .exceptionally(e -> GroundUtils.handleException(e, request()));
}

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

public CompletableFuture<Quote> requestQuoteAsync(Service service, final Long ssn, final Double amount,
        final Integer duration) {
    return CompletableFuture.supplyAsync(() -> {
        HystrixRequestContext context = null;
        try {//ww  w. ja  v a  2 s  .  c om
            context = HystrixRequestContext.initializeContext();
            return new RequestQuoteFromBankCommand(template, service, ssn, amount, duration).execute();
        } finally {
            if (context != null) {
                context.shutdown();
            }
        }
    }, executorService);
}

From source file:io.pravega.controller.server.ControllerService.java

public CompletableFuture<List<NodeUri>> getControllerServerList() {
    if (cluster == null) {
        return FutureHelpers.failedFuture(new IllegalStateException("Controller cluster not initialized"));
    }/*from   w  w  w  . j av a 2 s  .  c  o m*/

    return CompletableFuture.supplyAsync(() -> {
        try {
            return cluster.getClusterMembers().stream().map(
                    host -> NodeUri.newBuilder().setEndpoint(host.getIpAddr()).setPort(host.getPort()).build())
                    .collect(Collectors.toList());
        } catch (ClusterException e) {
            // cluster implementation throws checked exceptions which cannot be thrown inside completable futures.
            throw Lombok.sneakyThrow(e);
        }
    }, executor);
}

From source file:edu.berkeley.ground.postgres.controllers.StructureController.java

@BodyParser.Of(BodyParser.Json.class)
public final CompletionStage<Result> addStructure() {
    return CompletableFuture.supplyAsync(() -> {
        JsonNode json = request().body().asJson();
        Structure structure = Json.fromJson(json, Structure.class);

        try {/*from   w  w w .ja  v a  2  s .c o m*/
            structure = this.postgresStructureDao.create(structure);
        } catch (GroundException e) {
            throw new CompletionException(e);
        }
        return Json.toJson(structure);
    },

            PostgresUtils.getDbSourceHttpContext(this.actorSystem)).thenApply(Results::created)
            .exceptionally(e -> GroundUtils.handleException(e, request()));
}

From source file:com.ucu.seguridad.views.AbstractFxmlView.java

/**
 * Initializes the view synchronously and invokes the consumer with the created parent Node within the FX UI thread.
 *
 * @param consumer - an object interested in received the {@link Parent} as callback
 *///from  w  ww.  java  2  s.  c  o  m
public void getView(Consumer<Parent> consumer) {
    CompletableFuture.supplyAsync(this::getView, Platform::runLater).thenAccept(consumer);
}

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

@CrossOrigin(maxAge = 3600)
@RequestMapping(method = RequestMethod.GET, value = "/cart/{cartId}", produces = MediaType.APPLICATION_JSON_VALUE)
@ApiOperation("Get the user's cart")
@ResponseBody//from   w  w  w .  j ava2  s.co m
public ShoppingCart getCart(@PathVariable String cartId) throws ExecutionException, InterruptedException {

    final CompletableFuture<ShoppingCart> cart = CompletableFuture
            .supplyAsync(() -> feignClientFactory.getCartClient().getService().getCart(cartId), es);

    return cart.get();
}

From source file:com.twosigma.beakerx.evaluator.BaseEvaluator.java

protected TryResult evaluate(SimpleEvaluationObject seo, Callable<TryResult> callable) {
    try {/*from  ww  w .  j  a  v  a  2s  . co  m*/
        background = CompletableFuture.supplyAsync(() -> {
            try {
                InternalVariable.setValue(seo);
                Future<TryResult> submit = executorService.submit(callable);
                return submit.get();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }, executorBgkService);

        return background.get();

    } catch (Exception e) {
        return TryResult.createError(e.getLocalizedMessage());
    }
}

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 a v  a2s.c  o  m
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());
}