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

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

Introduction

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

Prototype

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

Source Link

Document

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

Usage

From source file:org.robotninjas.concurrent.FluentFutures.java

/**
 *
 * @param futures/*w  w w.  j  a v  a 2 s .co m*/
 * @param <Y>
 * @return
 */
public static <Y> FluentFuture<List<Y>> from(Iterable<ListenableFuture<Y>> futures) {
    return new FluentDecorator<>(Futures.allAsList(futures));
}

From source file:org.opendaylight.netconf.topology.impl.OnlySuccessStateAggregator.java

@Override
public ListenableFuture<Node> combineUpdateAttempts(List<ListenableFuture<Node>> stateFutures) {
    final SettableFuture<Node> future = SettableFuture.create();
    final ListenableFuture<List<Node>> allAsList = Futures.allAsList(stateFutures);
    Futures.addCallback(allAsList, new FutureCallback<List<Node>>() {
        @Override/*w  w  w .ja v a 2  s  . c o  m*/
        public void onSuccess(List<Node> result) {
            for (int i = 0; i < result.size() - 1; i++) {
                if (!result.get(i).equals(result.get(i + 1))) {
                    future.setException(new IllegalStateException("Update futures have different result"));
                }
            }
            future.set(result.get(0));
        }

        @Override
        public void onFailure(Throwable t) {
            LOG.error("One of the combined update attempts failed {}", t);
            future.setException(t);
        }
    });
    return future;
}

From source file:org.opendaylight.netconf.topology.impl.NetconfNodeOperationalDataAggregator.java

@Override
public ListenableFuture<Node> combineCreateAttempts(final List<ListenableFuture<Node>> stateFutures) {
    final SettableFuture<Node> future = SettableFuture.create();
    final ListenableFuture<List<Node>> allAsList = Futures.allAsList(stateFutures);
    Futures.addCallback(allAsList, new FutureCallback<List<Node>>() {
        @Override//from w  w w.  j  a va2  s.  c  o m
        public void onSuccess(final List<Node> result) {
            Node base = null;
            NetconfNode baseAugmentation = null;
            AvailableCapabilities masterCaps = null;
            UnavailableCapabilities unavailableMasterCaps = null;
            final ArrayList<NodeStatus> statusList = new ArrayList<>();
            for (final Node node : result) {
                final NetconfNode netconfNode = node.getAugmentation(NetconfNode.class);
                if (base == null && netconfNode.getConnectionStatus().equals(ConnectionStatus.Connected)) {
                    base = node;
                    baseAugmentation = netconfNode;
                }
                // we need to pull out caps from master, since slave does not go through resolution
                if (masterCaps == null) {
                    masterCaps = netconfNode.getAvailableCapabilities();
                    unavailableMasterCaps = netconfNode.getUnavailableCapabilities();
                }
                if (netconfNode.getAvailableCapabilities().getAvailableCapability().size() > masterCaps
                        .getAvailableCapability().size()) {
                    masterCaps = netconfNode.getAvailableCapabilities();
                    unavailableMasterCaps = netconfNode.getUnavailableCapabilities();
                }
                LOG.debug(netconfNode.toString());
                statusList.addAll(netconfNode.getClusteredConnectionStatus().getNodeStatus());
            }

            if (base == null) {
                base = result.get(0);
                baseAugmentation = result.get(0).getAugmentation(NetconfNode.class);
                LOG.debug("All results {}", result.toString());
            }

            final Node aggregatedNode = new NodeBuilder(base).addAugmentation(NetconfNode.class,
                    new NetconfNodeBuilder(baseAugmentation)
                            .setClusteredConnectionStatus(
                                    new ClusteredConnectionStatusBuilder().setNodeStatus(statusList).build())
                            .setAvailableCapabilities(masterCaps)
                            .setUnavailableCapabilities(unavailableMasterCaps).build())
                    .build();

            future.set(aggregatedNode);
        }

        @Override
        public void onFailure(final Throwable t) {
            LOG.error("One of the combined create attempts failed {}", t);
            future.setException(t);
        }
    });
    return future;
}

From source file:com.facebook.buck.distributed.testutil.DummyArtifactCacheByBuildRule.java

@Override
public void close() throws Exception {
    Futures.allAsList(uploadFutures).get();
}

From source file:com.android.camera.async.Futures2.java

/**
 * Create a new joined future from two existing futures and a joining function
 * that combines the resulting outputs of the previous functions into a single
 * result. The resulting future will fail if any of the dependent futures also
 * fail./*from   ww w  .j av a2s.  c o m*/
 */
public static <T1, T2, TResult> ListenableFuture<TResult> joinAll(final ListenableFuture<T1> f1,
        final ListenableFuture<T2> f2, final AsyncFunction2<T1, T2, TResult> fn) {
    ListenableFuture<?>[] futures = new ListenableFuture<?>[2];

    futures[0] = f1;
    futures[1] = f2;

    // Futures.allAsList is used instead of Futures.successfulAsList because
    // allAsList will propagate the failures instead of null values to the
    // parameters of the supplied function.
    ListenableFuture<List<Object>> result = Futures.allAsList(futures);
    return Futures.transform(result, new AsyncFunction<List<Object>, TResult>() {
        @Override
        public ListenableFuture<TResult> apply(@Nullable List<Object> list) throws Exception {
            T1 value1 = (T1) list.get(0);
            T2 value2 = (T2) list.get(1);

            return fn.apply(value1, value2);
        }
    });
}

From source file:com.facebook.buck.event.listener.HttpArtifactCacheEventListener.java

@Override
public void outputTrace(final BuildId buildId) {
    List<ListenableFuture<Void>> futures = Lists.newArrayList();
    futures.add(fetchRequestLogger.forceFlush());
    futures.add(storeRequestLogger.forceFlush());
    try {// w  ww .ja  v a 2s  .c  o  m
        Futures.allAsList(futures).get(TEAR_DOWN_SECONDS, TimeUnit.SECONDS);
    } catch (InterruptedException e) {
        LOG.warn(e, "Flushing of logs was interrupted.");
    } catch (ExecutionException e) {
        LOG.warn(e, "Execution of log flushing failed.");
    } catch (TimeoutException e) {
        LOG.warn(e, "Flushing the logs timed out.");
    }
}

From source file:org.opendaylight.toaster.impl.KitchenProvider.java

@Override
public Future<RpcResult<Void>> makeBreakfast(MakeBreakfastInput input) {
    ListenableFuture<RpcResult<Void>> makeEggFuture = makeEgg(input);
    ListenableFuture<RpcResult<Void>> makeToastFuture = makeToast(input);
    ListenableFuture<List<RpcResult<Void>>> combinedFutures = Futures
            .allAsList(ImmutableList.of(makeEggFuture, makeToastFuture));
    return Futures.transform(combinedFutures, new AsyncFunction<List<RpcResult<Void>>, RpcResult<Void>>() {
        @Override/*from   www .j  a  va 2 s  .c om*/
        public ListenableFuture<RpcResult<Void>> apply(List<RpcResult<Void>> input) throws Exception {
            boolean atLeastOneSucceed = false;
            ImmutableList.Builder<RpcError> errorList = ImmutableList.builder();
            for (RpcResult<Void> result : input) {
                if (result.isSuccessful()) {
                    atLeastOneSucceed = true;
                }
                if (result.getErrors() != null) {
                    errorList.addAll(result.getErrors());
                }
            }
            return Futures.immediateFuture(Rpcs.<Void>getRpcResult(atLeastOneSucceed, errorList.build()));
        }
    });
}

From source file:org.robotninjas.concurrent.FluentFutures.java

/**
 *
 * @param futures//from   w w w.j  a  va 2s  . co  m
 * @param executor
 * @param <Y>
 * @return
 */
public static <Y> FluentFuture<List<Y>> from(Iterable<ListenableFuture<Y>> futures, Executor executor) {
    return new FluentDecorator<>(Futures.allAsList(futures), executor);
}

From source file:com.google.gapid.models.ApiContext.java

@Override
protected ListenableFuture<FilteringContext[]> doLoad(Path.Any path) {
    return Futures.transform(Futures.transformAsync(client.get(path), val -> {
        List<ListenableFuture<ApiContext.IdAndContext>> contexts = Lists.newArrayList();
        for (Path.Context ctx : val.getContexts().getListList()) {
            contexts.add(Futures.transform(client.get(Path.Any.newBuilder().setContext(ctx).build()),
                    value -> new IdAndContext(ctx, value.getContext())));
        }/*from  w ww.j a va  2  s .  com*/
        return Futures.allAsList(contexts);
    }), this::unbox);
}

From source file:com.groupon.mesos.util.HttpProtocolSender.java

@Override
public void close() throws IOException {
    if (!closed.getAndSet(true)) {
        // Drain all outstanding requests.
        while (!inFlight.isEmpty()) {
            try {
                // Wait for all outstanding futures to complete
                Futures.allAsList(inFlight.values()).get();
            } catch (final ExecutionException e) {
                LOG.warn(e.getCause(), "While waiting for in flight requests to drain");
            } catch (final InterruptedException e) {
                Thread.currentThread().interrupt();
                return;
            }/*from   w ww  .j  a va2 s  .c  om*/
        }
    }
}