Example usage for com.google.common.util.concurrent Futures transformAsync

List of usage examples for com.google.common.util.concurrent Futures transformAsync

Introduction

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

Prototype

public static <I, O> ListenableFuture<O> transformAsync(ListenableFuture<I> input,
        AsyncFunction<? super I, ? extends O> function, Executor executor) 

Source Link

Document

Returns a new ListenableFuture whose result is asynchronously derived from the result of the given Future .

Usage

From source file:com.facebook.buck.distributed.MultiSourceContentsProvider.java

private ListenableFuture<Boolean> postInlineMaterializationHelper(boolean success,
        BuildJobStateFileHashEntry entry, Path targetAbsPath) {
    if (success) {
        LOG.info("Materialized source file using Inline Data: [%s]", targetAbsPath);
        return Futures.immediateFuture(true);
    }/*from  w w w .  j a  v  a 2  s .c o m*/

    ListenableFuture<Boolean> localFsFuture;
    if (localFsProvider.isPresent()) {
        localFsFuture = localFsProvider.get().materializeFileContentsAsync(entry, targetAbsPath);
    } else {
        localFsFuture = Futures.immediateFuture(false);
    }

    return Futures.transformAsync(localFsFuture,
            (localFsSuccess) -> postLocalFsMaterializationHelper(localFsSuccess, entry, targetAbsPath),
            executorService);
}

From source file:org.opendaylight.controller.cluster.sharding.PrefixedShardConfigWriter.java

private static ListenableFuture<Void> doSubmit(final DOMStoreThreePhaseCommitCohort cohort) {
    final AsyncFunction<Boolean, Void> validateFunction = input -> cohort.preCommit();
    final AsyncFunction<Void, Void> prepareFunction = input -> cohort.commit();

    final ListenableFuture<Void> prepareFuture = Futures.transformAsync(cohort.canCommit(), validateFunction,
            MoreExecutors.directExecutor());
    return Futures.transformAsync(prepareFuture, prepareFunction, MoreExecutors.directExecutor());
}

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

@Override
public ListenableFuture<Map<String, Object>> getNodeJob(final Cell cell, final BuildTarget buildTarget)
        throws BuildTargetException {
    return Futures.transformAsync(getAllNodesJob(cell, cell.getAbsolutePathToBuildFile(buildTarget)), input -> {
        for (Map<String, Object> rawNode : input) {
            Object shortName = rawNode.get("name");
            if (buildTarget.getShortName().equals(shortName)) {
                return Futures.immediateFuture(rawNode);
            }/*from w  w  w. j  av a  2 s .com*/
        }
        throw NoSuchBuildTargetException.createForMissingBuildRule(buildTarget,
                BuildTargetPatternParser.forBaseName(buildTarget.getBaseName()), cell.getBuildFileName(),
                "Defined in file: " + cell.getAbsolutePathToBuildFile(buildTarget));
    }, executorService);
}

From source file:com.orangerhymelabs.helenus.cassandra.AbstractCassandraRepository.java

public ListenableFuture<T> update(T entity) {
    ListenableFuture<ResultSet> future = submitUpdate(entity);
    return Futures.transformAsync(future, new AsyncFunction<ResultSet, T>() {
        @Override//  w  w w .  j  a  v a  2 s  . c  o m
        public ListenableFuture<T> apply(ResultSet result) {
            if (result.wasApplied()) {
                return Futures.immediateFuture(entity);
            }

            return Futures.immediateFailedFuture(new ItemNotFoundException(entity.toString()));
        }
    }, MoreExecutors.directExecutor());
}

From source file:io.prestosql.operator.index.IndexLookupSourceFactory.java

@Override
public ListenableFuture<?> whenBuildFinishes() {
    return Futures.transformAsync(whenTaskContextSet,
            ignored -> transform(this.createLookupSourceProvider(), lookupSourceProvider -> {
                // Close the lookupSourceProvider we just created.
                // The only reason we created it is to wait until lookup source is ready.
                lookupSourceProvider.close();
                return null;
            }, directExecutor()), directExecutor());
}

From source file:com.facebook.buck.distributed.MultiSourceContentsProvider.java

private ListenableFuture<Boolean> postLocalFsMaterializationHelper(boolean success,
        BuildJobStateFileHashEntry entry, Path targetAbsPath) {
    if (success) {
        fileMaterializationStatsTracker.recordLocalFileMaterialized();
        LOG.info("Materialized source file using Local Source File Cache: [%s]", targetAbsPath);
        return Futures.immediateFuture(true);
    }/*from   w ww. j av a  2s. c o m*/

    Stopwatch remoteMaterializationStopwatch = Stopwatch.createStarted();
    return Futures.transformAsync(serverContentsProvider.materializeFileContentsAsync(entry, targetAbsPath),
            (remoteSuccess) -> postRemoteMaterializationHelper(remoteSuccess, entry, targetAbsPath,
                    remoteMaterializationStopwatch.elapsed(TimeUnit.MILLISECONDS)),
            executorService);
}

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

public ListenableFuture<Table> update(Table table) {
    ListenableFuture<Boolean> dbFuture = databases.exists(table.databaseName());
    return Futures.transformAsync(dbFuture, new AsyncFunction<Boolean, Table>() {
        @Override//  w  w  w.  j a va  2  s . c om
        public ListenableFuture<Table> apply(Boolean exists) throws Exception {
            if (exists) {
                try {
                    ValidationEngine.validateAndThrow(table);
                    return tables.update(table);
                } catch (ValidationException e) {
                    return Futures.immediateFailedFuture(e);
                }
            } else {
                return Futures.immediateFailedFuture(
                        new ItemNotFoundException("Database not found: " + table.databaseName()));
            }
        }
    }, MoreExecutors.directExecutor());
}

From source file:com.orangerhymelabs.helenus.cassandra.AbstractCassandraRepository.java

public ListenableFuture<Boolean> delete(Identifier id) {
    ListenableFuture<ResultSet> future = submitDelete(id);
    return Futures.transformAsync(future, new AsyncFunction<ResultSet, Boolean>() {
        @Override/*from w  ww .  j  av  a 2s . c om*/
        public ListenableFuture<Boolean> apply(ResultSet result) {
            if (!result.wasApplied()) {
                return Futures.immediateFailedFuture(new ItemNotFoundException(id.toString()));
            }

            return Futures.immediateFuture(true);
        }
    }, MoreExecutors.directExecutor());
}

From source file:com.facebook.buck.util.concurrent.ResourcePool.java

/**
 * @param executorService where to perform the resource processing. Should really be a "real"
 *                        executor (not a directExecutor).
 * @return a {@link ListenableFuture} containing the result of the processing. The future will be
 *         cancelled if the {@link ResourcePool#close()} method is called.
 *//*w  w  w. j  a va  2  s .  c  om*/
public synchronized <T> ListenableFuture<T> scheduleOperationWithResource(ThrowingFunction<R, T> withResource,
        final ListeningExecutorService executorService) {
    Preconditions.checkState(!closing.get());

    final ListenableFuture<T> futureWork = Futures.transformAsync(initialSchedule(),
            new AsyncFunction<Void, T>() {
                @Override
                public ListenableFuture<T> apply(Void input) throws Exception {
                    Either<R, ListenableFuture<Void>> resourceRequest = requestResource();
                    if (resourceRequest.isLeft()) {
                        R resource = resourceRequest.getLeft();
                        boolean resourceIsDefunct = false;
                        try {
                            return Futures.immediateFuture(withResource.apply(resource));
                        } catch (Exception e) {
                            resourceIsDefunct = (resourceUsageErrorPolicy == ResourceUsageErrorPolicy.RETIRE);
                            throw e;
                        } finally {
                            returnResource(resource, resourceIsDefunct);
                        }
                    } else {
                        return Futures.transformAsync(resourceRequest.getRight(), this, executorService);
                    }
                }
            }, executorService);

    pendingWork.add(futureWork);
    futureWork.addListener(() -> {
        synchronized (ResourcePool.this) {
            pendingWork.remove(futureWork);
        }
    }, executorService);

    // If someone else calls cancel on `futureWork` it makes it impossible to wait for that future
    // to finish using the resource, which then makes shutdown code exit too early.
    return Futures.nonCancellationPropagating(futureWork);
}

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

private static <V, R> ListenableFuture<R> transformAsync(ListenableFuture<V> future, Executor asyncExecutor,
        AsyncFunction<V, R> function) {
    boolean inRollupThread = Session.isInRollupThread();
    return Futures.transformAsync(future, new AsyncFunction<V, R>() {
        @Override//  w w w  .j a  va 2 s  . c  o  m
        public ListenableFuture<R> apply(V input) throws Exception {
            boolean priorInRollupThread = Session.isInRollupThread();
            Session.setInRollupThread(inRollupThread);
            try {
                return function.apply(input);
            } finally {
                Session.setInRollupThread(priorInRollupThread);
            }
        }
    },
            // calls to Session.readAsync() inside of the function could block due to the
            // per-thread concurrent limit, so this needs to be executed in its own thread, not
            // in the cassandra driver thread that completes the last future which will block
            // the cassandra driver thread pool
            asyncExecutor);
}