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

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

Introduction

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

Prototype

public static <I, O> ListenableFuture<O> transform(ListenableFuture<I> input,
        Function<? super I, ? extends O> function) 

Source Link

Document

Returns a new ListenableFuture whose result is the product of applying the given Function to the result of the given Future .

Usage

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

private ListenableFuture<TreePath> getTreePath(CommandIndex index) {
    CommandStream.Node root = models.commands.getData();
    ListenableFuture<TreePath> result = getTreePath(root, Lists.newArrayList(root),
            index.getNode().getIndicesList().iterator());
    if (index.isGroup()) {
        // Find the deepest group/node in the path that is not the last child of its parent.
        result = Futures.transform(result, path -> {
            while (path.getSegmentCount() > 0) {
                CommandStream.Node node = (CommandStream.Node) path.getLastSegment();
                if (!node.isLastChild()) {
                    break;
                }/*w  w  w.j  a  v  a 2s .c o m*/
                path = path.getParentPath();
            }
            return path;
        });
    }
    return result;
}

From source file:zipkin.elasticsearch.ElasticsearchSpanStore.java

ListenableFuture<List<List<Span>>> getTracesByIds(Collection<Long> traceIds, String[] indices) {
    List<String> traceIdsStr = new ArrayList<>(traceIds.size());
    for (long traceId : traceIds) {
        traceIdsStr.add(String.format("%016x", traceId));
    }//ww  w. ja va 2  s . c om
    SearchRequestBuilder elasticRequest = client.prepareSearch(indices)
            .setIndicesOptions(IndicesOptions.lenientExpandOpen()).setTypes(ElasticsearchConstants.SPAN)
            // TODO: This is the default maximum size of an elasticsearch result set.
            // Need to determine whether this is enough by zipkin standards or should
            // increase it in the index template.
            .setSize(10000).setQuery(termsQuery("traceId", traceIdsStr));
    return Futures.transform(toGuava(elasticRequest.execute()), ConvertTracesResponse.INSTANCE);
}

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 . ja va  2s  . com
    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:io.v.android.security.BlessingsManager.java

private static ListenableFuture<Blessings> wrapWithSetAsDefault(final VContext ctx, final Context context,
        ListenableFuture<Blessings> future) {
    return Futures.transform(future, new AsyncFunction<Blessings, Blessings>() {
        @Override/*from w ww .j  a v a  2  s  .  c o  m*/
        public ListenableFuture<Blessings> apply(Blessings blessings) throws Exception {
            if (ctx.isCanceled()) {
                return Futures.immediateFailedFuture(new VException("Vanadium context canceled"));
            }
            // Update local state with the new blessings.
            try {
                VPrincipal p = V.getPrincipal(ctx);
                p.blessingStore().setDefaultBlessings(blessings);
                p.blessingStore().set(blessings, Constants.ALL_PRINCIPALS);
                VSecurity.addToRoots(p, blessings);
                return Futures.immediateFuture(blessings);
            } catch (VException e) {
                return Futures.immediateFailedFuture(e);
            }
        }
    });
}

From source file:org.opendaylight.openflowplugin.applications.frsync.impl.strategy.SyncPlanPushStrategyIncrementalImpl.java

ListenableFuture<RpcResult<Void>> addMissingFlows(final NodeId nodeId,
        final InstanceIdentifier<FlowCapableNode> nodeIdent,
        final Map<TableKey, ItemSyncBox<Flow>> flowsInTablesSyncBox, final SyncCrudCounters counters) {
    if (flowsInTablesSyncBox.isEmpty()) {
        LOG.trace("no tables in config for node: {} -> SKIPPING", nodeId.getValue());
        return RpcResultBuilder.<Void>success().buildFuture();
    }/*w  w  w. j a  v  a  2 s .  c  o  m*/

    final List<ListenableFuture<RpcResult<AddFlowOutput>>> allResults = new ArrayList<>();
    final List<ListenableFuture<RpcResult<UpdateFlowOutput>>> allUpdateResults = new ArrayList<>();
    final CrudCounts flowCrudCounts = counters.getFlowCrudCounts();

    for (Map.Entry<TableKey, ItemSyncBox<Flow>> flowsInTableBoxEntry : flowsInTablesSyncBox.entrySet()) {
        final TableKey tableKey = flowsInTableBoxEntry.getKey();
        final ItemSyncBox<Flow> flowSyncBox = flowsInTableBoxEntry.getValue();

        final KeyedInstanceIdentifier<Table, TableKey> tableIdent = nodeIdent.child(Table.class, tableKey);

        for (final Flow flow : flowSyncBox.getItemsToPush()) {
            final KeyedInstanceIdentifier<Flow, FlowKey> flowIdent = tableIdent.child(Flow.class,
                    flow.getKey());

            LOG.trace("adding flow {} in table {} - absent on device {} match{}", flow.getId(), tableKey,
                    nodeId, flow.getMatch());

            allResults.add(JdkFutureAdapters.listenInPoolThread(flowForwarder.add(flowIdent, flow, nodeIdent)));
            flowCrudCounts.incAdded();
        }

        for (final ItemSyncBox.ItemUpdateTuple<Flow> flowUpdate : flowSyncBox.getItemsToUpdate()) {
            final Flow existingFlow = flowUpdate.getOriginal();
            final Flow updatedFlow = flowUpdate.getUpdated();

            final KeyedInstanceIdentifier<Flow, FlowKey> flowIdent = tableIdent.child(Flow.class,
                    updatedFlow.getKey());
            LOG.trace("flow {} in table {} - needs update on device {} match{}", updatedFlow.getId(), tableKey,
                    nodeId, updatedFlow.getMatch());

            allUpdateResults.add(JdkFutureAdapters
                    .listenInPoolThread(flowForwarder.update(flowIdent, existingFlow, updatedFlow, nodeIdent)));
            flowCrudCounts.incUpdated();
        }
    }

    final ListenableFuture<RpcResult<Void>> singleVoidAddResult = Futures.transform(
            Futures.allAsList(allResults),
            ReconcileUtil.<AddFlowOutput>createRpcResultCondenser("flow adding"));

    final ListenableFuture<RpcResult<Void>> singleVoidUpdateResult = Futures.transform(
            Futures.allAsList(allUpdateResults),
            ReconcileUtil.<UpdateFlowOutput>createRpcResultCondenser("flow updating"));

    return Futures.transform(Futures.allAsList(singleVoidAddResult, singleVoidUpdateResult),
            ReconcileUtil.<Void>createRpcResultCondenser("flow add/update"));
}

From source file:io.druid.segment.realtime.appenderator.StreamAppenderatorDriver.java

/**
 * Execute a task in background to publish all segments corresponding to the given sequence names.  The task
 * internally pushes the segments to the deep storage first, and then publishes the metadata to the metadata storage.
 *
 * @param publisher     segment publisher
 * @param committer     committer//  w  w  w. j  a v a2 s.  com
 * @param sequenceNames a collection of sequence names to be published
 *
 * @return a {@link ListenableFuture} for the submitted task which removes published {@code sequenceNames} from
 * {@code activeSegments} and {@code publishPendingSegments}
 */
public ListenableFuture<SegmentsAndMetadata> publish(final TransactionalSegmentPublisher publisher,
        final Committer committer, final Collection<String> sequenceNames) {
    final List<SegmentIdentifier> theSegments = getSegmentWithStates(sequenceNames)
            .map(SegmentWithState::getSegmentIdentifier).collect(Collectors.toList());

    final ListenableFuture<SegmentsAndMetadata> publishFuture = ListenableFutures.transformAsync(
            // useUniquePath=true prevents inconsistencies in segment data when task failures or replicas leads to a second
            // version of a segment with the same identifier containing different data; see DataSegmentPusher.push() docs
            pushInBackground(wrapCommitter(committer), theSegments, true),
            sam -> publishInBackground(sam, publisher));
    return Futures.transform(publishFuture,
            (Function<? super SegmentsAndMetadata, ? extends SegmentsAndMetadata>) sam -> {
                synchronized (segments) {
                    sequenceNames.forEach(segments::remove);
                }
                return sam;
            });
}

From source file:com.google.cloud.bigtable.grpc.BigtableGrpcClient.java

@Override
public ListenableFuture<List<Row>> readRowsAsync(final ReadRowsRequest request) {
    final Call<ReadRowsRequest, ReadRowsResponse> readRowsCall = bigtableChannel
            .newCall(BigtableServiceGrpc.CONFIG.readRows);

    CollectingStreamObserver<ReadRowsResponse> responseCollector = new CollectingStreamObserver<>();

    Calls.asyncServerStreamingCall(readRowsCall, request, responseCollector);

    return Futures.transform(responseCollector.getResponseCompleteFuture(),
            new Function<List<ReadRowsResponse>, List<Row>>() {
                @Override//from   w  w  w.  j  a v  a2 s  .  c  om
                public List<Row> apply(List<ReadRowsResponse> responses) {
                    List<Row> result = new ArrayList<>();
                    Iterator<ReadRowsResponse> responseIterator = responses.iterator();
                    while (responseIterator.hasNext()) {
                        RowMerger currentRowMerger = new RowMerger();
                        while (responseIterator.hasNext() && !currentRowMerger.isRowCommitted()) {
                            currentRowMerger.addPartialRow(responseIterator.next());
                        }
                        result.add(currentRowMerger.buildRow());
                    }
                    return result;
                }
            });
}

From source file:io.v.v23.syncbase.DatabaseImpl.java

private ListenableFuture<QueryResults> execInternal(VContext ctx, String query, List<VdlAny> params) {
    final ClientRecvStream<List<VdlAny>, Void> stream = client.exec(ctx, this.batchHandle, query, params);
    return VFutures.withUserLandChecks(ctx,
            Futures.transform(stream.recv(), new AsyncFunction<List<VdlAny>, QueryResults>() {
                @Override//w  w  w.  j  av  a  2 s  . c  o m
                public ListenableFuture<QueryResults> apply(List<VdlAny> columnNames) throws Exception {
                    return Futures.immediateFuture((QueryResults) new QueryResultsImpl(columnNames, stream));
                }
            }));
}

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 w w. j  av  a2  s  . 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:org.opendaylight.openflowplugin.applications.frsync.impl.strategy.SyncPlanPushStrategyFlatBatchImpl.java

@Override
public ListenableFuture<RpcResult<Void>> executeSyncStrategy(ListenableFuture<RpcResult<Void>> resultVehicle,
        final SynchronizationDiffInput diffInput, final SyncCrudCounters counters) {
    final InstanceIdentifier<FlowCapableNode> nodeIdent = diffInput.getNodeIdent();
    final NodeId nodeId = PathUtil.digNodeId(nodeIdent);

    // prepare default (full) counts
    counters.getGroupCrudCounts().setAdded(ReconcileUtil.countTotalPushed(diffInput.getGroupsToAddOrUpdate()));
    counters.getGroupCrudCounts()/*w  ww  .j  a  v a  2  s  .  com*/
            .setUpdated(ReconcileUtil.countTotalUpdated(diffInput.getGroupsToAddOrUpdate()));
    counters.getGroupCrudCounts().setRemoved(ReconcileUtil.countTotalPushed(diffInput.getGroupsToRemove()));

    counters.getFlowCrudCounts()
            .setAdded(ReconcileUtil.countTotalPushed(diffInput.getFlowsToAddOrUpdate().values()));
    counters.getFlowCrudCounts()
            .setUpdated(ReconcileUtil.countTotalUpdated(diffInput.getFlowsToAddOrUpdate().values()));
    counters.getFlowCrudCounts()
            .setRemoved(ReconcileUtil.countTotalPushed(diffInput.getFlowsToRemove().values()));

    counters.getMeterCrudCounts().setAdded(diffInput.getMetersToAddOrUpdate().getItemsToPush().size());
    counters.getMeterCrudCounts().setUpdated(diffInput.getMetersToAddOrUpdate().getItemsToUpdate().size());
    counters.getMeterCrudCounts().setRemoved(diffInput.getMetersToRemove().getItemsToPush().size());

    /* Tables - have to be pushed before groups */
    // TODO enable table-update when ready
    //resultVehicle = updateTableFeatures(nodeIdent, configTree);

    resultVehicle = Futures.transform(resultVehicle, new AsyncFunction<RpcResult<Void>, RpcResult<Void>>() {
        @Override
        public ListenableFuture<RpcResult<Void>> apply(final RpcResult<Void> input) throws Exception {
            final List<Batch> batchBag = new ArrayList<>();
            int batchOrder = 0;

            batchOrder = assembleAddOrUpdateGroups(batchBag, batchOrder, diffInput.getGroupsToAddOrUpdate());
            batchOrder = assembleAddOrUpdateMeters(batchBag, batchOrder, diffInput.getMetersToAddOrUpdate());
            batchOrder = assembleAddOrUpdateFlows(batchBag, batchOrder, diffInput.getFlowsToAddOrUpdate());

            batchOrder = assembleRemoveFlows(batchBag, batchOrder, diffInput.getFlowsToRemove());
            batchOrder = assembleRemoveMeters(batchBag, batchOrder, diffInput.getMetersToRemove());
            batchOrder = assembleRemoveGroups(batchBag, batchOrder, diffInput.getGroupsToRemove());

            LOG.trace("Index of last batch step: {}", batchOrder);

            final ProcessFlatBatchInput flatBatchInput = new ProcessFlatBatchInputBuilder()
                    .setNode(new NodeRef(PathUtil.digNodePath(diffInput.getNodeIdent())))
                    // TODO: propagate from input
                    .setExitOnFirstError(false).setBatch(batchBag).build();

            final Future<RpcResult<ProcessFlatBatchOutput>> rpcResultFuture = flatBatchService
                    .processFlatBatch(flatBatchInput);

            final int failureIndexLimit = batchOrder;

            if (LOG.isDebugEnabled()) {
                Futures.addCallback(JdkFutureAdapters.listenInPoolThread(rpcResultFuture),
                        createCounterCallback(batchBag, failureIndexLimit, counters));
            }

            return Futures.transform(JdkFutureAdapters.listenInPoolThread(rpcResultFuture),
                    ReconcileUtil.<ProcessFlatBatchOutput>createRpcResultToVoidFunction("flat-batch"));
        }
    });

    Futures.addCallback(resultVehicle, FxChainUtil.logResultCallback(nodeId, "flat-batch"));
    return resultVehicle;
}