Example usage for com.google.common.util.concurrent AsyncFunction AsyncFunction

List of usage examples for com.google.common.util.concurrent AsyncFunction AsyncFunction

Introduction

In this page you can find the example usage for com.google.common.util.concurrent AsyncFunction AsyncFunction.

Prototype

AsyncFunction

Source Link

Usage

From source file:org.robotninjas.barge.rpc.netty.ProtoRpcRaftClient.java

private <T> ListenableFuture<T> call(final RpcCall<T> call) {
    LOGGER.debug("Sending message to {}: {}", replica, call);

    ListenableFuture<NettyRpcChannel> channel = null;
    try {/*from   ww w .j  a v a2  s .  co m*/

        channel = channelPool.borrowObject();
        ListenableFuture<T> response = transform(channel, new AsyncFunction<NettyRpcChannel, T>() {
            @Override
            public ListenableFuture<T> apply(NettyRpcChannel channel) throws Exception {
                RaftProto.RaftService.Stub stub = RaftProto.RaftService.newStub(channel);
                ClientController controller = new ClientController(channel);
                controller.setTimeout(DEFAULT_TIMEOUT, TimeUnit.MILLISECONDS);
                RpcHandlerFuture<T> responseHandler = new RpcHandlerFuture<T>(controller);
                call.call(stub, controller, responseHandler);
                return responseHandler;
            }
        });

        response.addListener(returnChannel(channel), sameThreadExecutor());

        return response;

    } catch (Exception e) {

        try {
            channelPool.invalidateObject(channel);
        } catch (Exception ignored) {
        }
        channel = null;
        return immediateFailedFuture(e);

    } finally {

        try {
            if (null != channel) {
                channelPool.returnObject(channel);
            }
        } catch (Exception ignored) {
        }

    }
}

From source file:org.opendaylight.toaster.impl.ToasterServiceImpl.java

@Override
public Future<RpcResult<java.lang.Void>> cancelToast() {
    LOG.info("cancelToast");
    final InstanceIdentifier<Toaster> TOASTER_IID = InstanceIdentifier.builder(Toaster.class).build();
    final ReadWriteTransaction tx = broker.newReadWriteTransaction();
    ListenableFuture<Optional<Toaster>> readFuture = tx.read(LogicalDatastoreType.OPERATIONAL, TOASTER_IID);

    //Optional<Toaster>ListenableFuture??VoidListenableFuture
    final ListenableFuture<Void> commitFuture = Futures.transform(readFuture,
            new AsyncFunction<Optional<Toaster>, Void>() {

                @Override/*from   w ww.  j a v a  2s  .c  o  m*/
                public ListenableFuture<Void> apply(final Optional<Toaster> toasterData) throws Exception {
                    //?toastertasterStatus
                    ToasterStatus toasterStatus = ToasterStatus.Down;
                    if (toasterData.isPresent()) {
                        toasterStatus = toasterData.get().getToasterStatus();
                    }

                    //???Up
                    if (toasterStatus == ToasterStatus.Down) {
                        //Down?
                        LOG.info("the toaster is not running!");
                        return Futures.immediateFailedCheckedFuture(new TransactionCommitFailedException("",
                                RpcResultBuilder.newWarning(ErrorType.APPLICATION, "not-in-use",
                                        "Toaster is not running", null, null, null)));
                    } else {
                        //up??down?
                        tx.put(LogicalDatastoreType.OPERATIONAL, TOASTER_IID,
                                new ToasterBuilder().setToasterStatus(ToasterStatus.Down).build());
                        return tx.submit();
                    }
                }
            });

    //callback
    Futures.addCallback(commitFuture, new FutureCallback<Void>() {
        @Override
        public void onSuccess(final Void result) {
            // data store?makeToast
            LOG.info("******Task was canceled.******");
        }

        @Override
        public void onFailure(final Throwable ex) {
            LOG.debug("Failed to commit Toaster status", ex);
        }
    });
    return Futures.immediateFuture(RpcResultBuilder.<Void>success().build());
}

From source file:com.android.camera.one.v2.initialization.PreviewStarter.java

/**
 * See {@link OneCamera#startPreview}.//w w  w .  jav a  2  s .c  om
 *
 * @param surface The preview surface to use.
 */
public ListenableFuture<Void> startPreview(final Surface surface) {
    // When we have the preview surface, start the capture session.
    List<Surface> surfaceList = new ArrayList<>();

    // Workaround of the face detection failure on Nexus 5 and L. (b/21039466)
    // Need to create a capture session with the single preview stream first
    // to lock it as the first stream. Then resend the another session with preview
    // and JPEG stream.
    if (ApiHelper.isLorLMr1() && ApiHelper.IS_NEXUS_5) {
        surfaceList.add(surface);
        mCaptureSessionCreator.createCaptureSession(surfaceList);
        surfaceList.addAll(mOutputSurfaces);
    } else {
        surfaceList.addAll(mOutputSurfaces);
        surfaceList.add(surface);
    }

    final ListenableFuture<CameraCaptureSessionProxy> sessionFuture = mCaptureSessionCreator
            .createCaptureSession(surfaceList);

    return Futures.transform(sessionFuture, new AsyncFunction<CameraCaptureSessionProxy, Void>() {
        @Override
        public ListenableFuture<Void> apply(CameraCaptureSessionProxy captureSession) throws Exception {
            mSessionListener.onCameraCaptureSessionCreated(captureSession, surface);
            return Futures.immediateFuture(null);
        }
    });
}

From source file:org.robotninjas.util.examples.FunctionComposerExample.java

AsyncFunction<List<File>, List<File>> backupFiles() {
    return new AsyncFunction<List<File>, List<File>>() {
        @Override//from  w w w . jav  a2 s.co m
        public ListenableFuture<List<File>> apply(List<File> input) throws Exception {
            System.out.println("5");
            return immediateFuture((List<File>) Lists.<File>newArrayList());
        }
    };
}

From source file:com.facebook.buck.parser.ParserLeaseVendor.java

/**
 * @param cell the cell in which we're parsing
 * @param withParser the function that performs the interaction with the parser
 * @param executorService where to apply the async function
 * @param <T> type of result//ww w .  jav  a2s. c  om
 * @return a {@link ListenableFuture} that will run the supplied AsyncFunction when a parser
 *         is available.
 */
public <T> ListenableFuture<T> leaseParser(final Cell cell, final AsyncFunction<P, T> withParser,
        ListeningExecutorService executorService) {
    Preconditions.checkState(!closed.get());

    final ListenableFuture<P> obtainedParser = obtainParser(cell);
    ListenableFuture<T> futureWork = Futures.transformAsync(obtainedParser, new AsyncFunction<P, T>() {
        @Override
        public ListenableFuture<T> apply(P input) throws Exception {
            try {
                return withParser.apply(input);
            } finally {
                returnParser(cell, input);
            }
        }
    }, executorService);
    return futureWork;
}

From source file:com.orangerhymelabs.helenus.cassandra.view.ViewService.java

public ListenableFuture<View> update(View view) {
    ListenableFuture<Boolean> tableFuture = tables.exists(view.databaseName(), view.tableName());
    return Futures.transformAsync(tableFuture, new AsyncFunction<Boolean, View>() {
        @Override//w ww.j  a  va2s.c  o  m
        public ListenableFuture<View> apply(Boolean exists) throws Exception {
            if (exists) {
                try {
                    ValidationEngine.validateAndThrow(view);
                    return views.update(view);
                } catch (ValidationException e) {
                    return Futures.immediateFailedFuture(e);
                }
            } else {
                return Futures.immediateFailedFuture(
                        new ItemNotFoundException("Database not found: " + view.databaseName()));
            }
        }
    }, MoreExecutors.directExecutor());
}

From source file:com.orangerhymelabs.helenus.cassandra.table.TableService.java

public ListenableFuture<List<Table>> readAll(String database, Object... parms) {
    ListenableFuture<Boolean> dbFuture = databases.exists(database);
    return Futures.transformAsync(dbFuture, new AsyncFunction<Boolean, List<Table>>() {
        @Override//from  ww w.j  a  v a 2  s.  com
        public ListenableFuture<List<Table>> apply(Boolean exists) throws Exception {
            if (exists) {
                return tables.readAll(parms);
            } else {
                return Futures
                        .immediateFailedFuture(new ItemNotFoundException("Database not found: " + database));
            }
        }
    }, MoreExecutors.directExecutor());
}

From source file:org.glowroot.central.util.MoreFutures.java

public static ListenableFuture<?> rollupAsync(Collection<ListenableFuture<ResultSet>> futures,
        Executor asyncExecutor, DoRollup function) {
    return transformAsync(Futures.allAsList(futures), asyncExecutor,
            new AsyncFunction<List<ResultSet>, /*@Nullable*/ Object>() {
                @Override/*from   w ww.j  a v a2 s  .  c o  m*/
                @SuppressWarnings("unchecked")
                public ListenableFuture</*@Nullable*/ Object> apply(List<ResultSet> list) throws Exception {
                    List<Row> rows = new ArrayList<>();
                    for (ResultSet results : list) {
                        rows.addAll(results.all());
                    }
                    if (rows.isEmpty()) {
                        return Futures.immediateFuture(null);
                    }
                    return (ListenableFuture</*@Nullable*/ Object>) function.execute(rows);
                }
            });
}

From source file:io.v.v23.syncbase.nosql.DatabaseImpl.java

@Override
public ListenableFuture<QueryResults> exec(VContext ctx, String query) {
    final ClientRecvStream<List<VdlAny>, Void> stream = client.exec(ctx, getSchemaVersion(), query);
    return Futures.transform(stream.recv(), new AsyncFunction<List<VdlAny>, QueryResults>() {
        @Override/*  w w  w  . ja v a 2  s .c  o m*/
        public ListenableFuture<QueryResults> apply(List<VdlAny> columnNames) throws Exception {
            return Futures.immediateFuture((QueryResults) new QueryResultsImpl(columnNames, stream));
        }
    });
}

From source file:org.robotninjas.util.examples.FunctionComposerExample.java

AsyncFunction<File, File> copyFile(final String name, final String extension) {
    return new AsyncFunction<File, File>() {
        @Override/*from  w  w w . jav a  2 s.  c  o  m*/
        public ListenableFuture<File> apply(File input) throws Exception {
            System.out.println("6 " + name);
            return immediateFuture(new File("copy"));
        }
    };
}