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

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

Introduction

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

Prototype

public static <I, O> ListenableFuture<O> transformAsync(ListenableFuture<I> input,
        AsyncFunction<? super I, ? extends O> function) 

Source Link

Document

Returns a new ListenableFuture whose result is asynchronously derived from the result of the given Future .

Usage

From source file:com.google.gapid.views.GeometryView.java

private ListenableFuture<Model> fetchModel(Path.Any path) {
    return Futures.transformAsync(client.get(path), value -> fetchModel(value.getMesh()));
}

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 ww .j a  v a 2 s  . c  o 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.glowroot.central.repo.SyntheticResultDao.java

private ListenableFuture<ResultSet> rollupOne(int rollupLevel, String agentRollupId, String syntheticMonitorId,
        long from, long to, int adjustedTTL) throws Exception {
    BoundStatement boundStatement = readResultForRollupPS.get(rollupLevel - 1).bind();
    int i = 0;//from w w  w  .  j  av a2  s.c  om
    boundStatement.setString(i++, agentRollupId);
    boundStatement.setString(i++, syntheticMonitorId);
    boundStatement.setTimestamp(i++, new Date(from));
    boundStatement.setTimestamp(i++, new Date(to));
    return Futures.transformAsync(session.executeAsync(boundStatement),
            new AsyncFunction<ResultSet, ResultSet>() {
                @Override
                public ListenableFuture<ResultSet> apply(@Nullable ResultSet results) throws Exception {
                    checkNotNull(results);
                    if (results.isExhausted()) {
                        // this is unexpected since TTL for "needs rollup" records is shorter
                        // than TTL for data
                        logger.warn("no synthetic result table records found for"
                                + " agentRollupId={}, syntheticMonitorId={}, from={}, to={}," + " level={}",
                                agentRollupId, syntheticMonitorId, from, to, rollupLevel);
                        return Futures.immediateFuture(DummyResultSet.INSTANCE);
                    }
                    return rollupOneFromRows(rollupLevel, agentRollupId, syntheticMonitorId, to, adjustedTTL,
                            results);
                }
            });
}

From source file:org.thingsboard.server.dao.relation.BaseRelationService.java

@Override
public ListenableFuture<List<EntityRelationInfo>> findInfoByFrom(TenantId tenantId, EntityId from,
        RelationTypeGroup typeGroup) {/*from   w  w  w .ja  va2 s.c o  m*/
    log.trace("Executing findInfoByFrom [{}][{}]", from, typeGroup);
    validate(from);
    validateTypeGroup(typeGroup);
    ListenableFuture<List<EntityRelation>> relations = relationDao.findAllByFrom(tenantId, from, typeGroup);
    return Futures.transformAsync(relations, relations1 -> {
        List<ListenableFuture<EntityRelationInfo>> futures = new ArrayList<>();
        relations1.forEach(relation -> futures.add(fetchRelationInfoAsync(tenantId, relation,
                EntityRelation::getTo, EntityRelationInfo::setToName)));
        return Futures.successfulAsList(futures);
    });
}

From source file:org.jooby.cassandra.Datastore.java

/**
 * Execute a query and map result to entityClass.
 *
 * @param entityClass Entity class./*from ww w . j av a2  s .c o m*/
 * @param statement Statement to execute.
 * @return A listenable future holding the result.
 */
public <T> ListenableFuture<Result<T>> queryAsync(final Class<T> entityClass, final Statement statement) {
    Mapper<T> mapper = mapper(entityClass);
    Session session = mapper.getManager().getSession();
    ResultSetFuture rs = session.executeAsync(statement);
    return Futures.transformAsync(rs, rs1 -> Futures.immediateFuture(mapper.map(rs1)));
}

From source file:org.thingsboard.server.dao.relation.BaseRelationService.java

@Override
public ListenableFuture<List<EntityRelationInfo>> findInfoByTo(TenantId tenantId, EntityId to,
        RelationTypeGroup typeGroup) {//from  ww  w .j av a2s . c  om
    log.trace("Executing findInfoByTo [{}][{}]", to, typeGroup);
    validate(to);
    validateTypeGroup(typeGroup);
    ListenableFuture<List<EntityRelation>> relations = relationDao.findAllByTo(tenantId, to, typeGroup);
    return Futures.transformAsync(relations, relations1 -> {
        List<ListenableFuture<EntityRelationInfo>> futures = new ArrayList<>();
        relations1.forEach(relation -> futures.add(fetchRelationInfoAsync(tenantId, relation,
                EntityRelation::getFrom, EntityRelationInfo::setFromName)));
        return Futures.successfulAsList(futures);
    });
}

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

private ListenableFuture<ResultSet> rollupOneFromChildren(int rollupLevel, String agentRollupId,
        String gaugeName, List<String> childAgentRollups, long captureTime, int adjustedTTL) {
    List<ListenableFuture<ResultSet>> futures = Lists.newArrayList();
    for (String childAgentRollup : childAgentRollups) {
        BoundStatement boundStatement = readValueForRollupFromChildPS.bind();
        int i = 0;
        boundStatement.setString(i++, childAgentRollup);
        boundStatement.setString(i++, gaugeName);
        boundStatement.setTimestamp(i++, new Date(captureTime));
        futures.add(session.executeAsync(boundStatement));
    }//from w  ww .  j a v a2  s  . c o  m
    return Futures.transformAsync(Futures.allAsList(futures), new AsyncFunction<List<ResultSet>, ResultSet>() {
        @Override
        public ListenableFuture<ResultSet> apply(@Nullable List<ResultSet> results) throws Exception {
            checkNotNull(results);
            List<Row> rows = Lists.newArrayList();
            for (int i = 0; i < results.size(); i++) {
                Row row = results.get(i).one();
                if (row == null) {
                    // this is unexpected since TTL for "needs rollup" records is
                    // shorter than TTL for data
                    logger.warn(
                            "no gauge value table records found for agentRollupId={},"
                                    + " gaugeName={}, captureTime={}, level={}",
                            childAgentRollups.get(i), gaugeName, captureTime, rollupLevel);
                } else {
                    rows.add(row);
                }
            }
            if (rows.isEmpty()) {
                // warning(s) already logged above
                return Futures.immediateFuture(DummyResultSet.INSTANCE);
            }
            return rollupOneFromRows(rollupLevel, agentRollupId, gaugeName, captureTime, adjustedTTL, rows);
        }
    });
}

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

@SuppressWarnings("checkstyle:methodname")
private ListenableFuture<Void> _processCatalogs(final List<String> catalogNames) {
    log.info("Start: Full refresh of catalogs: {}", catalogNames);
    final List<ListenableFuture<CatalogDto>> getCatalogFutures = catalogNames.stream()
            .map(catalogName -> service.submit(() -> {
                CatalogDto result = null;
                try {
                    result = getCatalog(catalogName);
                } catch (Exception e) {
                    log.error("Failed to retrieve catalog: {}", catalogName);
                    elasticSearchUtil.log("ElasticSearchMetacatRefresh.getCatalog",
                            ElasticSearchDoc.Type.catalog.name(), catalogName, null, e.getMessage(), e, true);
                }//from www . j  a  va2 s .c  om
                return result;
            })).collect(Collectors.toList());
    return Futures.transformAsync(Futures.successfulAsList(getCatalogFutures), input -> {
        final List<ListenableFuture<Void>> processCatalogFutures = input.stream().filter(NOT_NULL)
                .map(catalogDto -> {
                    final List<QualifiedName> databaseNames = getDatabaseNamesToRefresh(catalogDto);
                    return _processDatabases(catalogDto.getName(), databaseNames);
                }).filter(NOT_NULL).collect(Collectors.toList());
        return Futures.transform(Futures.successfulAsList(processCatalogFutures), Functions.constant(null));
    });
}

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

private ListenableFuture<ResultSet> rollupOne(int rollupLevel, String agentRollupId, String gaugeName,
        long from, long to, int adjustedTTL) throws Exception {
    BoundStatement boundStatement = readValueForRollupPS.get(rollupLevel - 1).bind();
    int i = 0;//from   w w w .j  a v  a 2s .c om
    boundStatement.setString(i++, agentRollupId);
    boundStatement.setString(i++, gaugeName);
    boundStatement.setTimestamp(i++, new Date(from));
    boundStatement.setTimestamp(i++, new Date(to));
    return Futures.transformAsync(session.executeAsync(boundStatement),
            new AsyncFunction<ResultSet, ResultSet>() {
                @Override
                public ListenableFuture<ResultSet> apply(@Nullable ResultSet results) throws Exception {
                    checkNotNull(results);
                    if (results.isExhausted()) {
                        // this is unexpected since TTL for "needs rollup" records is shorter
                        // than TTL for data
                        logger.warn(
                                "no gauge value table records found for agentRollupId={},"
                                        + " gaugeName={}, from={}, to={}, level={}",
                                agentRollupId, gaugeName, from, to, rollupLevel);
                        return Futures.immediateFuture(DummyResultSet.INSTANCE);
                    }
                    return rollupOneFromRows(rollupLevel, agentRollupId, gaugeName, to, adjustedTTL, results);
                }
            });
}

From source file:org.thingsboard.server.dao.relation.BaseRelationService.java

@Override
public ListenableFuture<List<EntityRelationInfo>> findInfoByQuery(TenantId tenantId,
        EntityRelationsQuery query) {/*w  w  w.j av  a2 s .  c  o  m*/
    log.trace("Executing findInfoByQuery [{}]", query);
    ListenableFuture<List<EntityRelation>> relations = findByQuery(tenantId, query);
    EntitySearchDirection direction = query.getParameters().getDirection();
    return Futures.transformAsync(relations, relations1 -> {
        List<ListenableFuture<EntityRelationInfo>> futures = new ArrayList<>();
        relations1.forEach(relation -> futures.add(fetchRelationInfoAsync(tenantId, relation,
                relation2 -> direction == EntitySearchDirection.FROM ? relation2.getTo() : relation2.getFrom(),
                (EntityRelationInfo relationInfo, String entityName) -> {
                    if (direction == EntitySearchDirection.FROM) {
                        relationInfo.setToName(entityName);
                    } else {
                        relationInfo.setFromName(entityName);
                    }
                })));
        return Futures.successfulAsList(futures);
    });
}