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:com.android.camera.async.Futures2.java

/**
 * Create a new joined future from two existing futures and a joining function
 * that combines the resulting outputs of the previous functions into a single
 * result. The resulting future will fail if any of the dependent futures also
 * fail./* ww  w . j a v  a  2  s  .co m*/
 */
public static <T1, T2, TResult> ListenableFuture<TResult> joinAll(final ListenableFuture<T1> f1,
        final ListenableFuture<T2> f2, final AsyncFunction2<T1, T2, TResult> fn) {
    ListenableFuture<?>[] futures = new ListenableFuture<?>[2];

    futures[0] = f1;
    futures[1] = f2;

    // Futures.allAsList is used instead of Futures.successfulAsList because
    // allAsList will propagate the failures instead of null values to the
    // parameters of the supplied function.
    ListenableFuture<List<Object>> result = Futures.allAsList(futures);
    return Futures.transform(result, new AsyncFunction<List<Object>, TResult>() {
        @Override
        public ListenableFuture<TResult> apply(@Nullable List<Object> list) throws Exception {
            T1 value1 = (T1) list.get(0);
            T2 value2 = (T2) list.get(1);

            return fn.apply(value1, value2);
        }
    });
}

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

@Override
protected ListenableFuture<Report> doLoad(Path.Any source) {
    return Futures.transform(client.get(source), Service.Value::getReport);
}

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

@Override
public Future<RpcResult<Void>> makeBreakfast(MakeBreakfastInput input) {
    ListenableFuture<RpcResult<Void>> makeEggFuture = makeEgg(input);
    ListenableFuture<RpcResult<Void>> makeToastFuture = makeToast(input);
    ListenableFuture<List<RpcResult<Void>>> combinedFutures = Futures
            .allAsList(ImmutableList.of(makeEggFuture, makeToastFuture));
    return Futures.transform(combinedFutures, new AsyncFunction<List<RpcResult<Void>>, RpcResult<Void>>() {
        @Override/*w ww.j  a  v  a2  s  .  c om*/
        public ListenableFuture<RpcResult<Void>> apply(List<RpcResult<Void>> input) throws Exception {
            boolean atLeastOneSucceed = false;
            ImmutableList.Builder<RpcError> errorList = ImmutableList.builder();
            for (RpcResult<Void> result : input) {
                if (result.isSuccessful()) {
                    atLeastOneSucceed = true;
                }
                if (result.getErrors() != null) {
                    errorList.addAll(result.getErrors());
                }
            }
            return Futures.immediateFuture(Rpcs.<Void>getRpcResult(atLeastOneSucceed, errorList.build()));
        }
    });
}

From source file:org.opendaylight.mdsal.binding.dom.adapter.AbstractForwardedTransaction.java

protected final <D extends DataObject> CheckedFuture<Optional<D>, ReadFailedException> doRead(
        final DOMDataTreeReadTransaction readTx, final LogicalDatastoreType store,
        final InstanceIdentifier<D> path) {
    Preconditions.checkArgument(!path.isWildcarded(), "Invalid read of wildcarded path %s", path);

    return MappingCheckedFuture
            .create(Futures.transform(readTx.read(store, codec.toYangInstanceIdentifierBlocking(path)),
                    codec.deserializeFunction(path)), ReadFailedException.MAPPER);
}

From source file:org.thingsboard.rule.engine.metadata.TbGetOriginatorFieldsNode.java

private ListenableFuture<Void> putEntityFields(TbContext ctx, EntityId entityId, TbMsg msg) {
    if (config.getFieldsMapping().isEmpty()) {
        return Futures.immediateFuture(null);
    } else {/* w  ww .j  a v  a2s . co  m*/
        return Futures.transform(EntitiesFieldsAsyncLoader.findAsync(ctx, entityId), data -> {
            config.getFieldsMapping().forEach((field, metaKey) -> {
                String val = data.getFieldValue(field);
                if (val != null) {
                    msg.getMetaData().putValue(metaKey, val);
                }
            });
            return null;
        });
    }
}

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

/**
 * Returns a future of a {@code Set} that contains a single element: the result of the input
 * future.//from w  w  w .j  a va 2s .c  o  m
 */
public static <T> ListenableFuture<Set<T>> createFutureSingletonSet(ListenableFuture<T> future) {
    return Futures.transform(future, new Function<T, Set<T>>() {
        @Override
        public Set<T> apply(T value) {
            return ImmutableSet.of(value);
        }
    });
}

From source file:org.opendaylight.controller.md.sal.binding.impl.AbstractForwardedTransaction.java

protected final <D extends DataObject> CheckedFuture<Optional<D>, ReadFailedException> doRead(
        final DOMDataReadTransaction readTx, final LogicalDatastoreType store,
        final InstanceIdentifier<D> path) {
    Preconditions.checkArgument(!path.isWildcarded(), "Invalid read of wildcarded path %s", path);

    return MappingCheckedFuture
            .create(Futures.transform(readTx.read(store, codec.toYangInstanceIdentifierBlocking(path)),
                    codec.deserializeFunction(path)), ReadFailedException.MAPPER);
}

From source file:io.airlift.discovery.client.testing.SimpleServiceSelector.java

@Override
public ListenableFuture<List<ServiceDescriptor>> refresh() {
    return Futures.transform(lookupClient.getServices(type, pool),
            new Function<ServiceDescriptors, List<ServiceDescriptor>>() {
                @Override//  w  ww  .j  a va2s.  c om
                public List<ServiceDescriptor> apply(ServiceDescriptors serviceDescriptors) {
                    return serviceDescriptors.getServiceDescriptors();
                }
            });
}

From source file:io.v.impl.google.lib.discovery.UpdateImpl.java

@Override
public ListenableFuture<byte[]> getAttachment(VContext ctx, final String name) throws VException {
    synchronized (ad) {
        Attachments attachments = ad.getAttachments();
        if (attachments != null) {
            if (attachments.containsKey(name)) {
                byte[] data = attachments.get(name);
                return Futures.immediateFuture(Arrays.copyOf(data, data.length));
            }//from w  w  w.  ja v a  2s  .  c o m
        }
    }

    ListenableFutureCallback<byte[]> callback = new ListenableFutureCallback<>();
    nativeAttachment(nativeRef, ctx, name, callback);
    return VFutures.withUserLandChecks(ctx,
            Futures.transform(callback.getVanillaFuture(), new Function<byte[], byte[]>() {
                @Override
                public byte[] apply(byte[] data) {
                    synchronized (ad) {
                        Attachments attachments = ad.getAttachments();
                        if (attachments == null) {
                            attachments = new Attachments();
                            ad.setAttachments(attachments);
                        }
                        attachments.put(name, data);
                        return Arrays.copyOf(data, data.length);
                    }
                }
            }));
}

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

@Nonnull
public ListenableFuture<AppendEntriesResponse> appendEntries(@Nonnull AppendEntries request) {
    checkNotNull(request);/*w w  w  .  ja v a2 s  . c om*/
    return Futures.transform(call(RpcCall.appendEntries(ProtoUtils.convert(request))),
            ProtoUtils.convertAppendResponse);
}