List of usage examples for com.google.common.util.concurrent AsyncFunction AsyncFunction
AsyncFunction
From source file:io.vitess.client.VTGateTx.java
public synchronized SQLFuture<Void> rollback(Context ctx) throws SQLException { checkCallIsAllowed("rollback"); RollbackRequest.Builder requestBuilder = RollbackRequest.newBuilder().setSession(session); if (ctx.getCallerId() != null) { requestBuilder.setCallerId(ctx.getCallerId()); }//from w w w . j av a 2s . com SQLFuture<Void> call = new SQLFuture<>(transformAsync(client.rollback(ctx, requestBuilder.build()), new AsyncFunction<RollbackResponse, Void>() { @Override public ListenableFuture<Void> apply(RollbackResponse response) throws Exception { setSession(null); return Futures.<Void>immediateFuture(null); } }, directExecutor())); lastCall = call; return call; }
From source file:com.continuuity.weave.yarn.ApplicationMasterService.java
@Override public ListenableFuture<State> start() { return Futures.transform(zkClientService.start(), new AsyncFunction<State, State>() { @Override//from ww w. j av a 2 s. c o m public ListenableFuture<State> apply(State input) throws Exception { return serviceDelegate.start(); } }); }
From source file:com.continuuity.weave.internal.ZKServiceDecorator.java
private <V> ListenableFuture<State> stopServiceOnComplete(ListenableFuture<V> future, final Service service) { return Futures.transform(future, new AsyncFunction<V, State>() { @Override// ww w. j a va2 s . co m public ListenableFuture<State> apply(V input) throws Exception { return service.stop(); } }); }
From source file:org.opendaylight.centinel.impl.CentinelStreamImpl.java
@Override public Future<RpcResult<DeleteStreamOutput>> deleteStream(final DeleteStreamInput input) { final ReadWriteTransaction tx = dataProvider.newReadWriteTransaction(); final SettableFuture<RpcResult<DeleteStreamOutput>> futureResult = SettableFuture.create(); boolean idMatches = false; if (input.getStreamID() == null || input.getStreamID().isEmpty() || input.getStreamID().trim().isEmpty()) { LOG.debug("STREAM ID CANNOT BE NULL"); return Futures.immediateFailedCheckedFuture( new TransactionCommitFailedException("inalid-input", streamIdcannotbenullError())); }//from ww w .ja v a2 s.c o m final DeleteStreamOutputBuilder deleteStreamRuleOutputBuilder = new DeleteStreamOutputBuilder(); deleteStreamRuleOutputBuilder.setMessage(input.getStreamID()); ListenableFuture<Optional<StreamRecord>> readFutureOperational = tx.read(LogicalDatastoreType.OPERATIONAL, streamRecordId); ListenableFuture<Optional<StreamRecord>> readFutureConfigure = tx.read(LogicalDatastoreType.CONFIGURATION, streamRecordId); String configId = null; try { Optional<StreamRecord> record = readFutureOperational.get(); if (record.isPresent()) { StreamRecord operationalRecord = readFutureOperational.get().get(); List<StreamList> streamList = new ArrayList<StreamList>(); if (!operationalRecord.getStreamList().isEmpty()) { streamList = operationalRecord.getStreamList(); Iterator<StreamList> iterator = streamList.iterator(); while (iterator.hasNext()) { StreamList operationalObject = iterator.next(); if (operationalObject.getStreamID().equals(input.getStreamID())) { configId = operationalObject.getConfigID(); idMatches = true; } } if (!idMatches) { return Futures.immediateFailedCheckedFuture(new TransactionCommitFailedException( "invalid-input", RpcResultBuilder.newError(ErrorType.APPLICATION, "invalid-input", "Invalid Stream id or The stream is not present in operational data store"))); } } } else { return Futures.immediateFailedCheckedFuture(new TransactionCommitFailedException("invalid-input", RpcResultBuilder.newError(ErrorType.APPLICATION, "invalid-input", "Record is not present in operational data store"))); } } catch (Exception ex) { deleteStreamRuleOutputBuilder .setMessage("Stream with stream id" + input.getStreamID() + "does not exists"); return Futures.immediateFailedCheckedFuture(new TransactionCommitFailedException("invalid-input", RpcResultBuilder.newError(ErrorType.APPLICATION, "invalid-input", "Invalid Stream id or The stream is not present in operational data store"))); } final String confID = configId; final ListenableFuture<Void> commitFuture = Futures.transform(readFutureConfigure, new AsyncFunction<Optional<StreamRecord>, Void>() { @Override public ListenableFuture<Void> apply(final Optional<StreamRecord> streamRulesRecord) throws Exception { List<StreamList> streamRulesLists = new ArrayList<StreamList>(); if (streamRulesRecord.isPresent()) { streamRulesLists = streamRulesRecord.get().getStreamList(); } Iterator<StreamList> iterator = streamRulesLists.iterator(); while (iterator.hasNext()) { StreamList configObject = iterator.next(); if (configObject.getConfigID().equalsIgnoreCase(confID)) { tx.delete(LogicalDatastoreType.CONFIGURATION, streamRecordId.child(StreamList.class, configObject.getKey())); } } return tx.submit(); } }); Futures.addCallback(commitFuture, new FutureCallback<Void>() { @Override public void onSuccess(final Void result) { futureResult.set(RpcResultBuilder.<DeleteStreamOutput>success(deleteStreamRuleOutputBuilder.build()) .build()); } @Override public void onFailure(final Throwable ex) { LOG.debug("Failed to commit Rule", ex); futureResult.set(RpcResultBuilder.<DeleteStreamOutput>failed() .withRpcErrors(((TransactionCommitFailedException) ex).getErrorList()).build()); } }); return futureResult; }
From source file:com.continuuity.weave.yarn.ApplicationMasterService.java
@Override public ListenableFuture<State> stop() { return Futures.transform(serviceDelegate.stop(), new AsyncFunction<State, State>() { @Override/* www .j a va2s. c o m*/ public ListenableFuture<State> apply(State input) throws Exception { return zkClientService.stop(); } }); }
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 e a ListenableFuture to combine * @param function the implementation of the transform * @return a ListenableFuture holding the result of function.apply() *///ww w .j a v a 2 s.co m public static <Z, A, B, C, D, E> ListenableFuture<Z> asyncTransform5(ListenableFuture<A> a, ListenableFuture<B> b, ListenableFuture<C> c, ListenableFuture<D> d, ListenableFuture<E> e, final AsyncFunction5<Z, ? super A, ? super B, ? super C, ? super D, ? super E> function) { return transform(Arrays.asList(a, b, c, d, e), 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), (E) results.get(4)); } }); }
From source file:com.microsoft.intellij.helpers.o365.Office365ManagerImpl.java
private <T> ListenableFuture<T> getFirstItem(ListenableFuture<List<T>> future) { return Futures.transform(future, new AsyncFunction<List<T>, T>() { @Override//from w w w.ja v a2 s .c o m public ListenableFuture<T> apply(List<T> items) throws Exception { return Futures.immediateFuture((items != null && items.size() > 0) ? items.get(0) : null); } }); }
From source file:com.datastax.driver.mapping.Mapper.java
/** * Fetch an entity based on its primary key asynchronously. * <p/>//from w ww . ja v a 2 s . com * This method is basically equivalent to mapping the result of: {@code getManager().getSession().executeAsync(getQuery(objects))}. * * @param objects the primary key of the entity to fetch, or more precisely * the values for the columns of said primary key in the order of the primary key. * Can be followed by {@link Option} to include in the DELETE query. * @return a future on the fetched entity. The return future will yield * {@code null} if said entity doesn't exist. * @throws IllegalArgumentException if the number of value provided differ from * the number of columns composing the PRIMARY KEY of the mapped class, or if * at least one of those values is {@code null}. */ public ListenableFuture<T> getAsync(final Object... objects) { ListenableFuture<BoundStatement> bsFuture = getQueryAsync(objects); ListenableFuture<ResultSet> rsFuture = Futures.transform(bsFuture, new AsyncFunction<BoundStatement, ResultSet>() { @Override public ListenableFuture<ResultSet> apply(BoundStatement bs) throws Exception { return session().executeAsync(bs); } }); return Futures.transform(rsFuture, mapOneFunction); }
From source file:io.vitess.client.VTGateConn.java
public SQLFuture<VTGateTx> begin(Context ctx, boolean singleDB) throws SQLException { BeginRequest.Builder requestBuilder = BeginRequest.newBuilder().setSingleDb(singleDB); if (ctx.getCallerId() != null) { requestBuilder.setCallerId(ctx.getCallerId()); }//from w w w . j a va 2 s . c om return new SQLFuture<VTGateTx>(transformAsync(client.begin(ctx, requestBuilder.build()), new AsyncFunction<BeginResponse, VTGateTx>() { @Override public ListenableFuture<VTGateTx> apply(BeginResponse response) throws Exception { return Futures .<VTGateTx>immediateFuture(new VTGateTx(client, response.getSession(), keyspace)); } }, directExecutor())); }
From source file:com.bt.sitb.opendaylight.controller.sample.btil.provider.OpendaylightBtil.java
private void checkStatusAndMakeToast(final MakeToastInput input, final SettableFuture<RpcResult<Void>> futureResult, final int tries) { LOG.info("checkStatusAndMakeToast input={}", input); // Read the BtilStatus and, if currently Up, try to write the status to Down. // If that succeeds, then we essentially have an exclusive lock and can proceed // to make toast. LOG.info("Reading from id={}", TOASTER_IID); final ReadWriteTransaction tx = dataProvider.newReadWriteTransaction(); ListenableFuture<Optional<SitbBtil>> readFuture = tx.read(LogicalDatastoreType.OPERATIONAL, TOASTER_IID); final ListenableFuture<Void> commitFuture = Futures.transform(readFuture, new AsyncFunction<Optional<SitbBtil>, Void>() { @Override/*from ww w . j a va2 s .com*/ public ListenableFuture<Void> apply(final Optional<SitbBtil> btilData) throws Exception { SitbBtil.BtilStatus btilStatus = SitbBtil.BtilStatus.Up; if (btilData.isPresent()) { btilStatus = btilData.get().getBtilStatus(); } LOG.debug("Read btil status: {}", btilStatus); if (btilStatus == SitbBtil.BtilStatus.Up) { if (outOfBread()) { LOG.debug("Btil is out of bread"); return Futures.immediateFailedCheckedFuture( new TransactionCommitFailedException("", makeBtilOutOfBreadError())); } LOG.debug("Setting Btil status to Down"); // We're not currently making toast - try to update the status to Down // to indicate we're going to make toast. This acts as a lock to prevent // concurrent toasting. tx.put(LogicalDatastoreType.OPERATIONAL, TOASTER_IID, buildBtil(SitbBtil.BtilStatus.Down)); return tx.submit(); } LOG.debug("Oops - already making toast!"); // Return an error since we are already making toast. This will get // propagated to the commitFuture below which will interpret the null // TransactionStatus in the RpcResult as an error condition. return Futures.immediateFailedCheckedFuture( new TransactionCommitFailedException("", makeBtilInUseError())); } }); Futures.addCallback(commitFuture, new FutureCallback<Void>() { @Override public void onSuccess(final Void result) { // OK to make toast currentMakeToastTask.set(executor.submit(new MakeToastTask(input, futureResult))); } @Override public void onFailure(final Throwable ex) { if (ex instanceof OptimisticLockFailedException) { // Another thread is likely trying to make toast simultaneously and updated the // status before us. Try reading the status again - if another make toast is // now in progress, we should get BtilStatus.Down and fail. if ((tries - 1) > 0) { LOG.debug("Got OptimisticLockFailedException - trying again"); checkStatusAndMakeToast(input, futureResult, tries - 1); } else { futureResult.set(RpcResultBuilder.<Void>failed() .withError(ErrorType.APPLICATION, ex.getMessage()).build()); } } else { LOG.debug("Failed to commit Btil status", ex); // Probably already making toast. futureResult.set(RpcResultBuilder.<Void>failed() .withRpcErrors(((TransactionCommitFailedException) ex).getErrorList()).build()); } } }); }