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.activity.initialization.ActivityInitialization.java

private void loadController(Class<?> controllerClass) {
    JavaFXExecutorService javaFXExecutor = controller.getJavaFXExecutor();
    ExecutorService executorService;
    if (shouldLoadInFXThread(controllerClass)) {
        executorService = javaFXExecutor;
    } else {/*  ww  w .  java2s.c  o  m*/
        executorService = controller.getExecutorService();
    }

    if (!preloads.containsKey(controllerClass)) {
        CompletableFuture<DefaultLoader<Node, Object>> loaderFuture = CompletableFuture
                .supplyAsync(getDefaultLoaderSupplier(controllerClass), executorService).exceptionally((t) -> {
                    if (t.getCause() instanceof RuntimeException
                            && t.getCause().getCause() instanceof LoadException) {
                        currentlyLoadedControllers.get().forEach(eventBus::unregister);
                        currentlyLoadedControllers.get().clear();
                        log.info("Last load of {} failed, will try again in JavaFX Thread",
                                new DefaultLoader<>(controllerClass).getFxmlFile());
                        return javaFXExecutor
                                .invokeInJavaFXThread(() -> getDefaultLoaderSupplier(controllerClass).get());
                    }
                    throw new RuntimeException(t);
                });

        preloads.put(controllerClass, loaderFuture);
    }
}

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

@BodyParser.Of(BodyParser.Json.class)
public final CompletionStage<Result> addGraphVersion() {
    return CompletableFuture.supplyAsync(() -> {
        JsonNode json = request().body().asJson();
        List<Long> parentIds = GroundUtils.getListFromJson(json, "parentIds");
        ((ObjectNode) json).remove("parentIds");
        GraphVersion graphVersion = Json.fromJson(json, GraphVersion.class);

        try {/*w w  w.  ja  v a2 s . c  o  m*/
            graphVersion = this.postgresGraphVersionDao.create(graphVersion, parentIds);
        } catch (GroundException e) {
            throw new CompletionException(e);
        }
        return Json.toJson(graphVersion);
    }, PostgresUtils.getDbSourceHttpContext(actorSystem)).thenApply(Results::ok)
            .exceptionally(e -> GroundUtils.handleException(e, request()));
}

From source file:com.gitpitch.services.OfflineService.java

public CountDownLatch fetchZip(PitchParams pp, Optional<SlideshowModel> ssmo) {

    log.debug("fetchZip: pp={}, ssmo.isPresent={}", pp, ssmo.isPresent());

    final String zipKey = MarkdownModel.genKey(pp);

    CountDownLatch freshLatch = new CountDownLatch(1);
    CountDownLatch activeLatch = zipLatchMap.putIfAbsent(zipKey, freshLatch);

    if (activeLatch != null) {
        /*/*from  w w w.  j a v a 2  s  .  c  o  m*/
         * A non-null activeLatch implies a fetchZip()
         * operation is already in progress for the current
         * /{user}/{repo}?b={branch}.
         */
        log.debug("fetchZip: pp={}, already in progress, " + "returning existing activeLatch={}", pp,
                activeLatch);
        return activeLatch;

    } else {

        CompletableFuture<Void> syncFuture = CompletableFuture.supplyAsync(() -> {

            Path branchPath = diskService.ensure(pp);
            int zipStatus = generateZip(pp, ssmo);

            if (zipStatus != STATUS_OK) {
                log.warn("fetchZip: pp={}, fetch status={}", pp, zipStatus);
            }

            /*
             * Current operation completed, so remove latch associated
             * with operation from zipLatchMap to permit future
             * operations on this /{user}/{repo}?b={branch}.
             */
            releaseCountDownLatch(zipLatchMap, zipKey);

            /*
             * Operation completed, valid result cached, no return required.
             */
            return null;

        }, backEndThreads.POOL).handle((result, error) -> {

            if (error != null) {

                log.warn("fetchZip: pp={}, fetch error={}", pp, error);
                releaseCountDownLatch(zipLatchMap, zipKey);
            }

            return null;
        });

        return freshLatch;
    }

}

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

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

        List<Long> parentIds = GroundUtils.getListFromJson(json, "parentIds");
        ((ObjectNode) json).remove("parentIds");

        StructureVersion structureVersion = Json.fromJson(json, StructureVersion.class);

        try {/*from   w  w w. ja  v a 2 s . com*/
            structureVersion = this.postgresStructureVersionDao.create(structureVersion, parentIds);
        } catch (GroundException e) {
            throw new CompletionException(e);
        }
        return Json.toJson(structureVersion);
    }, PostgresUtils.getDbSourceHttpContext(this.actorSystem)).thenApply(Results::created)
            .exceptionally(e -> GroundUtils.handleException(e, request()));
}

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

@CrossOrigin(maxAge = 3600)
@RequestMapping(method = RequestMethod.DELETE, value = "/cart/{cartId}/{itemId}/{quantity}", produces = MediaType.APPLICATION_JSON_VALUE)
@ApiOperation("Delete from the user's cart")
@ResponseBody//from   ww  w. j a v  a  2 s  .  co m
public ShoppingCart deleteFromCart(@PathVariable String cartId, @PathVariable String itemId,
        @PathVariable int quantity) throws ExecutionException, InterruptedException {

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

    return cart.get();
}

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

public void preload(Collection<AsciiDocContent> load) {
    ActivityExecutor executorService = controller.getExecutorService();
    JavaFXExecutorService javaFXExecutor = controller.getJavaFXExecutor();
    load.forEach(t -> {/*from w  w w  .  j a va 2s  .c om*/
        CompletableFuture<Pair<String, String>> completableFuture = CompletableFuture
                .supplyAsync(() -> preProcess(t.getAdoc()), executorService)//
                .thenApply(desc -> {
                    if (desc == null || desc.trim().isEmpty()) {
                        return "";
                    } else {
                        return parser.parse(desc);
                    }
                })//
                .thenApply(html -> Pair.of(t.getIdentifier(), html));
        completableFuture.thenApply(pair -> {
            preloaded.put(pair.getKey(), pair.getValue());
            return pair;
        }).thenAcceptAsync(pair -> {
            if (currentIdentifier.getValueSafe().equals(pair.getKey())) {
                String html = pair.getValue();
                currentHtml.set(html);
                webView.getEngine().loadContent(html);
            }
        }, javaFXExecutor)//
                .exceptionally(e -> {
                    log.error("Could not parse adoc", e);
                    return null;
                });
    });
}

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

@CrossOrigin(maxAge = 3600)
@RequestMapping(method = RequestMethod.POST, value = "/cart/{cartId}/{itemId}/{quantity}", produces = MediaType.APPLICATION_JSON_VALUE)
@ApiOperation("Add to user's cart")
@ResponseBody// w  w  w. j  a  v  a  2 s  . c  o  m
public ShoppingCart addToCart(@PathVariable String cartId, @PathVariable String itemId,
        @PathVariable int quantity) throws ExecutionException, InterruptedException {

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

    return cart.get();
}

From source file:com.teradata.benchto.driver.listeners.BenchmarkServiceExecutionListener.java

@Override
public Future<?> benchmarkFinished(BenchmarkExecutionResult benchmarkExecutionResult) {
    return CompletableFuture.supplyAsync(() -> getMeasurements(benchmarkExecutionResult), taskExecutor::execute)
            .thenCompose(future -> future).thenApply(measurements -> {
                return new FinishRequestBuilder()
                        .withStatus(benchmarkExecutionResult.isSuccessful() ? ENDED : FAILED)
                        .withEndTime(benchmarkExecutionResult.getUtcEnd().toInstant())
                        .addMeasurements(measurements).build();
            }).thenAccept(request -> {
                benchmarkServiceClient.finishBenchmark(benchmarkExecutionResult.getBenchmark().getUniqueName(),
                        benchmarkExecutionResult.getBenchmark().getSequenceId(), request);
            });//from w ww  .ja v a  2s .co  m
}

From source file:grakn.core.deduplicator.AttributeDeduplicatorE2E.java

private static void insertNameShuffled(GraknClient.Session session, int nameCount, int duplicatePerNameCount,
        ExecutorService executorService) throws ExecutionException, InterruptedException {

    List<String> duplicatedNames = new ArrayList<>();
    for (int i = 0; i < nameCount; ++i) {
        for (int j = 0; j < duplicatePerNameCount; ++j) {
            String name = "lorem ipsum dolor sit amet " + i;
            duplicatedNames.add(name);//from  w  w  w.  j a v  a2 s.  com
        }
    }

    Collections.shuffle(duplicatedNames, new Random(1));

    List<CompletableFuture<Void>> asyncInsertions = new ArrayList<>();
    for (String name : duplicatedNames) {
        CompletableFuture<Void> asyncInsert = CompletableFuture.supplyAsync(() -> {
            try (GraknClient.Transaction tx = session.transaction().write()) {
                List<ConceptMap> answer = tx.execute(Graql.insert(var().isa("name").val(name)));
                tx.commit();
            }
            return null;
        }, executorService);
        asyncInsertions.add(asyncInsert);
    }

    CompletableFuture.allOf(asyncInsertions.toArray(new CompletableFuture[] {})).get();
}

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

/**
 * Returns a CompletableFuture that retrieves the availability of an item from the Inventory service.
 *
 * @param itemId The item to query/*from   w  w  w  .  ja  v  a  2 s  .c o  m*/
 * @return A completablefuture for getting the Inventory for this item
 */
private CompletableFuture<Inventory> _getInventory(String itemId) {
    return CompletableFuture.supplyAsync(
            () -> feignClientFactory.getInventoryClient().getService().getAvailability(itemId), es);
}