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.hawkular.alerts.engine.impl.CassAlertsServiceImpl.java

private Set<String> getIdsByTags(String tenantId, TagType tagType, Map<String, String> tags) throws Exception {
    Set<String> ids = new HashSet<>();
    List<ResultSetFuture> futures = new ArrayList<>();
    PreparedStatement selectTagsByName = CassStatement.get(session, CassStatement.SELECT_TAGS_BY_NAME);
    PreparedStatement selectTagsByNameAndValue = CassStatement.get(session,
            CassStatement.SELECT_TAGS_BY_NAME_AND_VALUE);

    for (Map.Entry<String, String> tag : tags.entrySet()) {
        boolean nameOnly = "*".equals(tag.getValue());
        BoundStatement bs = nameOnly ? selectTagsByName.bind(tenantId, tagType.name(), tag.getKey())
                : selectTagsByNameAndValue.bind(tenantId, tagType.name(), tag.getKey(), tag.getValue());
        futures.add(session.executeAsync(bs));
    }/*w  ww  . j a  v  a  2  s.  c  o m*/
    List<ResultSet> rsTags = Futures.allAsList(futures).get();
    rsTags.stream().forEach(r -> {
        for (Row row : r) {
            ids.add(row.getString("id"));
        }
    });
    return ids;
}

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

public ListenableFuture<Void> closeConnections() {
    if (_logger.isDebugEnabled()) {
        _logger.debug("Closing connection registry :" + _connections.size() + " connections.");
    }//from  ww  w.  ja  v a2 s.  com
    _acceptsConnections.set(false);
    for (AMQPConnection<?> conn : _connections) {
        conn.stopConnection();
    }

    List<ListenableFuture<Void>> connectionCloseFutures = new ArrayList<>();
    while (!_connections.isEmpty()) {
        Iterator<AMQPConnection<?>> itr = _connections.iterator();
        while (itr.hasNext()) {
            Connection<?> connection = itr.next();
            try {
                connectionCloseFutures.add(connection.closeAsync());
            } catch (Exception e) {
                _logger.warn("Exception closing connection " + connection.getName() + " from "
                        + connection.getRemoteAddress(), e);
            } finally {
                itr.remove();
            }
        }
    }
    ListenableFuture<List<Void>> combinedFuture = Futures.allAsList(connectionCloseFutures);
    return Futures.transform(combinedFuture, new Function<List<Void>, Void>() {
        @Override
        public Void apply(List<Void> voids) {
            return null;
        }
    });
}

From source file:org.apache.druid.indexing.kafka.supervisor.KafkaSupervisor.java

private void verifyAndMergeCheckpoints(final Collection<TaskGroup> taskGroupsToVerify) {
    final List<ListenableFuture<?>> futures = new ArrayList<>();
    for (TaskGroup taskGroup : taskGroupsToVerify) {
        futures.add(workerExec.submit(() -> verifyAndMergeCheckpoints(taskGroup)));
    }//from   ww  w .  j ava  2  s. co m
    try {
        Futures.allAsList(futures).get(futureTimeoutInSeconds, TimeUnit.SECONDS);
    } catch (InterruptedException | ExecutionException | TimeoutException e) {
        throw new RuntimeException(e);
    }
}

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

/**
 * Starts multiple nodes in an async manner with the given settings and version and returns future with its name.
 *//*from  w  w w . jav a  2 s .  co m*/
public synchronized ListenableFuture<List<String>> startNodesAsync(final int numNodes, final Settings settings,
        final Version version) {
    List<ListenableFuture<String>> futures = Lists.newArrayList();
    for (int i = 0; i < numNodes; i++) {
        futures.add(startNodeAsync(settings, version));
    }
    return Futures.allAsList(futures);
}

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

/**
 * Starts multiple nodes (based on the number of settings provided) in an async manner, with explicit settings for each node.
 * The order of the node names returned matches the order of the settings provided.
 */// w ww. ja  v  a  2 s . c o m
public synchronized ListenableFuture<List<String>> startNodesAsync(final Settings... settings) {
    List<ListenableFuture<String>> futures = Lists.newArrayList();
    for (Settings setting : settings) {
        futures.add(startNodeAsync(setting, Version.CURRENT));
    }
    return Futures.allAsList(futures);
}

From source file:org.glowroot.central.repo.AggregateDaoImpl.java

private ListenableFuture<?> insertTransactionSummaries(RollupParams rollup, AggregateQuery query,
        Map<String, MutableSummary> summaries) throws Exception {
    BoundStatement boundStatement;/*w ww . j ava 2s .c  om*/
    List<ListenableFuture<?>> futures = new ArrayList<>();
    PreparedStatement preparedStatement = getInsertTransactionPS(summaryTable, rollup.rollupLevel());
    for (Map.Entry<String, MutableSummary> entry : summaries.entrySet()) {
        MutableSummary summary = entry.getValue();
        boundStatement = preparedStatement.bind();
        int i = 0;
        boundStatement.setString(i++, rollup.agentRollupId());
        boundStatement.setString(i++, query.transactionType());
        boundStatement.setTimestamp(i++, new Date(query.to()));
        boundStatement.setString(i++, entry.getKey());
        boundStatement.setDouble(i++, summary.totalDurationNanos);
        boundStatement.setLong(i++, summary.transactionCount);
        boundStatement.setInt(i++, rollup.adjustedTTL().generalTTL());
        futures.add(session.writeAsync(boundStatement));
    }
    return Futures.allAsList(futures);
}

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

private void fetchEvents(String tenantId, Set<String> eventIds, boolean thin, List<Event> events)
        throws Exception {
    PreparedStatement selectEvent = CassStatement.get(session, CassStatement.SELECT_EVENT);
    List<ResultSetFuture> futures = eventIds.stream()
            .map(id -> session.executeAsync(selectEvent.bind(tenantId, id))).collect(Collectors.toList());
    List<ResultSet> rsEvents = Futures.allAsList(futures).get();
    rsEvents.stream().forEach(r -> {/*from w  ww  .  j a va  2 s . co  m*/
        for (Row row : r) {
            String payload = row.getString("payload");
            Event event = JsonUtil.fromJson(payload, Event.class, thin);
            events.add(event);
        }
    });
}

From source file:org.glowroot.central.repo.AggregateDaoImpl.java

private ListenableFuture<?> rollupTransactionErrorSummaryFromRows(RollupParams rollup, AggregateQuery query,
        Iterable<Row> rows) throws Exception {
    BoundStatement boundStatement;//from  w w  w .ja  v  a2  s.  c  o m
    Map<String, MutableErrorSummary> summaries = new HashMap<>();
    for (Row row : rows) {
        int i = 0;
        String transactionName = checkNotNull(row.getString(i++));
        MutableErrorSummary summary = summaries.get(transactionName);
        if (summary == null) {
            summary = new MutableErrorSummary();
            summaries.put(transactionName, summary);
        }
        summary.errorCount += row.getLong(i++);
        summary.transactionCount += row.getLong(i++);
    }
    PreparedStatement preparedStatement = getInsertTransactionPS(errorSummaryTable, rollup.rollupLevel());
    List<ListenableFuture<?>> futures = new ArrayList<>();
    for (Map.Entry<String, MutableErrorSummary> entry : summaries.entrySet()) {
        MutableErrorSummary summary = entry.getValue();
        boundStatement = preparedStatement.bind();
        int i = 0;
        boundStatement.setString(i++, rollup.agentRollupId());
        boundStatement.setString(i++, query.transactionType());
        boundStatement.setTimestamp(i++, new Date(query.to()));
        boundStatement.setString(i++, entry.getKey());
        boundStatement.setLong(i++, summary.errorCount);
        boundStatement.setLong(i++, summary.transactionCount);
        boundStatement.setInt(i++, rollup.adjustedTTL().generalTTL());
        futures.add(session.writeAsync(boundStatement));
    }
    return Futures.allAsList(futures);
}

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

private Set<String> filterByTriggers(String tenantId, EventsCriteria criteria) throws Exception {
    Set<String> result = Collections.emptySet();
    Set<String> triggerIds = extractTriggerIds(tenantId, criteria);

    if (triggerIds.size() > 0) {
        PreparedStatement selectEventsTriggers = CassStatement.get(session, CassStatement.SELECT_EVENT_TRIGGER);

        List<ResultSetFuture> futures = new ArrayList<>();
        for (String triggerId : triggerIds) {
            if (isEmpty(triggerId)) {
                continue;
            }/*from w w  w.  jav  a  2  s.  c o m*/
            futures.add(session.executeAsync(selectEventsTriggers.bind(tenantId, triggerId)));
        }

        List<ResultSet> rsIdsByTriggerIds = Futures.allAsList(futures).get();

        Set<String> eventIds = new HashSet<>();
        rsIdsByTriggerIds.stream().forEach(r -> {
            for (Row row : r) {
                String eventId = row.getString("id");
                eventIds.add(eventId);
            }
        });
        result = eventIds;
    }

    return result;
}

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

private Set<String> filterByCategories(String tenantId, EventsCriteria criteria) throws Exception {
    Set<String> result = Collections.emptySet();

    Set<String> categories = new HashSet<>();
    if (isEmpty(criteria.getCategories())) {
        if (criteria.getCategory() != null) {
            categories.add(criteria.getCategory());
        }//from ww w .ja  v  a2s . c  o  m
    } else {
        categories.addAll(criteria.getCategories());
    }

    if (categories.size() > 0) {
        PreparedStatement selectEventCategory = CassStatement.get(session, CassStatement.SELECT_EVENT_CATEGORY);
        List<ResultSetFuture> futures = categories.stream()
                .map(category -> session.executeAsync(selectEventCategory.bind(tenantId, category)))
                .collect(Collectors.toList());
        List<ResultSet> rsAlertStatuses = Futures.allAsList(futures).get();

        Set<String> eventIds = new HashSet<>();
        rsAlertStatuses.stream().forEach(r -> {
            for (Row row : r) {
                String eventId = row.getString("id");
                eventIds.add(eventId);
            }
        });
        result = eventIds;
    }
    return result;
}