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.rhq.server.metrics.MetricsServer.java

private List<AggregateNumericMetric> loadMetrics(List<Integer> scheduleIds, long begin, long end,
        Bucket bucket) {//from  w  ww.  ja  v a  2 s  . c  o m
    List<StorageResultSetFuture> futures = new ArrayList<StorageResultSetFuture>(scheduleIds.size());
    for (Integer scheduleId : scheduleIds) {
        futures.add(dao.findAggregateMetricsAsync(scheduleId, bucket, begin, end));
    }
    ListenableFuture<List<ResultSet>> resultSetsFuture = Futures.successfulAsList(futures);
    try {
        List<ResultSet> resultSets = resultSetsFuture.get();
        AggregateNumericMetricMapper mapper = new AggregateNumericMetricMapper();
        List<AggregateNumericMetric> metrics = new ArrayList<AggregateNumericMetric>();
        for (ResultSet resultSet : resultSets) {
            metrics.addAll(mapper.mapAll(resultSet));
        }
        return metrics;
    } catch (Exception e) {
        log.warn("There was an error while fetching " + bucket + " data for {scheduleIds: " + scheduleIds
                + ", beginTime: " + begin + ", endTime: " + end + "}", e);
        return Collections.emptyList();
    }
}

From source file:org.thingsboard.server.dao.alarm.BaseAlarmService.java

@Override
public ListenableFuture<TimePageData<AlarmInfo>> findAlarms(TenantId tenantId, AlarmQuery query) {
    ListenableFuture<List<AlarmInfo>> alarms = alarmDao.findAlarms(tenantId, query);
    if (query.getFetchOriginator() != null && query.getFetchOriginator().booleanValue()) {
        alarms = Futures.transformAsync(alarms, input -> {
            List<ListenableFuture<AlarmInfo>> alarmFutures = new ArrayList<>(input.size());
            for (AlarmInfo alarmInfo : input) {
                alarmFutures.add(Futures.transform(
                        entityService.fetchEntityNameAsync(tenantId, alarmInfo.getOriginator()),
                        originatorName -> {
                            if (originatorName == null) {
                                originatorName = "Deleted";
                            }//from   ww w .j av a2 s .  c o  m
                            alarmInfo.setOriginatorName(originatorName);
                            return alarmInfo;
                        }));
            }
            return Futures.successfulAsList(alarmFutures);
        });
    }
    return Futures.transform(alarms, new Function<List<AlarmInfo>, TimePageData<AlarmInfo>>() {
        @Nullable
        @Override
        public TimePageData<AlarmInfo> apply(@Nullable List<AlarmInfo> alarms) {
            return new TimePageData<>(alarms, query.getPageLink());
        }
    });
}

From source file:org.apache.brooklyn.core.mgmt.internal.ManagementNodeStateListenerManager.java

public void terminate() {
    terminated = true;/*from ww w .  j a v a  2s  . c  om*/
    synchronized (waitForMasterRebindMutex) {
        waitForMasterRebindMutex.notifyAll();
    }

    // Wait for the listeners to finish + close the listeners
    Duration timeout = mgmt.getBrooklynProperties()
            .getConfig(BrooklynServerConfig.MANAGEMENT_NODE_STATE_LISTENER_TERMINATION_TIMEOUT);
    if (listenerQueueSize.get() > 0) {
        LOG.info("Management-node-state-listener manager waiting for " + listenerQueueSize
                + " listener events for up to " + timeout);
    }
    List<ListenableFuture<?>> futures = Lists.newArrayList();
    for (final ManagementNodeStateListener listener : listeners) {
        ListenableFuture<?> future = listenerExecutor.submit(new Runnable() {
            @Override
            public void run() {
                if (listener instanceof Closeable) {
                    try {
                        ((Closeable) listener).close();
                    } catch (IOException | RuntimeException e) {
                        LOG.warn("Problem closing management-node-state listener " + listener, e);
                        Exceptions.propagateIfFatal(e);
                    }
                }
            }
        });
        futures.add(future);
    }
    try {
        Futures.successfulAsList(futures).get(timeout.toMilliseconds(), TimeUnit.MILLISECONDS);
    } catch (Exception e) {
        Exceptions.propagateIfFatal(e);
        LOG.warn("Problem terminiating management-node-state listeners (continuing)", e);
    } finally {
        listenerExecutor.shutdownNow();
    }
}

From source file:com.netflix.metacat.main.services.search.ElasticSearchRefresh.java

@SuppressWarnings("checkstyle:methodname")
private ListenableFuture<Void> _processPartitions(final List<QualifiedName> qNames) {
    final List<QualifiedName> excludeQualifiedNames = config.getElasticSearchRefreshExcludeQualifiedNames();
    final List<String> tables = elasticSearchUtil.getTableIdsByCatalogs(ElasticSearchDoc.Type.table.name(),
            qNames, excludeQualifiedNames);
    final List<ListenableFuture<ListenableFuture<Void>>> futures = tables.stream()
            .map(s -> service.submit(() -> {
                final QualifiedName tableName = QualifiedName.fromString(s, false);
                final List<ListenableFuture<Void>> indexFutures = Lists.newArrayList();
                int offset = 0;
                int count;
                final Sort sort;
                if ("s3".equals(tableName.getCatalogName()) || "aegisthus".equals(tableName.getCatalogName())) {
                    sort = new Sort("id", SortOrder.ASC);
                } else {
                    sort = new Sort("part_id", SortOrder.ASC);
                }/*w  ww.ja  v a 2  s. c  om*/
                final Pageable pageable = new Pageable(10000, offset);
                do {
                    final List<PartitionDto> partitionDtos = partitionService.list(tableName, sort, pageable,
                            true, true, new GetPartitionsRequestDto(null, null, true, true));
                    count = partitionDtos.size();
                    if (!partitionDtos.isEmpty()) {
                        final List<List<PartitionDto>> partitionedPartitionDtos = Lists.partition(partitionDtos,
                                1000);
                        partitionedPartitionDtos.forEach(subPartitionsDtos -> indexFutures
                                .add(indexPartitionDtos(tableName, subPartitionsDtos)));
                        offset = offset + count;
                        pageable.setOffset(offset);
                    }
                } while (count == 10000);
                return Futures.transform(Futures.successfulAsList(indexFutures),
                        Functions.constant((Void) null));
            })).collect(Collectors.toList());
    final ListenableFuture<Void> processPartitionsFuture = Futures
            .transformAsync(Futures.successfulAsList(futures), input -> {
                final List<ListenableFuture<Void>> inputFuturesWithoutNulls = input.stream().filter(NOT_NULL)
                        .collect(Collectors.toList());
                return Futures.transform(Futures.successfulAsList(inputFuturesWithoutNulls),
                        Functions.constant(null));
            });
    return Futures.transformAsync(processPartitionsFuture, input -> {
        elasticSearchUtil.refresh();
        final List<ListenableFuture<Void>> cleanUpFutures = tables.stream()
                .map(s -> service.submit(
                        () -> partitionsCleanUp(QualifiedName.fromString(s, false), excludeQualifiedNames)))
                .collect(Collectors.toList());
        return Futures.transform(Futures.successfulAsList(cleanUpFutures), Functions.constant(null));
    });
}

From source file:com.google.cloud.bigtable.hbase.BatchExecutor.java

/**
 * <p>batch.</p>//from   w w w .  jav  a2 s  . c  o m
 *
 * @param actions a {@link java.util.List} object.
 * @param results an array of {@link java.lang.Object} objects.
 * @throws java.io.IOException if any.
 * @throws java.lang.InterruptedException if any.
 */
public void batch(List<? extends Row> actions, @Nullable Object[] results)
        throws IOException, InterruptedException {
    if (results == null) {
        results = new Object[actions.size()];
    }
    Preconditions.checkArgument(results.length == actions.size(),
            "Result array must have same dimensions as actions list.");
    Timer.Context timerContext = batchTimer.time();
    List<ListenableFuture<?>> resultFutures = issueAsyncRowRequests(actions, results, null);
    try {
        // Don't want to throw an exception for failed futures, instead the place in results is
        // set to null.
        Futures.successfulAsList(resultFutures).get();
        List<Throwable> problems = new ArrayList<>();
        List<Row> problemActions = new ArrayList<>();
        List<String> hosts = new ArrayList<>();
        for (int i = 0; i < resultFutures.size(); i++) {
            try {
                resultFutures.get(i).get();
            } catch (ExecutionException e) {
                problemActions.add(actions.get(i));
                problems.add(e.getCause());
                hosts.add(options.getDataHost().toString());
            }
        }
        if (problems.size() > 0) {
            throw new RetriesExhaustedWithDetailsException(problems, problemActions, hosts);
        }
    } catch (ExecutionException e) {
        LOG.error("Encountered exception in batch(List<>, Object[]).", e);
        throw new IOException("Batch error", e);
    } finally {
        timerContext.close();
    }
}

From source file:org.thingsboard.server.dao.asset.BaseAssetService.java

@Override
public ListenableFuture<List<Asset>> findAssetsByQuery(TenantId tenantId, AssetSearchQuery query) {
    ListenableFuture<List<EntityRelation>> relations = relationService.findByQuery(tenantId,
            query.toEntitySearchQuery());
    ListenableFuture<List<Asset>> assets = Futures.transformAsync(relations, r -> {
        EntitySearchDirection direction = query.toEntitySearchQuery().getParameters().getDirection();
        List<ListenableFuture<Asset>> futures = new ArrayList<>();
        for (EntityRelation relation : r) {
            EntityId entityId = direction == EntitySearchDirection.FROM ? relation.getTo() : relation.getFrom();
            if (entityId.getEntityType() == EntityType.ASSET) {
                futures.add(findAssetByIdAsync(tenantId, new AssetId(entityId.getId())));
            }//from  ww w.  ja v  a 2s . co m
        }
        return Futures.successfulAsList(futures);
    });
    assets = Futures.transform(assets,
            assetList -> assetList == null ? Collections.emptyList()
                    : assetList.stream().filter(asset -> query.getAssetTypes().contains(asset.getType()))
                            .collect(Collectors.toList()));
    return assets;
}

From source file:utils.teamcity.wallt.controller.api.ApiController.java

@Override
public ListenableFuture<Void> requestLastBuildStatus(final BuildTypeData buildType) {
    if (!getApiVersion().isSupported(ApiFeature.BUILD_TYPE_STATUS))
        return Futures.immediateFuture(null);

    _buildRequestErrorCounter.cleanUp();

    final SettableFuture<Void> ackFuture = SettableFuture.create();

    runInWorkerThread(() -> {/*from   w ww  .ja v a  2s  . c  o  m*/
        final ListenableFuture<BuildList> buildListFuture = _apiRequestController
                .sendRequest(getApiVersion(),
                        "builds/?locator=buildType:" + buildType.getId()
                                + ",running:any,branch:(default:any),count:" + MAX_BUILDS_TO_CONSIDER,
                        BuildList.class);
        addCallback(buildListFuture, new FutureCallback<BuildList>() {
            @Override
            public void onSuccess(final BuildList result) {
                // We consider only last builds
                final Set<Integer> buildToRequest = result.getBuilds().stream().limit(MAX_BUILDS_TO_CONSIDER)
                        .map(Build::getId).collect(Collectors.toSet());

                // We remove builds which status is already known as finished
                buildToRequest.removeIf(buildId -> {
                    final Optional<BuildData> previousBuildStatus = buildType.getBuildById(buildId);
                    return previousBuildStatus.isPresent()
                            && previousBuildStatus.get().getState() == BuildState.finished;
                });

                // We ignore builds which status is in error
                buildToRequest.removeIf(buildId -> {
                    final Integer errorCount = _buildRequestErrorCounter.getIfPresent(buildId);
                    return errorCount != null && errorCount >= ERROR_COUNT_BEFORE_IGNORING;
                });

                // We add all builds that are always in state running into data
                buildToRequest.addAll(buildType.getLastBuilds(BuildState.running, Integer.MAX_VALUE).stream()
                        .map(BuildData::getId).collect(Collectors.<Integer>toList()));

                final List<ListenableFuture<Build>> futures = Lists.newArrayList();
                for (final int buildId : buildToRequest) {
                    final ListenableFuture<Build> buildStatusFuture = _apiRequestController
                            .sendRequest(getApiVersion(), "builds/id:" + buildId, Build.class);
                    addCallback(buildStatusFuture, registerBuildStatus(buildType, buildId));
                    futures.add(buildStatusFuture);
                }

                addCallback(Futures.successfulAsList(futures), new FutureCallback<List<Build>>() {
                    @Override
                    public void onSuccess(final List<Build> build) {
                        ackFuture.set(null);
                    }

                    @Override
                    public void onFailure(final Throwable throwable) {
                        ackFuture.setException(throwable);
                    }
                });
            }

            @Override
            public void onFailure(final Throwable t) {
                ackFuture.setException(t);
                LOGGER.error("Error during loading builds list for build type: " + buildType.getId(), t);
            }
        });
    });

    return ackFuture;
}

From source file:org.thingsboard.server.dao.device.DeviceServiceImpl.java

@Override
public ListenableFuture<List<Device>> findDevicesByQuery(TenantId tenantId, DeviceSearchQuery query) {
    ListenableFuture<List<EntityRelation>> relations = relationService.findByQuery(tenantId,
            query.toEntitySearchQuery());
    ListenableFuture<List<Device>> devices = Futures.transformAsync(relations, r -> {
        EntitySearchDirection direction = query.toEntitySearchQuery().getParameters().getDirection();
        List<ListenableFuture<Device>> futures = new ArrayList<>();
        for (EntityRelation relation : r) {
            EntityId entityId = direction == EntitySearchDirection.FROM ? relation.getTo() : relation.getFrom();
            if (entityId.getEntityType() == EntityType.DEVICE) {
                futures.add(findDeviceByIdAsync(tenantId, new DeviceId(entityId.getId())));
            }/*from w w w .  j  a  v  a2s  .  co m*/
        }
        return Futures.successfulAsList(futures);
    });

    devices = Futures.transform(devices, new Function<List<Device>, List<Device>>() {
        @Nullable
        @Override
        public List<Device> apply(@Nullable List<Device> deviceList) {
            return deviceList == null ? Collections.emptyList()
                    : deviceList.stream().filter(device -> query.getDeviceTypes().contains(device.getType()))
                            .collect(Collectors.toList());
        }
    });

    return devices;
}

From source file:org.apache.cassandra.service.ActiveRepairService.java

/**
 * Run final process of repair.// w  w  w .j  av a 2  s  .  c  om
 * This removes all resources held by parent repair session, after performing anti compaction if necessary.
 *
 * @param parentSession Parent session ID
 * @param neighbors Repair participants (not including self)
 * @param successfulRanges Ranges that repaired successfully
 */
public synchronized ListenableFuture finishParentSession(UUID parentSession, Set<InetAddress> neighbors,
        Collection<Range<Token>> successfulRanges) {
    List<ListenableFuture<?>> tasks = new ArrayList<>(neighbors.size() + 1);
    for (InetAddress neighbor : neighbors) {
        AnticompactionTask task = new AnticompactionTask(parentSession, neighbor, successfulRanges);
        tasks.add(task);
        task.run(); // 'run' is just sending message
    }
    tasks.add(doAntiCompaction(parentSession, successfulRanges));
    return Futures.successfulAsList(tasks);
}

From source file:com.google.cloud.spanner.SpannerImpl.java

@Override
public void close() {
    List<ListenableFuture<Void>> closureFutures = null;
    synchronized (this) {
        Preconditions.checkState(!spannerIsClosed, "Cloud Spanner client has been closed");
        spannerIsClosed = true;/* ww  w. j  a  v  a 2 s  .co  m*/
        closureFutures = new ArrayList<>();
        for (DatabaseClientImpl dbClient : dbClients.values()) {
            closureFutures.add(dbClient.closeAsync());
        }
        dbClients.clear();
    }
    try {
        Futures.successfulAsList(closureFutures).get();
    } catch (InterruptedException | ExecutionException e) {
        throw SpannerExceptionFactory.newSpannerException(e);
    }
    for (ManagedChannel channel : getOptions().getRpcChannels()) {
        try {
            channel.shutdown();
        } catch (RuntimeException e) {
            logger.log(Level.WARNING, "Failed to close channel", e);
        }
    }
}