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

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

Introduction

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

Prototype

public static <I, O> ListenableFuture<O> transform(ListenableFuture<I> input,
        Function<? super I, ? extends O> function) 

Source Link

Document

Returns a new ListenableFuture whose result is the product of applying the given Function to the result of the given Future .

Usage

From source file:org.opendaylight.mdsal.mount.cache.impl.tx.CachedDOMReadOnlyTransaction.java

@Override
public CheckedFuture<Boolean, ReadFailedException> exists(LogicalDatastoreType store,
        YangInstanceIdentifier path) {//www  .  j a va  2s.c o m
    LOG.debug("{}: Exists store={} path={}", nodeId, store, path);

    final CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> read = read(store, path);

    final ListenableFuture<Boolean> transform = Futures.transform(read,
            new Function<Optional<NormalizedNode<?, ?>>, Boolean>() {
                @Nullable
                @Override
                public Boolean apply(final Optional<NormalizedNode<?, ?>> input) {
                    return input.isPresent();
                }
            });

    return Futures.makeChecked(transform, new Function<Exception, ReadFailedException>() {
        @Nullable
        @Override
        public ReadFailedException apply(final Exception e) {
            return new ReadFailedException("%s: Unable to read from cache" + nodeId, e);
        }
    });
}

From source file:com.microsoft.services.orc.core.OrcMediaEntityFetcher.java

public ListenableFuture<InputStream> getStreamedContent() {

    Request request = getResolver().createRequest();
    request.setVerb(HttpVerb.GET);/*from  w w  w .jav a  2s.  c o  m*/
    request.addOption(Request.MUST_STREAM_RESPONSE_CONTENT, "true");
    OrcURL url = request.getUrl();
    url.appendPathComponent("$value");

    ListenableFuture<OrcResponse> future = oDataExecute(request);

    return Futures.transform(future, new AsyncFunction<OrcResponse, InputStream>() {
        @Override
        public ListenableFuture<InputStream> apply(OrcResponse response) throws Exception {
            SettableFuture<InputStream> result = SettableFuture.create();
            result.set(new MediaEntityInputStream(response.openStreamedResponse(), response));
            return result;
        }
    });
}

From source file:dagger2.producers.internal.SetProducer.java

/**
 * Returns a future {@link Set} whose iteration order is that of the elements given by each of the
 * producers, which are invoked in the order given at creation.
 *
 * <p>If any of the delegate sets, or any elements therein, are null, then this future will fail
 * with a NullPointerException./*from   ww  w. ja v a 2s.  co m*/
 *
 * <p>Canceling this future will attempt to cancel all of the component futures, and if any of the
 * delegate futures fails or is canceled, this one is, too.
 *
 * @throws NullPointerException if any of the delegate producers return null
 */
@Override
public ListenableFuture<Set<T>> compute() {
    List<ListenableFuture<Set<T>>> futureSets = new ArrayList<ListenableFuture<Set<T>>>(
            contributingProducers.size());
    for (Producer<Set<T>> producer : contributingProducers) {
        ListenableFuture<Set<T>> futureSet = producer.get();
        if (futureSet == null) {
            throw new NullPointerException(producer + " returned null");
        }
        futureSets.add(futureSet);
    }
    return Futures.transform(Futures.allAsList(futureSets), new Function<List<Set<T>>, Set<T>>() {
        @Override
        public Set<T> apply(List<Set<T>> sets) {
            ImmutableSet.Builder<T> builder = ImmutableSet.builder();
            for (Set<T> set : sets) {
                builder.addAll(set);
            }
            return builder.build();
        }
    });
}

From source file:org.thingsboard.server.dao.AbstractModelDao.java

protected ListenableFuture<List<T>> findListByStatementAsync(Statement statement) {
    if (statement != null) {
        statement.setConsistencyLevel(cluster.getDefaultReadConsistencyLevel());
        ResultSetFuture resultSetFuture = getSession().executeAsync(statement);
        ListenableFuture<List<T>> result = Futures.transform(resultSetFuture,
                new Function<ResultSet, List<T>>() {
                    @Nullable/*from   w  w  w.j a  v a  2 s .c o  m*/
                    @Override
                    public List<T> apply(@Nullable ResultSet resultSet) {
                        Result<T> result = getMapper().map(resultSet);
                        if (result != null) {
                            return result.all();
                        } else {
                            return Collections.emptyList();
                        }
                    }
                });
        return result;
    }
    return Futures.immediateFuture(Collections.emptyList());
}

From source file:com.facebook.buck.artifact_cache.MultiArtifactCache.java

private static ListenableFuture<Void> storeToCaches(ImmutableList<ArtifactCache> caches, ArtifactInfo info,
        BorrowablePath output) {// www .j av  a2 s. c  o m
    // TODO(cjhopman): support BorrowablePath with multiple writable caches.
    if (caches.size() != 1) {
        output = BorrowablePath.notBorrowablePath(output.getPath());
    }
    List<ListenableFuture<Void>> storeFutures = Lists.newArrayListWithExpectedSize(caches.size());
    for (ArtifactCache artifactCache : caches) {
        storeFutures.add(artifactCache.store(info, output));
    }

    // Aggregate future to ensure all store operations have completed.
    return Futures.transform(Futures.allAsList(storeFutures), Functions.<Void>constant(null));
}

From source file:org.opendaylight.bgpcep.pcep.topology.provider.TopologyRPCs.java

@Override
public Future<RpcResult<AddLspOutput>> addLsp(final AddLspInput input) {
    return Futures.transform(manager.addLsp(input), new Function<OperationResult, RpcResult<AddLspOutput>>() {
        @Override// www  .j  a va  2  s  .  co  m
        public RpcResult<AddLspOutput> apply(final OperationResult input) {
            return SuccessfulRpcResult.create(new AddLspOutputBuilder(input).build());
        }
    });
}

From source file:com.datastax.driver.core.AbstractSession.java

/**
 * {@inheritDoc}//from  ww w  .  j  a v a  2 s  . c  o m
 */
@Override
public ListenableFuture<PreparedStatement> prepareAsync(final RegularStatement statement) {
    if (statement.hasValues())
        throw new IllegalArgumentException("A statement to prepare should not have values");

    ListenableFuture<PreparedStatement> prepared = prepareAsync(statement.toString());
    return Futures.transform(prepared, new Function<PreparedStatement, PreparedStatement>() {
        @Override
        public PreparedStatement apply(PreparedStatement prepared) {
            ByteBuffer routingKey = statement.getRoutingKey();
            if (routingKey != null)
                prepared.setRoutingKey(routingKey);
            prepared.setConsistencyLevel(statement.getConsistencyLevel());
            if (statement.isTracing())
                prepared.enableTracing();
            prepared.setRetryPolicy(statement.getRetryPolicy());

            return prepared;
        }
    });
}

From source file:demos.AsynchronousRead.java

@Override
public void run() {
    try {//  www  .  jav  a  2 s . c  o  m
        logger.info("Preparing to read data points");

        Cluster cluster = Cluster.builder().addContactPoint("127.0.0.1").build();
        Session session = cluster.connect("demo");
        PreparedStatement query = session.prepare(
                "SELECT metric_id, time, value FROM metric_data WHERE metric_id = ? AND time >= ? AND time <= ?");
        DateTime end = DateTime.now();
        DateTime start = end.minusYears(1);
        final CountDownLatch latch = new CountDownLatch(NUM_METRICS);
        final Set<DataPoint> dataPoints = new ConcurrentSkipListSet<>(
                comparing(DataPoint::getTimestamp).thenComparing(DataPoint::getValue));

        Stopwatch stopwatch = new Stopwatch().start();
        for (int i = 0; i < NUM_METRICS; ++i) {
            ResultSetFuture queryFuture = session
                    .executeAsync(query.bind("metric-" + i, start.toDate(), end.toDate()));
            ListenableFuture<List<DataPoint>> dataFuture = Futures.transform(queryFuture,
                    (ResultSet resultSet) -> StreamSupport.stream(resultSet.spliterator(), false)
                            .map(row -> new DataPoint(row.getString(0), row.getDate(1), row.getDouble(2)))
                            .collect(toList()));
            Futures.addCallback(dataFuture, new FutureCallback<List<DataPoint>>() {
                @Override
                public void onSuccess(List<DataPoint> results) {
                    dataPoints.addAll(results);
                    latch.countDown();
                }

                @Override
                public void onFailure(Throwable t) {
                    logger.warn("There was an error reading data", t);
                    latch.countDown();
                }
            });
        }
        latch.await();
        stopwatch.stop();

        logger.info("Retrieved {} data points in {} ms", dataPoints.size(),
                stopwatch.elapsed(TimeUnit.MILLISECONDS));
    } catch (InterruptedException e) {
        logger.info("There was an interrupt while waiting for inserts to complete");
    }
}

From source file:net.oneandone.troilus.DeleteQuery.java

@Override
public ListenableFuture<Result> executeAsync() {
    ListenableFuture<Result> future = super.executeAsync();

    Function<Result, Result> validateOnlyIfFunction = new Function<Result, Result>() {
        @Override/*w w  w .j ava  2 s . co  m*/
        public Result apply(Result result) {
            if (!data.getOnlyIfConditions().isEmpty() && !result.wasApplied()) {
                throw new IfConditionException(result, "if condition does not match");
            }
            return result;
        }
    };
    return Futures.transform(future, validateOnlyIfFunction);
}

From source file:com.google.gapid.models.ApiState.java

@Override
protected ListenableFuture<Node> doLoad(Path.Any path) {
    return Futures.transformAsync(client.get(path),
            tree -> Futures.transform(client.get(Paths.any(tree.getStateTree().getRoot())),
                    val -> new RootNode(tree.getStateTree().getRoot().getTree(), val.getStateTreeNode())));
}