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)
From source file:org.dcache.poolmanager.RendezvousPoolManagerHandler.java
@Override @SuppressWarnings("unchecked") public <T extends PoolManagerMessage> ListenableFuture<T> sendAsync(CellEndpoint endpoint, T msg, long timeout) { if (msg instanceof PoolManagerGetRestoreHandlerInfo) { return (ListenableFuture<T>) Futures.transform( allSuccessful(endpoint, "xrc ls", RestoreHandlerInfo[].class, timeout), l -> new PoolManagerGetRestoreHandlerInfo( l.stream().filter(Objects::nonNull).flatMap(Stream::of).collect(toList()))); } else {//from w w w. jav a 2s .co m return submit(endpoint, new CellPath(backendFor(msg)), msg, timeout); } }
From source file:org.opendaylight.controller.sample.kitchen.impl.KitchenServiceImpl.java
@Override public Future<RpcResult<Void>> makeBreakfast(EggsType eggsType, Class<? extends ToastType> toastType, int toastDoneness) { // Call makeToast and use JdkFutureAdapters to convert the Future to a ListenableFuture, // The OpendaylightToaster impl already returns a ListenableFuture so the conversion is // actually a no-op. ListenableFuture<RpcResult<Void>> makeToastFuture = JdkFutureAdapters .listenInPoolThread(makeToast(toastType, toastDoneness), executor); ListenableFuture<RpcResult<Void>> makeEggsFuture = makeEggs(eggsType); // Combine the 2 ListenableFutures into 1 containing a list of RpcResults. ListenableFuture<List<RpcResult<Void>>> combinedFutures = Futures .allAsList(ImmutableList.of(makeToastFuture, makeEggsFuture)); // Then transform the RpcResults into 1. return Futures.transform(combinedFutures, new AsyncFunction<List<RpcResult<Void>>, RpcResult<Void>>() { @Override//from ww w . j av a2 s. c om public ListenableFuture<RpcResult<Void>> apply(List<RpcResult<Void>> results) throws Exception { boolean atLeastOneSucceeded = false; Builder<RpcError> errorList = ImmutableList.builder(); for (RpcResult<Void> result : results) { if (result.isSuccessful()) { atLeastOneSucceeded = true; } if (result.getErrors() != null) { errorList.addAll(result.getErrors()); } } return Futures.immediateFuture(RpcResultBuilder.<Void>status(atLeastOneSucceeded) .withRpcErrors(errorList.build()).build()); } }); }
From source file:com.spotify.futures.FuturesExtra.java
/** * This takes two futures of type {@link A} and {@link B} and works like * a valve on {@link A}, with validation executed on {@link B}. * * Returns a future with the result of {@link A} that will wait for a * condition on {@link B} to be validated first. Both futures can run in * parallel. If the condition fails validation, the {@link A} future will * be cancelled by a call to {@link ListenableFuture#cancel(boolean)} with * {@code false}./*ww w . j ava 2s . com*/ * * This is useful for when you want to optimistically run a time consuming * path while validating if it should be computed or not by a parallel * async computation. * * @param conditionValue The future computing the value for validation. * @param future The actual value future. * @param validator A validator for the condition. * * @return a new {@link ListenableFuture} eventually either containing * {@param future} or any exception thrown by {@param validator}. */ public static <A, B> ListenableFuture<A> fastFail(final ListenableFuture<B> conditionValue, final ListenableFuture<A> future, final Validator<B> validator) { return Futures.transform(conditionValue, new AsyncFunction<B, A>() { @Override public ListenableFuture<A> apply(B value) throws Exception { try { validator.validate(value); return future; } catch (Exception e) { future.cancel(false); throw e; } } }); }
From source file:com.continuuity.weave.internal.AbstractServiceController.java
@Override public ListenableFuture<State> stop() { State oldState = state.getAndSet(State.STOPPING); if (oldState == null || oldState == State.STARTING || oldState == State.RUNNING) { return Futures.transform(ZKMessages.sendMessage(zkClient, getZKPath("messages/msg"), SystemMessages.stopApplication(), State.TERMINATED), new AsyncFunction<State, State>() { @Override/*from w ww. j a va 2s .co m*/ public ListenableFuture<State> apply(State input) throws Exception { // Wait for the instance ephemeral node goes away return Futures.transform(ZKOperations.watchDeleted(zkClient, "/instances/" + runId), new Function<String, State>() { @Override public State apply(String input) { LOG.info("Remote service stopped: " + runId); state.set(State.TERMINATED); fireStateChange(new StateNode(State.TERMINATED, null)); return State.TERMINATED; } }); } }); } state.set(oldState); return Futures.immediateFuture(getState()); }
From source file:org.opendaylight.netconf.sal.connect.netconf.sal.SchemalessNetconfDeviceRpc.java
private CheckedFuture<DOMRpcResult, DOMRpcException> handleRpc(@Nonnull final SchemaPath type, @Nullable final NormalizedNode<?, ?> input, final MessageTransformer<NetconfMessage> transformer) { final NetconfMessage netconfMessage = transformer.toRpcRequest(type, input); final ListenableFuture<RpcResult<NetconfMessage>> rpcResultListenableFuture = listener .sendRequest(netconfMessage, type.getLastComponent()); final ListenableFuture<DOMRpcResult> transformed = Futures.transform(rpcResultListenableFuture, new Function<RpcResult<NetconfMessage>, DOMRpcResult>() { @Override/*from ww w.ja v a 2 s. c o m*/ public DOMRpcResult apply(final RpcResult<NetconfMessage> input) { if (input.isSuccessful()) { return transformer.toRpcResult(input.getResult(), type); } else { return new DefaultDOMRpcResult(input.getErrors()); } } }); return Futures.makeChecked(transformed, new Function<Exception, DOMRpcException>() { @Nullable @Override public DOMRpcException apply(@Nullable final Exception e) { return new DOMRpcImplementationNotAvailableException(e, "Unable to invoke rpc %s on device %s", type, deviceId); } }); }
From source file:com.android.tools.idea.apk.viewer.ApkParser.java
@NotNull public synchronized ListenableFuture<Long> getUncompressedApkSize() { return Futures.transform(constructTreeStructure(), (Function<DefaultMutableTreeNode, Long>) input -> { ApkEntry entry = ApkEntry.fromNode(input); assert entry != null; return entry.getSize(); });//from www. j a v a 2 s .c om }
From source file:com.facebook.presto.operator.PartitionedOutputOperator.java
public PartitionedOutputOperator(OperatorContext operatorContext, List<Type> sourceTypes, SharedBuffer sharedBuffer) {//from w w w . ja v a 2 s. c o m this.operatorContext = requireNonNull(operatorContext, "operatorContext is null"); this.partitionFunction = Futures.transform(sharedBuffer.getFinalOutputBuffers(), (OutputBuffers outputBuffers) -> { return new PartitionFunction(sharedBuffer, sourceTypes, outputBuffers); }); }
From source file:org.opendaylight.mdsal.dom.broker.ShardedDOMWriteTransactionAdapter.java
@Override public CheckedFuture<Void, TransactionCommitFailedException> submit() { checkRunning();/* ww w . j a v a 2 s. co m*/ LOG.debug("{}: Submitting transaction", txIdentifier); if (!initialized) { // If underlying producers, transactions and cursors are // not even initialized just seal this transaction and // return immediate future finished = true; return Futures.immediateCheckedFuture(null); } // First we need to close cursors cursorMap.values().forEach(DOMDataTreeWriteCursor::close); final ListenableFuture<List<Void>> aggregatedSubmit = Futures.allAsList( transactionMap.get(LogicalDatastoreType.CONFIGURATION).submit(), transactionMap.get(LogicalDatastoreType.OPERATIONAL).submit()); // Now we can close producers and mark transaction as finished closeProducers(); finished = true; return Futures.makeChecked(Futures.transform(aggregatedSubmit, (List<Void> input) -> input.get(0)), TransactionCommitFailedExceptionMapper.COMMIT_ERROR_MAPPER); }
From source file:com.continuuity.weave.internal.WeaveContainerMain.java
private static Service wrapService(final ZKClientService zkClientService, final Service containerService) { return new Service() { @Override/*from w w w . j av a2 s . c o m*/ public ListenableFuture<State> start() { return Futures.transform(Services.chainStart(zkClientService, containerService), new AsyncFunction<List<ListenableFuture<State>>, State>() { @Override public ListenableFuture<State> apply(List<ListenableFuture<State>> input) throws Exception { return input.get(1); } }); } @Override public State startAndWait() { return Futures.getUnchecked(start()); } @Override public boolean isRunning() { return containerService.isRunning(); } @Override public State state() { return containerService.state(); } @Override public ListenableFuture<State> stop() { return Futures.transform(Services.chainStop(containerService, zkClientService), new AsyncFunction<List<ListenableFuture<State>>, State>() { @Override public ListenableFuture<State> apply(List<ListenableFuture<State>> input) throws Exception { return input.get(0); } }); } @Override public State stopAndWait() { return Futures.getUnchecked(stop()); } @Override public void addListener(Listener listener, Executor executor) { containerService.addListener(listener, executor); } }; }
From source file:net.oneandone.troilus.DBSession.java
/** * @param preparedStatementFuture the prepared statement future to bind * @param values the values to bind /*from w w w. j a va 2 s.c o m*/ * @return the statement future */ public ListenableFuture<Statement> bindAsync(ListenableFuture<PreparedStatement> preparedStatementFuture, final Object[] values) { Function<PreparedStatement, Statement> bindStatementFunction = new Function<PreparedStatement, Statement>() { @Override public Statement apply(PreparedStatement preparedStatement) { return preparedStatement.bind(values); } }; return Futures.transform(preparedStatementFuture, bindStatementFunction); }