List of usage examples for com.google.common.util.concurrent AsyncFunction AsyncFunction
AsyncFunction
From source file:com.facebook.buck.distributed.DistBuildService.java
public ListenableFuture<Void> uploadBuckDotFiles(final BuildId id, final ProjectFilesystem filesystem, FileHashCache fileHashCache, ListeningExecutorService executorService) throws IOException { ListenableFuture<Pair<List<FileInfo>, List<PathInfo>>> filesFuture = executorService .submit(new Callable<Pair<List<FileInfo>, List<PathInfo>>>() { @Override/*from w ww.j a va2 s. co m*/ public Pair<List<FileInfo>, List<PathInfo>> call() throws IOException { Path[] buckDotFilesExceptConfig = Arrays.stream(filesystem.listFiles(Paths.get("."))) .filter(f -> !f.isDirectory()).filter(f -> !Files.isSymbolicLink(f.toPath())) .filter(f -> f.getName().startsWith(".")).filter(f -> f.getName().contains("buck")) .filter(f -> !f.getName().startsWith(".buckconfig")).map(f -> f.toPath()) .toArray(Path[]::new); List<FileInfo> fileEntriesToUpload = new LinkedList<>(); List<PathInfo> pathEntriesToUpload = new LinkedList<>(); for (Path path : buckDotFilesExceptConfig) { FileInfo fileInfoObject = new FileInfo(); fileInfoObject.setContent(filesystem.readFileIfItExists(path).get().getBytes()); fileInfoObject.setContentHash(fileHashCache.get(path.toAbsolutePath()).toString()); fileEntriesToUpload.add(fileInfoObject); PathInfo pathInfoObject = new PathInfo(); pathInfoObject.setPath(path.toString()); pathInfoObject.setContentHash(fileHashCache.get(path.toAbsolutePath()).toString()); pathEntriesToUpload.add(pathInfoObject); } return new Pair<List<FileInfo>, List<PathInfo>>(fileEntriesToUpload, pathEntriesToUpload); } }); ListenableFuture<Void> setFilesFuture = Futures.transformAsync(filesFuture, new AsyncFunction<Pair<List<FileInfo>, List<PathInfo>>, Void>() { @Override public ListenableFuture<Void> apply( @Nullable Pair<List<FileInfo>, List<PathInfo>> filesAndPaths) throws IOException { setBuckDotFiles(id, filesAndPaths.getSecond()); return Futures.immediateFuture(null); } }, executorService); ListenableFuture<Void> uploadFilesFuture = Futures.transformAsync(filesFuture, new AsyncFunction<Pair<List<FileInfo>, List<PathInfo>>, Void>() { @Override public ListenableFuture<Void> apply( @Nullable Pair<List<FileInfo>, List<PathInfo>> filesAndPaths) throws Exception { uploadMissingFilesFromList(filesAndPaths.getFirst(), executorService); return Futures.immediateFuture(null); } }, executorService); return Futures.transform(Futures.allAsList(ImmutableList.of(setFilesFuture, uploadFilesFuture)), new Function<List<Void>, Void>() { @Nullable @Override public Void apply(@Nullable List<Void> input) { return null; } }); }
From source file:io.v.v23.rpc.ReflectInvoker.java
@Override public ListenableFuture<io.v.v23.vdlroot.signature.Method> getMethodSignature(VContext ctx, final String methodName) { return Futures.transform(getSignature(ctx), new AsyncFunction<Interface[], io.v.v23.vdlroot.signature.Method>() { @Override// w w w. ja v a2 s . c o m public ListenableFuture<io.v.v23.vdlroot.signature.Method> apply(Interface[] interfaces) throws Exception { for (Interface iface : interfaces) { for (io.v.v23.vdlroot.signature.Method method : iface.getMethods()) { if (method.getName().equals(methodName)) { return Futures.immediateFuture(method); } } } throw new VException(String.format("Could not find method %s", methodName)); } }); }
From source file:io.vitess.client.VTGateTx.java
public synchronized SQLFuture<List<Cursor>> executeBatchKeyspaceIds(Context ctx, Iterable<? extends BoundKeyspaceIdQuery> queries, TabletType tabletType, Query.ExecuteOptions.IncludedFields includedFields) throws SQLException { checkCallIsAllowed("executeBatchKeyspaceIds"); ExecuteBatchKeyspaceIdsRequest.Builder requestBuilder = ExecuteBatchKeyspaceIdsRequest.newBuilder() .addAllQueries(queries).setTabletType(tabletType).setSession(session) .setOptions(Query.ExecuteOptions.newBuilder().setIncludedFields(includedFields)); if (ctx.getCallerId() != null) { requestBuilder.setCallerId(ctx.getCallerId()); }/*from www . j a va 2s . c o m*/ SQLFuture<List<Cursor>> call = new SQLFuture<>( transformAsync(client.executeBatchKeyspaceIds(ctx, requestBuilder.build()), new AsyncFunction<ExecuteBatchKeyspaceIdsResponse, List<Cursor>>() { @Override public ListenableFuture<List<Cursor>> apply(ExecuteBatchKeyspaceIdsResponse response) throws Exception { setSession(response.getSession()); Proto.checkError(response.getError()); return Futures.<List<Cursor>>immediateFuture( Proto.toCursorList(response.getResultsList())); } }, directExecutor())); lastCall = call; return call; }
From source file:com.spotify.futures.FuturesExtra.java
/** * Transform the input futures into a single future, using the provided * transform function. The transformation follows the same semantics as as * {@link Futures#transform(ListenableFuture, AsyncFunction)} and the input * futures are combined using {@link Futures#allAsList}. * * @param a a ListenableFuture to combine * @param b a ListenableFuture to combine * @param c a ListenableFuture to combine * @param d a ListenableFuture to combine * @param function the implementation of the transform * @return a ListenableFuture holding the result of function.apply() *///w w w . j a v a 2 s. co m public static <Z, A, B, C, D> ListenableFuture<Z> asyncTransform4(ListenableFuture<A> a, ListenableFuture<B> b, ListenableFuture<C> c, ListenableFuture<D> d, final AsyncFunction4<Z, ? super A, ? super B, ? super C, ? super D> function) { return transform(Arrays.asList(a, b, c, d), new AsyncFunction<List<Object>, Z>() { @Override public ListenableFuture<Z> apply(List<Object> results) throws Exception { return function.apply((A) results.get(0), (B) results.get(1), (C) results.get(2), (D) results.get(3)); } }); }
From source file:io.vitess.client.VTGateConn.java
/** * Execute multiple keyspace ID queries as a batch. * * @param asTransaction If true, automatically create a transaction (per shard) that encloses all * the batch queries.//from w w w . j av a2s . c om */ public SQLFuture<List<Cursor>> executeBatchKeyspaceIds(Context ctx, Iterable<? extends BoundKeyspaceIdQuery> queries, TabletType tabletType, boolean asTransaction, Query.ExecuteOptions.IncludedFields includedFields) throws SQLException { ExecuteBatchKeyspaceIdsRequest.Builder requestBuilder = ExecuteBatchKeyspaceIdsRequest.newBuilder() .addAllQueries(checkNotNull(queries)).setTabletType(checkNotNull(tabletType)) .setAsTransaction(asTransaction) .setOptions(Query.ExecuteOptions.newBuilder().setIncludedFields(includedFields)); if (ctx.getCallerId() != null) { requestBuilder.setCallerId(ctx.getCallerId()); } return new SQLFuture<List<Cursor>>( transformAsync(client.executeBatchKeyspaceIds(ctx, requestBuilder.build()), new AsyncFunction<ExecuteBatchKeyspaceIdsResponse, List<Cursor>>() { @Override public ListenableFuture<List<Cursor>> apply(ExecuteBatchKeyspaceIdsResponse response) throws Exception { Proto.checkError(response.getError()); return Futures.<List<Cursor>>immediateFuture( Proto.toCursorList(response.getResultsList())); } }, directExecutor())); }
From source file:org.opendaylight.openflowplugin.applications.frsync.impl.strategy.SyncPlanPushStrategyIncrementalImpl.java
ListenableFuture<RpcResult<Void>> removeRedundantGroups(final NodeId nodeId, final InstanceIdentifier<FlowCapableNode> nodeIdent, final List<ItemSyncBox<Group>> groupsRemovalPlan, final SyncCrudCounters counters) { if (groupsRemovalPlan.isEmpty()) { LOG.trace("no groups on device for node: {} -> SKIPPING", nodeId.getValue()); return RpcResultBuilder.<Void>success().buildFuture(); }/* ww w . j a va 2 s. c o m*/ final CrudCounts groupCrudCounts = counters.getGroupCrudCounts(); ListenableFuture<RpcResult<Void>> chainedResult = RpcResultBuilder.<Void>success().buildFuture(); try { groupCrudCounts.setRemoved(ReconcileUtil.countTotalPushed(groupsRemovalPlan)); if (LOG.isDebugEnabled()) { LOG.debug("removing groups: planSteps={}, toRemoveTotal={}", groupsRemovalPlan.size(), groupCrudCounts.getRemoved()); } Collections.reverse(groupsRemovalPlan); for (final ItemSyncBox<Group> groupsPortion : groupsRemovalPlan) { chainedResult = Futures.transform(chainedResult, new AsyncFunction<RpcResult<Void>, RpcResult<Void>>() { @Override public ListenableFuture<RpcResult<Void>> apply(final RpcResult<Void> input) throws Exception { final ListenableFuture<RpcResult<Void>> result; if (input.isSuccessful()) { result = flushRemoveGroupPortionAndBarrier(nodeIdent, groupsPortion); } else { // pass through original unsuccessful rpcResult result = Futures.immediateFuture(input); } return result; } }); } } catch (IllegalStateException e) { chainedResult = RpcResultBuilder.<Void>failed() .withError(RpcError.ErrorType.APPLICATION, "failed to add missing groups", e).buildFuture(); } return chainedResult; }
From source file:com.spotify.helios.client.HeliosClient.java
public ListenableFuture<VersionResponse> version() { // Create a fallback in case we fail to connect to the master. Return null if this happens. // The transform below will handle this and return an appropriate error message to the caller. final ListenableFuture<Response> futureWithFallback = withFallback(request(uri("/version/"), "GET"), new FutureFallback<Response>() { @Override//from w w w.ja v a 2 s . c o m public ListenableFuture<Response> create(@NotNull Throwable t) throws Exception { return immediateFuture(null); } }); return transform(futureWithFallback, new AsyncFunction<Response, VersionResponse>() { @Override public ListenableFuture<VersionResponse> apply(@NotNull Response reply) throws Exception { final String masterVersion = reply == null ? "Unable to connect to master" : reply.status() == HTTP_OK ? Json.read(reply.payload(), String.class) : "Master replied with error code " + reply.status(); return immediateFuture(new VersionResponse(Version.POM_VERSION, masterVersion)); } }); }
From source file:org.opendaylight.faas.fabric.general.FabricServiceAPIProvider.java
@Override public Future<RpcResult<CreateGatewayOutput>> createGateway(CreateGatewayInput input) { final RpcResultBuilder<CreateGatewayOutput> resultBuilder = RpcResultBuilder.<CreateGatewayOutput>success(); CreateGatewayOutputBuilder outputBuilder = new CreateGatewayOutputBuilder(); final FabricId fabricId = input.getFabricId(); final NodeId routerId = input.getLogicalRouter(); final NodeId swId = input.getLogicalSwitch(); final FabricInstance fabricObj = FabricInstanceCache.INSTANCE.retrieveFabric(fabricId); if (fabricObj == null) { return Futures.immediateFailedFuture( new IllegalArgumentException(String.format("fabric %s does not exist", fabricId))); }/*from w ww .ja va 2 s .co m*/ WriteTransaction trans = dataBroker.newWriteOnlyTransaction(); // add logic port to Router TpId tpid1 = createGWPortOnRouter(input, outputBuilder, trans, fabricObj); // add logic port to switch TpId tpid2 = createGWPortOnSwitch(fabricId, swId, trans); // add link LinkId linkId = createGatewayLink(routerId, tpid1); createLogicLink(fabricId, routerId, swId, trans, tpid1, tpid2, linkId); return Futures.transform(trans.submit(), new AsyncFunction<Void, RpcResult<CreateGatewayOutput>>() { @Override public ListenableFuture<RpcResult<CreateGatewayOutput>> apply(Void submitResult) throws Exception { resultBuilder.withResult(outputBuilder); return Futures.immediateFuture(resultBuilder.build()); } }, executor); }
From source file:io.vitess.client.VTGateTx.java
public synchronized SQLFuture<Void> commit(Context ctx, boolean atomic) throws SQLException { checkCallIsAllowed("commit"); CommitRequest.Builder requestBuilder = CommitRequest.newBuilder().setSession(session).setAtomic(atomic); if (ctx.getCallerId() != null) { requestBuilder.setCallerId(ctx.getCallerId()); }/*from ww w .j a v a2 s. c o m*/ SQLFuture<Void> call = new SQLFuture<>(transformAsync(client.commit(ctx, requestBuilder.build()), new AsyncFunction<CommitResponse, Void>() { @Override public ListenableFuture<Void> apply(CommitResponse response) throws Exception { setSession(null); return Futures.<Void>immediateFuture(null); } }, directExecutor())); lastCall = call; return call; }
From source file:org.jenkinsci.plugins.workflow.support.concurrent.Futures.java
/** * <p>Returns a new {@code ListenableFuture} whose result is asynchronously * derived from the result of the given {@code Future}. More precisely, the * returned {@code Future} takes its result from a {@code Future} produced by * applying the given {@code Function} to the result of the original {@code * Future}. Example://from w w w .j av a 2 s .c o m * * <pre> {@code * ListenableFuture<RowKey> rowKeyFuture = indexService.lookUp(query); * Function<RowKey, ListenableFuture<QueryResult>> queryFunction = * new Function<RowKey, ListenableFuture<QueryResult>>() { * public ListenableFuture<QueryResult> apply(RowKey rowKey) { * return dataService.read(rowKey); * } * }; * ListenableFuture<QueryResult> queryFuture = * chain(rowKeyFuture, queryFunction, executor); * }</pre> * * <p>The returned {@code Future} attempts to keep its cancellation state in * sync with that of the input future and that of the future returned by the * chain function. That is, if the returned {@code Future} is cancelled, it * will attempt to cancel the other two, and if either of the other two is * cancelled, the returned {@code Future} will receive a callback in which it * will attempt to cancel itself. * * <p>Note: For cases in which the work of creating the derived future is * fast and lightweight, consider {@linkplain Futures#chain(ListenableFuture, * Function) the other overload} or explicit use of {@code * sameThreadExecutor}. For heavier derivations, this choice carries some * caveats: First, the thread that the derivation runs in depends on whether * the input {@code Future} is done at the time {@code chain} is called. In * particular, if called late, {@code chain} will run the derivation in the * thread that called {@code chain}. Second, derivations may run in an * internal thread of the system responsible for the input {@code Future}, * such as an RPC network thread. Finally, during the execution of a {@code * sameThreadExecutor} {@code chain} function, all other registered but * unexecuted listeners are prevented from running, even if those listeners * are to run in other executors. * * @param input The future to chain * @param function A function to chain the results of the provided future * to the results of the returned future. * @param executor Executor to run the function in. * @return A future that holds result of the chain. * @deprecated Convert your {@code Function} to a {@code AsyncFunction}, and * use {@link #transform(ListenableFuture, AsyncFunction, Executor)}. This * method is scheduled to be removed from Guava in Guava release 12.0. */ @Deprecated /*package*/ static <I, O> ListenableFuture<O> chain(ListenableFuture<I> input, final Function<? super I, ? extends ListenableFuture<? extends O>> function, Executor executor) { checkNotNull(function); ChainingListenableFuture<I, O> chain = new ChainingListenableFuture<I, O>(new AsyncFunction<I, O>() { @Override /* * All methods of ListenableFuture are covariant, and we don't expose * the object anywhere that would allow it to be downcast. */ @SuppressWarnings("unchecked") public ListenableFuture<O> apply(I input) { return (ListenableFuture) function.apply(input); } }, input); input.addListener(chain, executor); return chain; }