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:org.opendaylight.openflowplugin.impl.statistics.services.direct.AbstractDirectStatisticsService.java

/**
 * Handle input and reply future.//  w  w w. java  2s  .  c  o m
 *
 * @param input the input
 * @return the future
 */
public Future<RpcResult<O>> handleAndReply(final I input) {
    final ListenableFuture<RpcResult<List<MultipartReply>>> rpcReply = handleServiceCall(input);
    ListenableFuture<RpcResult<O>> rpcResult = Futures.transform(rpcReply, resultTransformFunction);

    if (Boolean.TRUE.equals(input.isStoreStats())) {
        rpcResult = Futures.transform(rpcResult, resultStoreFunction);
    }

    return rpcResult;
}

From source file:org.thingsboard.rule.engine.metadata.TbAbstractGetAttributesNode.java

private ListenableFuture<Void> putLatestTelemetry(TbContext ctx, EntityId entityId, TbMsg msg,
        List<String> keys) {
    if (CollectionUtils.isEmpty(keys)) {
        return Futures.immediateFuture(null);
    }//  w  ww  . j  a va2s .  c o  m
    ListenableFuture<List<TsKvEntry>> latest = ctx.getTimeseriesService().findLatest(ctx.getTenantId(),
            entityId, keys);
    return Futures.transform(latest, l -> {
        l.forEach(r -> {
            if (r.getValue() != null) {
                msg.getMetaData().putValue(r.getKey(), r.getValueAsString());
            } else {
                throw new RuntimeException("[" + r.getKey() + "] telemetry value is not present in the DB!");
            }
        });
        return null;
    });
}

From source file:org.opendaylight.controller.sal.binding.impl.connect.dom.RpcInvocationStrategy.java

@SuppressWarnings({ "unchecked" })
public ListenableFuture<RpcResult<?>> forwardToDomBroker(final DataObject input) {

    if (biRpcRegistry == null) {
        return Futures.<RpcResult<?>>immediateFuture(RpcResultBuilder.failed().build());
    }//from w  w w  .  j a v  a  2s. c  om

    CompositeNode inputXml = null;
    if (input != null) {
        CompositeNode xml = mappingService.toDataDom(input);
        inputXml = ImmutableCompositeNode.create(rpc, ImmutableList.<Node<?>>of(xml));
    } else {
        inputXml = ImmutableCompositeNode.create(rpc, Collections.<Node<?>>emptyList());
    }

    Function<RpcResult<CompositeNode>, RpcResult<?>> transformationFunction = new Function<RpcResult<CompositeNode>, RpcResult<?>>() {
        @SuppressWarnings("rawtypes")
        @Override
        public RpcResult<?> apply(RpcResult<CompositeNode> result) {

            Object output = null;

            if (getOutputClass() != null) {
                if (result.getResult() != null) {
                    output = mappingService.dataObjectFromDataDom(getOutputClass().get(), result.getResult());
                }
            }

            return RpcResultBuilder.from((RpcResult) result).withResult(output).build();
        }
    };

    return Futures.transform(biRpcRegistry.invokeRpc(rpc, inputXml), transformationFunction);
}

From source file:com.facebook.watchman.WatchmanClientImpl.java

@Override
public ListenableFuture<Boolean> unsubscribe(final SubscriptionDescriptor descriptor) {
    if (!subscriptions.containsKey(descriptor)) {
        return Futures.immediateFuture(false);
    }//from  ww w. ja  v a 2 s.  c om

    List<String> request = ImmutableList.of("unsubscribe", descriptor.root(), descriptor.name());

    return Futures.transform(connection.run(request), new Function<Map<String, Object>, Boolean>() {
        @Nullable
        @Override
        public Boolean apply(@Nullable Map<String, Object> input) {
            checkNotNull(input);

            boolean wasDeleted = (Boolean) input.get("deleted");
            if (wasDeleted) {
                if (subscriptions.remove(descriptor) == null) {
                    return false;
                }
            }
            return wasDeleted;
        }
    });
}

From source file:org.apache.helix.provisioning.yarn.YarnProvisioner.java

@Override
public ListenableFuture<ContainerId> allocateContainer(ContainerSpec spec) {
    ContainerRequest containerAsk = setupContainerAskForRM(spec);
    ListenableFuture<ContainerAskResponse> requestNewContainer = applicationMaster
            .acquireContainer(containerAsk);
    return Futures.transform(requestNewContainer, new Function<ContainerAskResponse, ContainerId>() {
        @Override/*from  w  w w  .  ja  v a  2s  .  co m*/
        public ContainerId apply(ContainerAskResponse containerAskResponse) {
            ContainerId helixContainerId = ContainerId
                    .from(containerAskResponse.getContainer().getId().toString());
            allocatedContainersMap.put(helixContainerId, containerAskResponse.getContainer());
            return helixContainerId;
        }
    });

}

From source file:com.facebook.buck.distributed.DistBuildFileHashes.java

public DistBuildFileHashes(ActionGraph actionGraph, final SourcePathResolver sourcePathResolver,
        SourcePathRuleFinder ruleFinder, final FileHashCache rootCellFileHashCache,
        final Function<? super Path, Integer> cellIndexer, ListeningExecutorService executorService,
        final int keySeed, final BuckConfig buckConfig) {

    this.remoteFileHashes = CacheBuilder.newBuilder()
            .build(new CacheLoader<ProjectFilesystem, BuildJobStateFileHashes>() {
                @Override//from   ww  w.  j  av  a  2 s  . c om
                public BuildJobStateFileHashes load(ProjectFilesystem filesystem) throws Exception {
                    BuildJobStateFileHashes fileHashes = new BuildJobStateFileHashes();
                    fileHashes.setCellIndex(cellIndexer.apply(filesystem.getRootPath()));
                    return fileHashes;
                }
            });
    this.fileHashLoaders = CacheBuilder.newBuilder()
            .build(new CacheLoader<ProjectFilesystem, FileHashLoader>() {
                @Override
                public FileHashLoader load(ProjectFilesystem key) throws Exception {
                    return new RecordingFileHashLoader(
                            new StackedFileHashCache(ImmutableList.of(rootCellFileHashCache,
                                    DefaultFileHashCache.createDefaultFileHashCache(key))),
                            key, remoteFileHashes.get(key), new DistBuildConfig(buckConfig));
                }
            });
    this.ruleKeyFactories = createRuleKeyFactories(sourcePathResolver, ruleFinder, fileHashLoaders, keySeed);
    this.ruleKeys = ruleKeyComputation(actionGraph, this.ruleKeyFactories, executorService);
    this.fileHashes = fileHashesComputation(Futures.transform(this.ruleKeys, Functions.constant(null)),
            this.remoteFileHashes, executorService);
}

From source file:com.google.gapid.models.CommandStream.java

public ListenableFuture<Node> load(Node node) {
    return node.load(shell, () -> Futures
            .transformAsync(client.get(Paths.toAny(node.getPath(Path.CommandTreeNode.newBuilder()))), v1 -> {
                Service.CommandTreeNode data = v1.getCommandTreeNode();
                if (data.getGroup().isEmpty() && data.hasCommands()) {
                    return Futures.transform(loadCommand(lastCommand(data.getCommands())),
                            cmd -> new NodeData(data, cmd));
                }/*  ww w . ja v  a2 s .  c  o m*/
                return Futures.immediateFuture(new NodeData(data, null));
            }));
}

From source file:org.opendaylight.bgpcep.pcep.topology.provider.TopologyRPCs.java

@Override
public Future<RpcResult<EnsureLspOperationalOutput>> ensureLspOperational(
        final EnsureLspOperationalInput input) {
    return Futures.transform(manager.ensureLspOperational(input),
            new Function<OperationResult, RpcResult<EnsureLspOperationalOutput>>() {
                @Override/* w w w .j a va  2  s .  c  o m*/
                public RpcResult<EnsureLspOperationalOutput> apply(final OperationResult input) {
                    return SuccessfulRpcResult.create(new EnsureLspOperationalOutputBuilder(input).build());
                }
            });
}

From source file:com.facebook.buck.rules.modern.builders.OutputsMaterializer.java

private ListenableFuture<Void> fetchAndMaterialize(Protocol.Digest digest, boolean isExecutable, Path path) {
    return Futures.transform(fetcher.fetch(digest), data -> {
        try {//from w w  w. j a  v a  2  s .co  m
            try (FileOutputStream fileStream = new FileOutputStream(path.toFile())) {
                fileStream.getChannel().write(data);
            }
            if (isExecutable) {
                setExecutable(true, path);
            }
            return null;
        } catch (IOException e) {
            throw new UncheckedExecutionException(e);
        }
    });
}

From source file:net.oneandone.troilus.SingleReadQuery.java

@Override
public ListenableFuture<Record> executeAsync() {
    ListenableFuture<ResultList<Record>> recordsFuture = new ListReadQuery(getContext(), data).executeAsync();
    recordsFuture = toSingleEntryResultList(recordsFuture);

    Function<ResultList<Record>, Record> fetchRecordFunction = new Function<ResultList<Record>, Record>() {

        @Override//from ww  w . j  a  v  a2s .  c om
        public Record apply(ResultList<Record> records) {
            Iterator<Record> it = records.iterator();
            if (it.hasNext()) {
                Record record = it.next();

                if (it.hasNext()) {
                    throw new TooManyResultsException(records, "more than one record exists");
                }

                return record;
            } else {
                return null;
            }
        }
    };

    return Futures.transform(recordsFuture, fetchRecordFunction);
}