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:com.microsoft.tooling.msservices.helpers.azure.sdk.AzureSDKHelper.java

@NotNull
public static SDKRequestCallback<List<StorageAccount>, StorageManagementClient> getStorageAccounts(
        @NotNull final String subscriptionId, final boolean detailed) {
    return new SDKRequestCallback<List<StorageAccount>, StorageManagementClient>() {
        @NotNull//from www . ja  v a  2s  . c  o m
        @Override
        public List<StorageAccount> execute(@NotNull StorageManagementClient client) throws Throwable {
            List<StorageAccount> saList = new ArrayList<StorageAccount>();
            ArrayList<com.microsoft.windowsazure.management.storage.models.StorageAccount> storageAccounts = getStorageAccounts(
                    client).getStorageAccounts();

            if (storageAccounts == null) {
                return saList;
            }

            List<ListenableFuture<StorageAccount>> saFutureList = new ArrayList<ListenableFuture<StorageAccount>>();

            for (com.microsoft.windowsazure.management.storage.models.StorageAccount storageAccount : storageAccounts) {
                saFutureList.add(getStorageAccountAsync(subscriptionId, client, storageAccount, detailed));
            }

            saList.addAll(Futures.allAsList(saFutureList).get());

            return saList;
        }
    };
}

From source file:com.spotify.futures.FuturesExtra.java

/**
 * <p>Transform a list of futures to a future that returns a joined result of them all.
 * The result can be used to get the joined results and ensures no future that were not part of
 * the join is accessed.</p>/*from   w ww . j a  v a 2s  .c om*/
 * <p>Example</p>
 * <pre>
 * {@code
 * final Future<String> first = Futures.immediateFuture("ok");
 * final Future<Integer> second = Futures.immediateFuture(1);
 * JoinedResults futures = FuturesExtra.join(first, second).get();
 * assertEquals("ok", futures.get(first));
 * assertEquals(1, futures.get(second));
 * }
 * </pre>
 */
public static ListenableFuture<JoinedResults> join(ListenableFuture<?>... inputs) {
    List<? extends ListenableFuture<?>> list = Arrays.asList(inputs);
    return Futures.transform(Futures.allAsList(list), new JoinedResults.Transform(list));
}

From source file:com.google.gerrit.server.git.BatchUpdate.java

private void executeChangeOps(boolean parallel) throws UpdateException, RestApiException {
    ListeningExecutorService executor = parallel ? changeUpdateExector
            : MoreExecutors.newDirectExecutorService();

    List<ChangeTask> tasks = new ArrayList<>(ops.keySet().size());
    try {//  ww w .  ja v a  2 s. c  o  m
        if (notesMigration.commitChangeWrites() && repo != null) {
            // A NoteDb change may have been rebuilt since the repo was originally
            // opened, so make sure we see that.
            repo.scanForRepoChanges();
        }
        if (!ops.isEmpty() && notesMigration.failChangeWrites()) {
            // Fail fast before attempting any writes if changes are read-only, as
            // this is a programmer error.
            throw new OrmException(NoteDbUpdateManager.CHANGES_READ_ONLY);
        }
        List<ListenableFuture<?>> futures = new ArrayList<>(ops.keySet().size());
        for (Map.Entry<Change.Id, Collection<Op>> e : ops.asMap().entrySet()) {
            ChangeTask task = new ChangeTask(e.getKey(), e.getValue(), Thread.currentThread());
            tasks.add(task);
            futures.add(executor.submit(task));
        }
        long startNanos = System.nanoTime();
        Futures.allAsList(futures).get();
        maybeLogSlowUpdate(startNanos, "change");

        if (notesMigration.commitChangeWrites()) {
            startNanos = System.nanoTime();
            executeNoteDbUpdates(tasks);
            maybeLogSlowUpdate(startNanos, "NoteDb");
        }
    } catch (ExecutionException | InterruptedException e) {
        Throwables.propagateIfInstanceOf(e.getCause(), UpdateException.class);
        Throwables.propagateIfInstanceOf(e.getCause(), RestApiException.class);
        throw new UpdateException(e);
    } catch (OrmException | IOException e) {
        throw new UpdateException(e);
    }

    // Reindex changes.
    for (ChangeTask task : tasks) {
        if (task.deleted) {
            indexFutures.add(indexer.deleteAsync(task.id));
        } else if (task.dirty) {
            indexFutures.add(indexer.indexAsync(project, task.id));
        }
    }
}

From source file:org.elasticsearch.test.InternalTestCluster.java

/**
 * Ensures that at least <code>n</code> data nodes are present in the cluster.
 * if more nodes than <code>n</code> are present this method will not
 * stop any of the running nodes.//  ww  w.  java 2s . c  om
 */
public void ensureAtLeastNumDataNodes(int n) {
    List<ListenableFuture<String>> futures = Lists.newArrayList();
    synchronized (this) {
        int size = numDataNodes();
        for (int i = size; i < n; i++) {
            logger.info("increasing cluster size from {} to {}", size, n);
            futures.add(startNodeAsync());
        }
    }
    try {
        Futures.allAsList(futures).get();
    } catch (Exception e) {
        throw new ElasticsearchException("failed to start nodes", e);
    }
    if (!futures.isEmpty()) {
        synchronized (this) {
            assertNoTimeout(client().admin().cluster().prepareHealth()
                    .setWaitForNodes(Integer.toString(nodes.size())).get());
        }
    }
}

From source file:org.hawkular.alerts.engine.impl.CassActionsServiceImpl.java

private boolean filterByActionId(String tenantId, Set<ActionHistoryPK> actionPks, ActionsCriteria criteria)
        throws Exception {
    boolean filterByActionId = false;
    if (criteria.getActionId() != null
            || (criteria.getActionIds() != null && !criteria.getActionIds().isEmpty())) {
        filterByActionId = true;/*  w  w  w.j  a v  a  2  s .c  o m*/

        PreparedStatement selectActionHistoryActionId = CassStatement.get(session,
                CassStatement.SELECT_ACTION_HISTORY_ACTION_ID);

        List<ResultSetFuture> futures = new ArrayList<>();
        if (criteria.getActionId() != null) {
            futures.add(
                    session.executeAsync(selectActionHistoryActionId.bind(tenantId, criteria.getActionId())));
        }
        if (criteria.getActionIds() != null && !criteria.getActionIds().isEmpty()) {
            for (String actionId : criteria.getActionIds()) {
                futures.add(session.executeAsync(selectActionHistoryActionId.bind(tenantId, actionId)));
            }
        }

        List<ResultSet> rsActionHistory = Futures.allAsList(futures).get();
        rsActionHistory.stream().forEach(r -> {
            for (Row row : r) {
                ActionHistoryPK actionHistoryPK = new ActionHistoryPK();
                actionHistoryPK.tenantId = tenantId;
                actionHistoryPK.actionPlugin = row.getString("actionPlugin");
                actionHistoryPK.actionId = row.getString("actionId");
                actionHistoryPK.alertId = row.getString("alertId");
                actionHistoryPK.ctime = row.getLong("ctime");
                actionPks.add(actionHistoryPK);
            }
        });
    }
    return filterByActionId;
}

From source file:org.apache.brooklyn.core.mgmt.persist.BrooklynMementoPersisterToObjectStore.java

/** See {@link BrooklynPersistenceUtils} for conveniences for using this method. */
@Override/*www .  j a v  a  2 s.  c  om*/
@Beta
public void checkpoint(BrooklynMementoRawData newMemento, PersistenceExceptionHandler exceptionHandler) {
    checkWritesAllowed();
    try {
        lock.writeLock().lockInterruptibly();
    } catch (InterruptedException e) {
        throw Exceptions.propagate(e);
    }

    try {
        objectStore.prepareForMasterUse();

        Stopwatch stopwatch = Stopwatch.createStarted();
        List<ListenableFuture<?>> futures = Lists.newArrayList();

        for (BrooklynObjectType type : BrooklynPersistenceUtils.STANDARD_BROOKLYN_OBJECT_TYPE_PERSISTENCE_ORDER) {
            for (Map.Entry<String, String> entry : newMemento.getObjectsOfType(type).entrySet()) {
                futures.add(asyncPersist(type.getSubPathName(), type, entry.getKey(), entry.getValue(),
                        exceptionHandler));
            }
        }

        try {
            // Wait for all the tasks to complete or fail, rather than aborting on the first failure.
            // But then propagate failure if any fail. (hence the two calls).
            Futures.successfulAsList(futures).get();
            Futures.allAsList(futures).get();
        } catch (Exception e) {
            throw Exceptions.propagate(e);
        }
        if (LOG.isDebugEnabled())
            LOG.debug("Checkpointed entire memento in {}", Time.makeTimeStringRounded(stopwatch));
    } finally {
        lock.writeLock().unlock();
    }
}

From source file:com.microsoft.intellij.helpers.o365.Office365ManagerImpl.java

@Override
@NotNull//from   w  ww. j  a  va2s  . com
public ListenableFuture<List<ServicePrincipal>> getO365ServicePrincipalsForApp(
        @NotNull final Application application) {
    return requestFutureWithToken(new RequestCallback<ListenableFuture<List<ServicePrincipal>>>() {
        @Override
        public ListenableFuture<List<ServicePrincipal>> execute() throws Throwable {
            @SuppressWarnings("unchecked")
            ListenableFuture<List<ServicePrincipal>>[] futures = new ListenableFuture[] {
                    getServicePrincipalsForApp(application), getServicePrincipalsForO365() };

            final String[] filterAppIds = new String[] { ServiceAppIds.SHARE_POINT, ServiceAppIds.EXCHANGE,
                    ServiceAppIds.AZURE_ACTIVE_DIRECTORY };

            return Futures.transform(Futures.allAsList(futures),
                    new AsyncFunction<List<List<ServicePrincipal>>, List<ServicePrincipal>>() {
                        @Override
                        public ListenableFuture<List<ServicePrincipal>> apply(
                                List<List<ServicePrincipal>> lists) throws Exception {
                            // According to Guava documentation for allAsList, the list of results is in the
                            // same order as the input list. So first we get the service principals for the app
                            // filtered for O365 and Graph service principals.
                            final List<ServicePrincipal> servicePrincipalsForApp = Lists.newArrayList(
                                    Iterables.filter(lists.get(0), new Predicate<ServicePrincipal>() {
                                        @Override
                                        public boolean apply(final ServicePrincipal servicePrincipal) {
                                            // we are only interested in O365 and Graph service principals
                                            return Iterators.any(Iterators.forArray(filterAppIds),
                                                    new Predicate<String>() {
                                                        @Override
                                                        public boolean apply(String appId) {
                                                            return appId.equals(servicePrincipal.getappId());
                                                        }
                                                    });
                                        }
                                    }));

                            // next we get the O365/graph service principals
                            final List<ServicePrincipal> servicePrincipalsForO365 = lists.get(1);

                            // then we add service principals from servicePrincipalsForO365 to servicePrincipalsForApp
                            // where the service principal is not available in the latter
                            Iterable<ServicePrincipal> servicePrincipalsToBeAdded = Iterables
                                    .filter(servicePrincipalsForO365, new Predicate<ServicePrincipal>() {
                                        @Override
                                        public boolean apply(ServicePrincipal servicePrincipal) {
                                            return !servicePrincipalsForApp.contains(servicePrincipal);
                                        }
                                    });
                            Iterables.addAll(servicePrincipalsForApp, servicePrincipalsToBeAdded);

                            // assign the appid to the service principal and reset permissions on new service principals;
                            // we do Lists.newArrayList calls below to create a copy of the service lists because Lists.transform
                            // invokes the transformation function lazily and this causes problems for us; we force immediate
                            // evaluation of our transfomer by copying the elements to a new list
                            List<ServicePrincipal> servicePrincipals = Lists
                                    .newArrayList(Lists.transform(servicePrincipalsForApp,
                                            new Function<ServicePrincipal, ServicePrincipal>() {
                                                @Override
                                                public ServicePrincipal apply(
                                                        ServicePrincipal servicePrincipal) {
                                                    if (!servicePrincipal.getappId()
                                                            .equals(application.getappId())) {
                                                        servicePrincipal.setappId(application.getappId());
                                                        servicePrincipal.setoauth2Permissions(
                                                                Lists.newArrayList(Lists.transform(
                                                                        servicePrincipal.getoauth2Permissions(),
                                                                        new Function<OAuth2Permission, OAuth2Permission>() {
                                                                            @Override
                                                                            public OAuth2Permission apply(
                                                                                    OAuth2Permission oAuth2Permission) {
                                                                                oAuth2Permission
                                                                                        .setisEnabled(false);
                                                                                return oAuth2Permission;
                                                                            }
                                                                        })));
                                                    }

                                                    return servicePrincipal;
                                                }
                                            }));

                            return Futures.immediateFuture(servicePrincipals);
                        }
                    });
        }
    });
}

From source file:org.apache.qpid.server.virtualhost.AbstractVirtualHost.java

private ListenableFuture<List<Void>> createDefaultExchanges() {
    return Subject.doAs(getSubjectWithAddedSystemRights(),
            new PrivilegedAction<ListenableFuture<List<Void>>>() {

                @Override/*from   w w w  .ja va2  s .  co m*/
                public ListenableFuture<List<Void>> run() {
                    List<ListenableFuture<Void>> standardExchangeFutures = new ArrayList<>();
                    standardExchangeFutures.add(addStandardExchange(ExchangeDefaults.DIRECT_EXCHANGE_NAME,
                            ExchangeDefaults.DIRECT_EXCHANGE_CLASS));
                    standardExchangeFutures.add(addStandardExchange(ExchangeDefaults.TOPIC_EXCHANGE_NAME,
                            ExchangeDefaults.TOPIC_EXCHANGE_CLASS));
                    standardExchangeFutures.add(addStandardExchange(ExchangeDefaults.HEADERS_EXCHANGE_NAME,
                            ExchangeDefaults.HEADERS_EXCHANGE_CLASS));
                    standardExchangeFutures.add(addStandardExchange(ExchangeDefaults.FANOUT_EXCHANGE_NAME,
                            ExchangeDefaults.FANOUT_EXCHANGE_CLASS));
                    return Futures.allAsList(standardExchangeFutures);
                }

                ListenableFuture<Void> addStandardExchange(String name, String type) {

                    Map<String, Object> attributes = new HashMap<String, Object>();
                    attributes.put(Exchange.NAME, name);
                    attributes.put(Exchange.TYPE, type);
                    attributes.put(Exchange.ID, UUIDGenerator.generateExchangeUUID(name, getName()));
                    final ListenableFuture<Exchange<?>> future = addExchangeAsync(attributes);
                    final SettableFuture<Void> returnVal = SettableFuture.create();
                    addFutureCallback(future, new FutureCallback<Exchange<?>>() {
                        @Override
                        public void onSuccess(final Exchange<?> result) {
                            try {
                                childAdded(result);
                                returnVal.set(null);
                            } catch (Throwable t) {
                                returnVal.setException(t);
                            }
                        }

                        @Override
                        public void onFailure(final Throwable t) {
                            returnVal.setException(t);
                        }
                    }, getTaskExecutor());

                    return returnVal;
                }
            });
}

From source file:org.apache.qpid.server.model.AbstractConfiguredObject.java

protected final ListenableFuture<Void> closeChildren() {
    final List<ListenableFuture<Void>> childCloseFutures = new ArrayList<>();

    applyToChildren(new Action<ConfiguredObject<?>>() {
        @Override/*from   w ww.j  a v a2s .  c  o  m*/
        public void performAction(final ConfiguredObject<?> child) {
            ListenableFuture<Void> childCloseFuture = child.closeAsync();
            addFutureCallback(childCloseFuture, new FutureCallback<Void>() {
                @Override
                public void onSuccess(final Void result) {
                }

                @Override
                public void onFailure(final Throwable t) {
                    LOGGER.error("Exception occurred while closing {} : {}", child.getClass().getSimpleName(),
                            child.getName(), t);
                }
            }, getTaskExecutor());
            childCloseFutures.add(childCloseFuture);
        }
    });

    ListenableFuture<List<Void>> combinedFuture = Futures.allAsList(childCloseFutures);
    return doAfter(combinedFuture, new Runnable() {
        @Override
        public void run() {
            // TODO consider removing each child from the parent as each child close completes, rather
            // than awaiting the completion of the combined future.  This would make it easy to give
            // clearer debug that would highlight the children that have failed to closed.
            for (Collection<ConfiguredObject<?>> childList : _children.values()) {
                childList.clear();
            }

            for (Map<UUID, ConfiguredObject<?>> childIdMap : _childrenById.values()) {
                childIdMap.clear();
            }

            for (Map<String, ConfiguredObject<?>> childNameMap : _childrenByName.values()) {
                childNameMap.clear();
            }

            LOGGER.debug("All children closed {} : {}",
                    AbstractConfiguredObject.this.getClass().getSimpleName(), getName());
        }
    });
}

From source file:org.hawkular.alerts.engine.impl.CassActionsServiceImpl.java

private boolean filterByAlertId(String tenantId, Set<ActionHistoryPK> actionPks, ActionsCriteria criteria)
        throws Exception {
    boolean filterByAlertId = false;
    if (criteria.getAlertId() != null
            || (criteria.getAlertIds() != null && !criteria.getAlertIds().isEmpty())) {
        filterByAlertId = true;//w  ww .  j av a 2s  .c o  m

        PreparedStatement selectActionHistoryAlertId = CassStatement.get(session,
                CassStatement.SELECT_ACTION_HISTORY_ALERT_ID);

        List<ResultSetFuture> futures = new ArrayList<>();
        if (criteria.getAlertId() != null) {
            futures.add(session.executeAsync(selectActionHistoryAlertId.bind(tenantId, criteria.getAlertId())));
        }
        if (criteria.getAlertIds() != null && !criteria.getAlertIds().isEmpty()) {
            for (String alertId : criteria.getAlertIds()) {
                futures.add(session.executeAsync(selectActionHistoryAlertId.bind(tenantId, alertId)));
            }
        }

        List<ResultSet> rsActionHistory = Futures.allAsList(futures).get();
        rsActionHistory.stream().forEach(r -> {
            for (Row row : r) {
                ActionHistoryPK actionHistoryPK = new ActionHistoryPK();
                actionHistoryPK.tenantId = tenantId;
                actionHistoryPK.actionPlugin = row.getString("actionPlugin");
                actionHistoryPK.actionId = row.getString("actionId");
                actionHistoryPK.alertId = row.getString("alertId");
                actionHistoryPK.ctime = row.getLong("ctime");
                actionPks.add(actionHistoryPK);
            }
        });
    }
    return filterByAlertId;
}