List of usage examples for com.google.common.util.concurrent Futures transform
public static <I, O> ListenableFuture<O> transform(ListenableFuture<I> input, Function<? super I, ? extends O> function, Executor executor)
From source file:com.facebook.buck.core.build.engine.cache.manager.InputBasedRuleKeyManager.java
private ListenableFuture<Optional<Pair<BuildRuleSuccessType, CacheResult>>> performInputBasedCacheFetch( RuleKey inputRuleKey) {/* w w w . j a va 2 s . co m*/ Preconditions.checkArgument(SupportsInputBasedRuleKey.isSupported(rule)); getBuildInfoRecorder().addBuildMetadata(BuildInfo.MetadataKey.INPUT_BASED_RULE_KEY, inputRuleKey.toString()); // Check the input-based rule key says we're already built. if (checkMatchingInputBasedKey(inputRuleKey)) { return Futures .immediateFuture(Optional.of(new Pair<>(BuildRuleSuccessType.MATCHING_INPUT_BASED_RULE_KEY, CacheResult.localKeyUnchangedHit()))); } // Try to fetch the artifact using the input-based rule key. return Futures.transform(buildCacheArtifactFetcher .tryToFetchArtifactFromBuildCacheAndOverlayOnTopOfProjectFilesystem(inputRuleKey, artifactCache, // TODO(simons): Share this between all tests, not one per cell. rule.getProjectFilesystem()), cacheResult -> { if (cacheResult.getType().isSuccess()) { try (Scope ignored = LeafEvents.scope(eventBus, "handling_cache_result")) { return Optional.of( new Pair<>(BuildRuleSuccessType.FETCHED_FROM_CACHE_INPUT_BASED, cacheResult)); } } return Optional.empty(); }, MoreExecutors.directExecutor()); }
From source file:info.archinnov.achilles.internal.async.AsyncUtils.java
public <V> ListenableFuture<Empty> transformFutureToEmpty(ListenableFuture<V> from, ExecutorService executorService) { Function<V, Empty> function = new Function<V, Empty>() { @Override/*from w w w .j a v a 2s . c o m*/ public Empty apply(V input) { return Empty.INSTANCE; } }; return Futures.transform(from, function, executorService); }
From source file:com.facebook.buck.distributed.DistBuildArtifactCacheImpl.java
private ListenableFuture<Map<RuleKey, CacheResult>> multiContainsAsync(List<RuleKey> ruleKeys) { List<ListenableFuture<ImmutableMap<RuleKey, CacheResult>>> requestResultsFutures = new ArrayList<>( ruleKeys.size() / MAX_RULEKEYS_IN_MULTI_CONTAINS_REQUEST + 1); while (ruleKeys.size() > 0) { int numKeysInCurrentRequest = Math.min(MAX_RULEKEYS_IN_MULTI_CONTAINS_REQUEST, ruleKeys.size()); LOG.verbose("Making multi-contains request for [%d] rulekeys.", numKeysInCurrentRequest); requestResultsFutures.add(remoteCache .multiContainsAsync(ImmutableSet.copyOf(ruleKeys.subList(0, numKeysInCurrentRequest)))); ruleKeys = ruleKeys.subList(numKeysInCurrentRequest, ruleKeys.size()); }/*from www . ja va2s .c o m*/ return Futures.transform(Futures.allAsList(requestResultsFutures), (List<Map<RuleKey, CacheResult>> requestResults) -> { Map<RuleKey, CacheResult> allResults = new HashMap<>(); for (Map<RuleKey, CacheResult> partResults : requestResults) { allResults.putAll(partResults); } return allResults; }, MoreExecutors.directExecutor()); }
From source file:io.prestosql.split.MockSplitSource.java
@Override public ListenableFuture<SplitBatch> getNextBatch(ConnectorPartitionHandle partitionHandle, Lifespan lifespan, int maxSize) { if (partitionHandle != NOT_PARTITIONED) { throw new UnsupportedOperationException(); }// ww w . java 2s. c o m checkArgument(Lifespan.taskWide().equals(lifespan)); checkState(nextBatchFuture.isDone(), "concurrent getNextBatch invocation"); nextBatchFuture = SettableFuture.create(); nextBatchMaxSize = maxSize; nextBatchInvocationCount++; doGetNextBatch(); return Futures.transform(nextBatchFuture, splits -> new SplitBatch(splits, isFinished()), directExecutor()); }
From source file:com.spotify.trickle.PreparedGraph.java
private ListenableFuture<R> nodeFuture(final ImmutableList<ListenableFuture<?>> values, final ListenableFuture<List<Object>> doneSignal, final Executor executor) { return Futures.transform(doneSignal, new AsyncFunction<List<Object>, R>() { @Override// w w w. j a va 2s . c o m public ListenableFuture<R> apply(List<Object> input) { // the input future is not going to be null unless there's a Trickle bug, so we should // be fine with an NPE in that case //noinspection NullableProblems return graph.getNode().run(Lists.transform(values, new Function<ListenableFuture<?>, Object>() { @Override public Object apply(ListenableFuture<?> input) { return inputValueFromFuture(input); } })); } }, executor); }
From source file:com.datastax.driver.core.SessionManager.java
private ListenableFuture<PreparedStatement> toPreparedStatement(final String query, final Connection.Future future) { return Futures.transform(future, new Function<Message.Response, PreparedStatement>() { public PreparedStatement apply(Message.Response response) { switch (response.type) { case RESULT: Responses.Result rm = (Responses.Result) response; switch (rm.kind) { case PREPARED: Responses.Result.Prepared pmsg = (Responses.Result.Prepared) rm; PreparedStatement stmt = DefaultPreparedStatement.fromMessage(pmsg, cluster.getMetadata(), cluster.getConfiguration().getProtocolOptions().getProtocolVersion(), query, poolsState.keyspace); stmt = cluster.manager.addPrepared(stmt); try { // All Sessions are connected to the same nodes so it's enough to prepare only the nodes of this session. // If that changes, we'll have to make sure this propagate to other sessions too. prepare(stmt.getQueryString(), future.getAddress()); } catch (InterruptedException e) { Thread.currentThread().interrupt(); // This method doesn't propagate interruption, at least not for now. However, if we've // interrupted preparing queries on other node it's not a problem as we'll re-prepare // later if need be. So just ignore. }//from w w w . jav a2 s. c o m return stmt; default: throw new DriverInternalError(String .format("%s response received when prepared statement was expected", rm.kind)); } case ERROR: throw ((Responses.Error) response).asException(future.getAddress()); default: throw new DriverInternalError(String .format("%s response received when prepared statement was expected", response.type)); } } }, executor()); // Since the transformation involves querying other nodes, we should not do that in an I/O thread }
From source file:com.facebook.buck.remoteexecution.util.OutputsMaterializer.java
private ListenableFuture<Void> fetchAndMaterialize(Protocol.Digest digest, boolean isExecutable, Path path) throws IOException { OutputStream fileStream = new BufferedOutputStream(new FileOutputStream(path.toFile())); return Futures.transform(fetcher.fetchToStream(digest, fileStream), ignored -> { try {/*from w w w . j a va 2 s . c o m*/ fileStream.close(); if (isExecutable) { setExecutable(true, path); } return null; } catch (IOException e) { throw new UncheckedExecutionException(e); } }, MoreExecutors.directExecutor()); }
From source file:com.continuuity.weave.internal.ZKServiceDecorator.java
/** * Deletes the given ZK path recursively and create the path again. */// www .j a v a2 s . c o m private ListenableFuture<String> deleteAndCreate(final String path, final byte[] data, final CreateMode mode) { return Futures.transform(ZKOperations.ignoreError(ZKOperations.recursiveDelete(zkClient, path), KeeperException.NoNodeException.class, null), new AsyncFunction<String, String>() { @Override public ListenableFuture<String> apply(String input) throws Exception { return zkClient.create(path, data, mode); } }, Threads.SAME_THREAD_EXECUTOR); }
From source file:com.facebook.buck.parser.ParserWithConfigurableAttributes.java
@Override public ListenableFuture<SortedMap<String, Object>> getTargetNodeRawAttributesJob(PerBuildState state, Cell cell, TargetNode<?> targetNode) throws BuildFileParseException { Cell owningCell = cell.getCell(targetNode.getBuildTarget()); ListenableFuture<BuildFileManifest> buildFileManifestFuture = state.getBuildFileManifestJob(owningCell, cell.getAbsolutePathToBuildFile(targetNode.getBuildTarget())); return Futures.transform(buildFileManifestFuture, buildFileManifest -> getTargetFromManifest(state, cell, targetNode, buildFileManifest), MoreExecutors.directExecutor()); }
From source file:com.facebook.buck.remoteexecution.util.MultiThreadedBlobUploader.java
private ListenableFuture<Void> enqueue(ImmutableMap<Digest, UploadDataSupplier> data) { ImmutableList.Builder<ListenableFuture<Void>> futures = ImmutableList.builder(); for (Entry<Digest, UploadDataSupplier> entry : data.entrySet()) { Digest digest = entry.getKey();/* w ww. j av a 2 s . c om*/ ListenableFuture<Void> resultFuture = pendingUploads.computeIfAbsent(digest.getHash(), hash -> { if (containedHashes.contains(hash)) { return Futures.immediateFuture(null); } SettableFuture<Void> future = SettableFuture.create(); waitingMissingCheck.add(new PendingUpload(new UploadData(digest, entry.getValue()), future)); return Futures.transform(future, ignore -> { // If the upload was successful short circuit for future requests. containedHashes.add(digest.getHash()); return null; }, directExecutor()); }); Futures.addCallback(resultFuture, MoreFutures.finallyCallback(() -> { pendingUploads.remove(digest.getHash()); }), directExecutor()); futures.add(resultFuture); uploadService.submit(this::processUploads); } return Futures.whenAllSucceed(futures.build()).call(() -> null, directExecutor()); }