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

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

Introduction

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

Prototype

@GwtIncompatible("TODO")
@CheckReturnValue
public static <I, O> Future<O> lazyTransform(final Future<I> input,
        final Function<? super I, ? extends O> function) 

Source Link

Document

Like #transform(ListenableFuture,Function) except that the transformation function is invoked on each call to Future#get() get() on the returned future.

Usage

From source file:io.fabric8.etcd.core.AsynchronousExecution.java

@Override
public Future<Response> execute(final OperationContext context, Operation operation) {
    Future<HttpResponse> httpResponseFuture = context.getHttpClient().execute(operation.createRequest(context),
            FUTURE_CALLBACK);/*from w w  w.j  av a 2s  .  c  o m*/
    return Futures.lazyTransform(httpResponseFuture, context.getConverter());
}

From source file:org.onosproject.store.hz.SMap.java

@Override
public Future<V> getAsync(K key) {
    Future<byte[]> f = m.getAsync(serializeKey(key));
    return Futures.lazyTransform(f, new DeserializeVal());
}

From source file:org.onosproject.store.hz.SMap.java

@Override
public Future<V> putAsync(K key, V value) {
    Future<byte[]> f = m.putAsync(serializeKey(key), serializeVal(value));
    return Futures.lazyTransform(f, new DeserializeVal());
}

From source file:org.onosproject.store.hz.SMap.java

@Override
public Future<V> putAsync(K key, V value, long ttl, TimeUnit timeunit) {
    Future<byte[]> f = m.putAsync(serializeKey(key), serializeVal(value), ttl, timeunit);
    return Futures.lazyTransform(f, new DeserializeVal());
}

From source file:org.onosproject.store.hz.SMap.java

@Override
public Future<V> removeAsync(K key) {
    Future<byte[]> f = m.removeAsync(serializeKey(key));
    return Futures.lazyTransform(f, new DeserializeVal());
}

From source file:com.google.cloud.pubsub.PubSubImpl.java

private static <I, O> Future<O> transform(Future<I> future, Function<? super I, ? extends O> function) {
    if (future instanceof ListenableFuture) {
        return Futures.transform((ListenableFuture<I>) future, function);
    }//from w w w .ja v a2 s.co m
    return Futures.lazyTransform(future, function);
}

From source file:com.google.cloud.dataflow.sdk.runners.worker.WindmillStateReader.java

/**
 * Return future which transforms a {@code ValuesAndContToken<T>} result into the
 * initial Iterable<T> result expected from the external caller.
 *///from ww w.j  a  v  a2s. co  m
private <T> Future<Iterable<T>> valuesToPagingIterableFuture(final StateTag stateTag, final Coder<T> elemCoder,
        final Future<ValuesAndContToken<T>> future) {
    return Futures.lazyTransform(future, new Function<ValuesAndContToken<T>, Iterable<T>>() {
        @Override
        public Iterable<T> apply(ValuesAndContToken<T> valuesAndContToken) {
            if (valuesAndContToken.continuationToken == null) {
                // Number of values is small enough Windmill sent us the entire list in one response.
                return valuesAndContToken.values;
            } else {
                // Return an iterable which knows how to come back for more.
                StateTag contStateTag = new StateTag(stateTag.kind, stateTag.tag, stateTag.stateFamily,
                        valuesAndContToken.continuationToken);
                return new TagListPagingIterable<>(valuesAndContToken.values, contStateTag, elemCoder);
            }
        }
    });
}

From source file:org.opendaylight.tsdr.datastorage.TSDRStorageServiceImpl.java

@Override
public Future<RpcResult<GetTSDRAggregatedMetricsOutput>> getTSDRAggregatedMetrics(
        final GetTSDRAggregatedMetricsInput input) {

    if (this.metricPersistenceService == null) {
        RpcResultBuilder<GetTSDRAggregatedMetricsOutput> builder = RpcResultBuilder.failed();
        return builder.buildFuture();
    }//  w  w  w.j av  a2 s.c om

    // Locate the appropriate aggregation function implementation
    final AggregationFunction aggregationFunction = Iterators.find(aggregationFunctions.iterator(),
            new Predicate<AggregationFunction>() {
                @Override
                public boolean apply(AggregationFunction candidate) {
                    return candidate.getType().equals(input.getAggregation());
                }
            }, null);
    if (aggregationFunction == null) {
        return RpcResultBuilder.<GetTSDRAggregatedMetricsOutput>failed()
                .withError(ErrorType.APPLICATION, String.format(
                        "No aggregation function implementation was found for '%s'.", input.getAggregation()))
                .buildFuture();
    }

    // Gather the metrics for the given time span
    final GetTSDRMetricsInput metricsInput = new GetTSDRMetricsInputBuilder()
            .setTSDRDataCategory(input.getTSDRDataCategory()).setStartTime(input.getStartTime())
            .setEndTime(input.getEndTime()).build();
    final Future<RpcResult<GetTSDRMetricsOutput>> result = getTSDRMetrics(metricsInput);

    //Fix for bug 5655 - Do not aggregate when # of points is less than requested
    long numberOfPoints = (input.getEndTime() - input.getStartTime()) / input.getInterval();
    try {
        //In case of a MEAN aggregation and the number of requested points is larger than what is, just return the original
        //result.
        if (input.getAggregation() == AggregationType.MEAN
                && result.get().getResult().getMetrics().size() <= numberOfPoints) {
            final List<AggregatedMetrics> aggregatedMetrics = Lists.newLinkedList();
            for (Metrics m : result.get().getResult().getMetrics()) {
                // Aggregate the metrics in the interval
                aggregatedMetrics.add(new AggregatedMetricsBuilder().setTimeStamp(m.getTimeStamp())
                        .setMetricValue(m.getMetricValue()).build());
            }
            // We're done
            final GetTSDRAggregatedMetricsOutputBuilder outputBuilder = new GetTSDRAggregatedMetricsOutputBuilder()
                    .setAggregatedMetrics(aggregatedMetrics);
            return RpcResultBuilder.success(outputBuilder).buildFuture();

        }
    } catch (InterruptedException | ExecutionException e) {
        RpcResultBuilder builder = RpcResultBuilder.failed();
        builder.withError(ErrorType.APPLICATION, "Failed to extract data for aggregation");
        return builder.buildFuture();
    }

    // Aggregate the results
    return Futures.lazyTransform(result,
            new Function<RpcResult<GetTSDRMetricsOutput>, RpcResult<GetTSDRAggregatedMetricsOutput>>() {
                @Override
                public RpcResult<GetTSDRAggregatedMetricsOutput> apply(
                        RpcResult<GetTSDRMetricsOutput> metricsOutput) {
                    final List<AggregatedMetrics> aggregatedMetrics = Lists.newLinkedList();
                    final PeekingIterator<Metrics> metricIterator = Iterators
                            .peekingIterator(metricsOutput.getResult().getMetrics().iterator());
                    // Generate and iterate over all the intervals in the given range
                    for (Long intervalStartInclusive : new IntervalGenerator(input.getStartTime(),
                            input.getEndTime(), input.getInterval())) {
                        final Long intervalEndExclusive = intervalStartInclusive + input.getInterval();

                        // Gather the list of metrics that fall within the current interval
                        // We make the assumption that the list of metrics is already sorted by time-stamp
                        final List<Metrics> metricsInInterval = Lists.newLinkedList();
                        while (metricIterator.hasNext()) {
                            if (metricIterator.peek().getTimeStamp() >= intervalEndExclusive) {
                                break;
                            }
                            metricsInInterval.add(metricIterator.next());
                        }

                        // Aggregate the metrics in the interval
                        aggregatedMetrics.add(new AggregatedMetricsBuilder()
                                .setTimeStamp(intervalStartInclusive)
                                .setMetricValue(aggregationFunction.aggregate(metricsInInterval)).build());
                    }

                    // We're done
                    final GetTSDRAggregatedMetricsOutput output = new GetTSDRAggregatedMetricsOutputBuilder()
                            .setAggregatedMetrics(aggregatedMetrics).build();
                    return RpcResultBuilder.success(output).build();
                }
            });
}

From source file:org.apache.beam.runners.dataflow.worker.WindmillStateReader.java

/**
 * Return future which transforms a {@code ValuesAndContPosition<T>} result into the initial
 * Iterable<T> result expected from the external caller.
 *//*from  ww  w. j ava  2s  . c  o  m*/
private <T> Future<Iterable<T>> valuesToPagingIterableFuture(final StateTag stateTag, final Coder<T> elemCoder,
        final Future<ValuesAndContPosition<T>> future) {
    return Futures.lazyTransform(future, new ToIterableFunction<T>(this, stateTag, elemCoder));
}