Example usage for com.google.common.util.concurrent Futures successfulAsList

List of usage examples for com.google.common.util.concurrent Futures successfulAsList

Introduction

In this page you can find the example usage for com.google.common.util.concurrent Futures successfulAsList.

Prototype

@Beta
@CheckReturnValue
public static <V> ListenableFuture<List<V>> successfulAsList(
        Iterable<? extends ListenableFuture<? extends V>> futures) 

Source Link

Document

Creates a new ListenableFuture whose value is a list containing the values of all its successful input futures.

Usage

From source file:org.immutables.eventual.CompletedModule.java

static ListenableFuture<Module> from(Injector injectingFutures, CompletionCriteria criteria) {
    final LinkedHashMap<Key<?>, Key<?>> keyMapping = mapUnfutureKeys(injectingFutures);
    List<ListenableFuture<?>> listOfFutures = getFutureInstances(keyMapping.keySet(), injectingFutures);

    ListenableFuture<List<Object>> futureOfList = criteria == CompletionCriteria.SUCCESSFUL
            ? Futures.successfulAsList(listOfFutures)
            : Futures.allAsList(listOfFutures);

    return Futures.transform(futureOfList, new Function<List<Object>, Module>() {
        Key<?>[] keys = Iterables.toArray(keyMapping.values(), Key.class);

        @Override//from   w w w.  ja  v a 2s  . c  o m
        public Module apply(List<Object> instances) {
            return new CompletedModule(keys, instances.toArray());
        }
    }, MoreExecutors.directExecutor());
}

From source file:org.apache.phoenix.hbase.index.parallel.WaitForCompletionTaskRunner.java

@Override
public <R> ListenableFuture<List<R>> submitTasks(List<ListenableFuture<R>> futures) {
    return Futures.successfulAsList(futures);
}

From source file:org.opendaylight.openflowplugin.impl.services.FlowService.java

ListenableFuture<RpcResult<O>> processFlowModInputBuilders(final List<FlowModInputBuilder> ofFlowModInputs) {
    final List<ListenableFuture<RpcResult<O>>> partialFutures = new ArrayList<>(ofFlowModInputs.size());

    for (final FlowModInputBuilder flowModInputBuilder : ofFlowModInputs) {
        partialFutures.add(handleServiceCall(flowModInputBuilder));
    }/*from www .  ja  v  a2s .  c  om*/

    final ListenableFuture<List<RpcResult<O>>> allFutures = Futures.successfulAsList(partialFutures);
    final SettableFuture<RpcResult<O>> finalFuture = SettableFuture.create();
    Futures.addCallback(allFutures, new FutureCallback<List<RpcResult<O>>>() {
        @Override
        public void onSuccess(final List<RpcResult<O>> results) {
            final ArrayList<RpcError> errors = new ArrayList();
            for (RpcResult<O> flowModResult : results) {
                if (flowModResult == null) {
                    errors.add(RpcResultBuilder.newError(RpcError.ErrorType.PROTOCOL,
                            OFConstants.APPLICATION_TAG, "unexpected flowMod result (null) occurred"));
                } else if (!flowModResult.isSuccessful()) {
                    errors.addAll(flowModResult.getErrors());
                }
            }

            final RpcResultBuilder<O> rpcResultBuilder;
            if (errors.isEmpty()) {
                rpcResultBuilder = RpcResultBuilder.success();
            } else {
                rpcResultBuilder = RpcResultBuilder.<O>failed().withRpcErrors(errors);
            }

            finalFuture.set(rpcResultBuilder.build());
        }

        @Override
        public void onFailure(final Throwable t) {
            RpcResultBuilder<O> rpcResultBuilder = RpcResultBuilder.failed();
            finalFuture.set(rpcResultBuilder.build());
        }
    });

    return finalFuture;
}

From source file:com.github.nethad.clustermeister.example.fractals.ComputeMandelbrotAsync.java

public void computePicture(final FractalConfiguration config) {
    try {//from  w ww. ja v  a  2 s .  c o  m
        if (clustermeister == null) {
            clustermeister = ClustermeisterFactory.create();
        }
        int nbTask = config.bsize;
        logger.info("Executing " + nbTask + " tasks");

        Map<String, Object> jobData = new HashMap<String, Object>();
        jobData.put("config", config);

        Job<MandelbrotResult> job = JobFactory.create("Clustermeister Mandelbrot", jobData);

        newImage(config);

        for (int i = 0; i < nbTask; i++) {
            job.addTask(new MandelbrotCMTask(i, config));
        }

        long start = System.currentTimeMillis();

        //            List<MandelbrotResult> results = clustermeister.executeJob(job);
        final List<ListenableFuture<MandelbrotResult>> futures = clustermeister.executeJobAsyncTasks(job);
        final FutureCallback<MandelbrotResult> callback = new FutureCallback<MandelbrotResult>() {
            public void onSuccess(MandelbrotResult result) {
                processPictureLine(result, config);
                //                    logger.info("process line {}", result.getRow());
            }

            public void onFailure(Throwable t) {
                logger.warn("Parts of the picture could not be computed.", t);
            }
        };

        for (ListenableFuture<MandelbrotResult> future : futures) {
            Futures.addCallback(future, callback);
        }

        Futures.successfulAsList(futures).get(); // wait for all jobs to be finished

        long elapsed = System.currentTimeMillis() - start;
        logger.info("Computation performed in " + StringUtils.toStringDuration(elapsed));

        //            generateMandelbrotImage(results, config);

        refreshImage();

    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:org.springframework.integration.samples.helloworld.HelloService.java

public void doGuavaDownloadWithChainedThreads(final URL url) throws IOException {
    ListeningExecutorService service = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(10));
    List<ListenableFuture<String>> calls = new ArrayList<ListenableFuture<String>>();
    while (calls.size() < 5) {
        com.google.common.util.concurrent.ListenableFuture<String> call = service
                .submit(new Callable<String>() {
                    @Override/*from w  ww.  j av  a  2 s . c o  m*/
                    public String call() throws Exception {
                        try (InputStream input = url.openStream()) {
                            return IOUtils.toString(input, StandardCharsets.UTF_8);
                        }
                    }
                });
        calls.add(call);
    }

    ListenableFuture<List<String>> goodCalls = Futures.successfulAsList(calls);
    Futures.addCallback(goodCalls, new FutureCallback<List<String>>() {
        @Override
        public void onSuccess(List<String> strings) {
            System.out.print("Successful call");
        }

        @Override
        public void onFailure(Throwable throwable) {
            System.err.println("Problems");
        }
    });

}

From source file:com.google.gerrit.server.index.account.AllAccountsIndexer.java

private SiteIndexer.Result reindexAccounts(AccountIndex index, List<Account.Id> ids, ProgressMonitor progress) {
    progress.beginTask("Reindexing accounts", ids.size());
    List<ListenableFuture<?>> futures = new ArrayList<>(ids.size());
    AtomicBoolean ok = new AtomicBoolean(true);
    AtomicInteger done = new AtomicInteger();
    AtomicInteger failed = new AtomicInteger();
    Stopwatch sw = Stopwatch.createStarted();
    for (Account.Id id : ids) {
        String desc = "account " + id;
        ListenableFuture<?> future = executor.submit(() -> {
            try {
                accountCache.evict(id);/*  w ww .  jav  a  2 s. c  om*/
                index.replace(accountCache.get(id));
                verboseWriter.println("Reindexed " + desc);
                done.incrementAndGet();
            } catch (Exception e) {
                failed.incrementAndGet();
                throw e;
            }
            return null;
        });
        addErrorListener(future, desc, progress, ok);
        futures.add(future);
    }

    try {
        Futures.successfulAsList(futures).get();
    } catch (ExecutionException | InterruptedException e) {
        log.error("Error waiting on account futures", e);
        return new SiteIndexer.Result(sw, false, 0, 0);
    }

    progress.endTask();
    return new SiteIndexer.Result(sw, ok.get(), done.get(), failed.get());
}

From source file:org.glassfish.jersey.examples.rx.agent.ListenableFutureAgentResource.java

@GET
@ManagedAsync//w w  w .j  a  va2  s  .  c o m
public void observable(@Suspended final AsyncResponse async) {
    final long time = System.nanoTime();
    final AgentResponse response = new AgentResponse();

    // Fallback.
    Futures.addCallback(Futures.successfulAsList(Arrays.asList(visited(response), recommended(response))),
            new FutureCallback<List<AgentResponse>>() {
                @Override
                public void onSuccess(final List<AgentResponse> result) {
                    response.setProcessingTime((System.nanoTime() - time) / 1000000);
                    async.resume(response);
                }

                @Override
                public void onFailure(final Throwable t) {
                    async.resume(t);
                }
            });
}

From source file:org.opendaylight.protocol.bgp.openconfig.impl.moduleconfig.TableTypesFunction.java

@Override
public ListenableFuture<List<T>> apply(final List<AfiSafi> afiSafis) {
    final ListenableFuture<Optional<Service>> readFuture = configModuleWriter
            .readConfigService(new ServiceKey(BgpTableType.class), rTx);
    return Futures.transform(readFuture, new AsyncFunction<Optional<Service>, List<T>>() {

        @Override//from w  ww  . j a va2 s .c  o  m
        public ListenableFuture<List<T>> apply(final Optional<Service> maybeService) {
            if (maybeService.isPresent()) {
                final Service service = maybeService.get();
                final List<ListenableFuture<Optional<Module>>> modulesFuture = new ArrayList<>();
                final Map<String, String> moduleNameToService = new HashMap<>();
                for (final Instance instance : service.getInstance()) {
                    final String moduleName = OpenConfigUtil.getModuleName(instance.getProvider());
                    modulesFuture.add(configModuleWriter
                            .readModuleConfiguration(new ModuleKey(moduleName, BgpTableTypeImpl.class), rTx));
                    moduleNameToService.put(moduleName, instance.getName());
                }
                return Futures.transform(Futures.successfulAsList(modulesFuture),
                        new ModulesToLocalTablesFunction(afiSafis, moduleNameToService));
            }
            return Futures.immediateFailedFuture(
                    new IllegalStateException("No BgpTableType service present in configuration."));
        }

    });
}

From source file:org.thingsboard.server.dao.dashboard.CassandraDashboardInfoDao.java

@Override
public ListenableFuture<List<DashboardInfo>> findDashboardsByTenantIdAndCustomerId(UUID tenantId,
        UUID customerId, TimePageLink pageLink) {
    log.debug("Try to find dashboards by tenantId [{}], customerId[{}] and pageLink [{}]", tenantId, customerId,
            pageLink);/*  w w  w. j  av  a  2s  . co  m*/

    ListenableFuture<List<EntityRelation>> relations = relationDao.findRelations(new TenantId(tenantId),
            new CustomerId(customerId), EntityRelation.CONTAINS_TYPE, RelationTypeGroup.DASHBOARD,
            EntityType.DASHBOARD, pageLink);

    return Futures.transformAsync(relations, input -> {
        List<ListenableFuture<DashboardInfo>> dashboardFutures = new ArrayList<>(input.size());
        for (EntityRelation relation : input) {
            dashboardFutures.add(findByIdAsync(new TenantId(tenantId), relation.getTo().getId()));
        }
        return Futures.successfulAsList(dashboardFutures);
    });
}

From source file:com.google.gerrit.server.index.group.AllGroupsIndexer.java

private SiteIndexer.Result reindexGroups(GroupIndex index, List<AccountGroup.UUID> uuids,
        ProgressMonitor progress) {
    progress.beginTask("Reindexing groups", uuids.size());
    List<ListenableFuture<?>> futures = new ArrayList<>(uuids.size());
    AtomicBoolean ok = new AtomicBoolean(true);
    AtomicInteger done = new AtomicInteger();
    AtomicInteger failed = new AtomicInteger();
    Stopwatch sw = Stopwatch.createStarted();
    for (AccountGroup.UUID uuid : uuids) {
        String desc = "group " + uuid;
        ListenableFuture<?> future = executor.submit(() -> {
            try {
                AccountGroup oldGroup = groupCache.get(uuid);
                if (oldGroup != null) {
                    groupCache.evict(oldGroup);
                }/*from w w  w  .  j a v  a2s  .  co m*/
                index.replace(groupCache.get(uuid));
                verboseWriter.println("Reindexed " + desc);
                done.incrementAndGet();
            } catch (Exception e) {
                failed.incrementAndGet();
                throw e;
            }
            return null;
        });
        addErrorListener(future, desc, progress, ok);
        futures.add(future);
    }

    try {
        Futures.successfulAsList(futures).get();
    } catch (ExecutionException | InterruptedException e) {
        log.error("Error waiting on group futures", e);
        return new SiteIndexer.Result(sw, false, 0, 0);
    }

    progress.endTask();
    return new SiteIndexer.Result(sw, ok.get(), done.get(), failed.get());
}