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:org.thingsboard.server.dao.alarm.BaseAlarmService.java

@Override
public ListenableFuture<AlarmInfo> findAlarmInfoByIdAsync(TenantId tenantId, AlarmId alarmId) {
    log.trace("Executing findAlarmInfoByIdAsync [{}]", alarmId);
    validateId(alarmId, "Incorrect alarmId " + alarmId);
    return Futures.transformAsync(alarmDao.findAlarmByIdAsync(tenantId, alarmId.getId()), a -> {
        AlarmInfo alarmInfo = new AlarmInfo(a);
        return Futures.transform(entityService.fetchEntityNameAsync(tenantId, alarmInfo.getOriginator()),
                originatorName -> {//from ww  w .  j  a va2  s.  c om
                    alarmInfo.setOriginatorName(originatorName);
                    return alarmInfo;
                });
    });
}

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   w  ww.  j a v a2s .  co 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.thingsboard.server.dao.relation.BaseRelationService.java

@Override
public ListenableFuture<Void> deleteEntityRelationsAsync(TenantId tenantId, EntityId entityId) {
    Cache cache = cacheManager.getCache(RELATIONS_CACHE);
    log.trace("Executing deleteEntityRelationsAsync [{}]", entityId);
    validate(entityId);//from   w  w w.  j  av a  2 s .c o  m
    List<ListenableFuture<List<EntityRelation>>> inboundRelationsList = new ArrayList<>();
    for (RelationTypeGroup typeGroup : RelationTypeGroup.values()) {
        inboundRelationsList.add(relationDao.findAllByTo(tenantId, entityId, typeGroup));
    }

    ListenableFuture<List<List<EntityRelation>>> inboundRelations = Futures.allAsList(inboundRelationsList);

    List<ListenableFuture<List<EntityRelation>>> outboundRelationsList = new ArrayList<>();
    for (RelationTypeGroup typeGroup : RelationTypeGroup.values()) {
        outboundRelationsList.add(relationDao.findAllByFrom(tenantId, entityId, typeGroup));
    }

    ListenableFuture<List<List<EntityRelation>>> outboundRelations = Futures.allAsList(outboundRelationsList);

    ListenableFuture<List<Boolean>> inboundDeletions = Futures.transformAsync(inboundRelations, relations -> {
        List<ListenableFuture<Boolean>> results = deleteRelationGroupsAsync(tenantId, relations, cache, true);
        return Futures.allAsList(results);
    });

    ListenableFuture<List<Boolean>> outboundDeletions = Futures.transformAsync(outboundRelations, relations -> {
        List<ListenableFuture<Boolean>> results = deleteRelationGroupsAsync(tenantId, relations, cache, false);
        return Futures.allAsList(results);
    });

    ListenableFuture<List<List<Boolean>>> deletionsFuture = Futures.allAsList(inboundDeletions,
            outboundDeletions);

    return Futures.transform(
            Futures.transformAsync(deletionsFuture,
                    (deletions) -> relationDao.deleteOutboundRelationsAsync(tenantId, entityId)),
            result -> null);
}

From source file:com.orangerhymelabs.helenus.cassandra.document.DocumentRepository.java

public ListenableFuture<Document> upsert(Document entity) {
    ListenableFuture<ResultSet> future = submitUpsert(entity);
    return Futures.transformAsync(future, new AsyncFunction<ResultSet, Document>() {
        @Override//from   w  w w  .  j a v a2  s .  c  o  m
        public ListenableFuture<Document> apply(ResultSet result) throws Exception {
            if (result.wasApplied()) {
                return Futures.immediateFuture(entity);
            }

            //TODO: This doesn't provide any informational value... what should it be?
            return Futures.immediateFailedFuture(new StorageException(String
                    .format("Table %s failed to store document: %s", table.toDbTable(), entity.toString())));
        }
    });
}

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())));
            }// w  ww .  jav  a 2  s  .  c o 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: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);
                }//from   w  w w.  j  a  va 2s. c  o m
                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.facebook.presto.transaction.TransactionManager.java

public ListenableFuture<?> asyncCommit(TransactionId transactionId) {
    return nonCancellationPropagating(Futures.transformAsync(removeTransactionMetadataAsFuture(transactionId),
            TransactionMetadata::asyncCommit));
}

From source file:com.facebook.presto.transaction.TransactionManager.java

public ListenableFuture<?> asyncAbort(TransactionId transactionId) {
    return nonCancellationPropagating(Futures.transformAsync(removeTransactionMetadataAsFuture(transactionId),
            TransactionMetadata::asyncAbort));
}

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

private ListenableFuture<TreePath> getTreePath(CommandStream.Node node, List<Object> path,
        Iterator<Long> indices) {
    ListenableFuture<CommandStream.Node> load = models.commands.load(node);
    if (!indices.hasNext()) {
        TreePath result = new TreePath(path.toArray());
        // Ensure the last node in the path is loaded.
        return (load == null) ? Futures.immediateFuture(result) : Futures.transform(load, ignored -> result);
    }//w  w  w  .j  a v  a 2  s. c o  m
    return (load == null) ? getTreePathForLoadedNode(node, path, indices)
            : Futures.transformAsync(load, loaded -> getTreePathForLoadedNode(loaded, path, indices));
}

From source file:io.v.todos.persistence.syncbase.SyncbaseTodoList.java

public ListenableFuture<Void> updateListTimestamp() {
    ListenableFuture<io.v.todos.model.ListSpec> get = mList.get(getVContext(), LIST_METADATA_ROW_NAME,
            ListSpec.class);
    return Futures.transformAsync(get, new AsyncFunction<Object, Void>() {
        @Override//from  ww w  . ja  v  a2s . co  m
        public ListenableFuture<Void> apply(Object oldValue) throws Exception {
            ListSpec listSpec = (ListSpec) oldValue;
            listSpec.setUpdatedAt(System.currentTimeMillis());
            return mList.put(getVContext(), LIST_METADATA_ROW_NAME, listSpec);
        }
    });
}