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:com.spotify.folsom.LoadTestRunner.java

public static void main(final String[] args) throws Throwable {
    final BinaryMemcacheClient<String> client = new MemcacheClientBuilder<>(StringTranscoder.UTF8_INSTANCE)
            .withAddress("127.0.0.1").withMaxOutstandingRequests(100000).connectBinary();

    final String[] keys = new String[10];
    for (int i = 0; i < 10; i++) {
        keys[i] = "key" + i;
    }/* w  w w  .ja v  a2 s.  c  o m*/

    final List<ListenableFuture<Boolean>> futures = Lists.newArrayList();
    for (int r = 0; r < 100; r++) {
        for (final String keyProto : keys) {
            final String key = keyProto + ":" + r;

            final ListenableFuture<MemcacheStatus> setFuture = client.set(key, "value" + key, 100000);
            final ListenableFuture<String> getFuture = Utils.transform(setFuture,
                    new AsyncFunction<MemcacheStatus, String>() {
                        @Override
                        public ListenableFuture<String> apply(final MemcacheStatus input) throws Exception {
                            return client.get(key);
                        }
                    });
            final ListenableFuture<String> deleteFuture = Utils.transform(getFuture,
                    new AsyncFunction<String, String>() {
                        @Override
                        public ListenableFuture<String> apply(final String value) throws Exception {
                            return Utils.transform(client.delete(key), new Function<MemcacheStatus, String>() {
                                @Override
                                public String apply(final MemcacheStatus input) {
                                    return value;
                                }
                            });
                        }
                    });

            final ListenableFuture<Boolean> assertFuture = Utils.transform(deleteFuture,
                    new Function<String, Boolean>() {
                        @Override
                        public Boolean apply(final String input) {
                            return ("value" + key).equals(input);
                        }
                    });

            futures.add(assertFuture);
        }
    }

    final List<Boolean> asserts = Futures.allAsList(futures).get();

    int failed = 0;
    for (final boolean b : asserts) {
        if (!b) {
            failed++;
        }
    }
    System.out.println(failed + " failed of " + asserts.size());

    client.shutdown();
}

From source file:com.spotify.trickle.Fallbacks.java

public static <T> AsyncFunction<Throwable, T> always(@Nullable final T value) {
    return new AsyncFunction<Throwable, T>() {
        @Nullable/*from w w w . ja  v a2s.c om*/
        @Override
        public ListenableFuture<T> apply(@Nullable Throwable input) {
            return immediateFuture(value);
        }
    };
}

From source file:org.opendaylight.controller.md.sal.common.impl.service.AbstractDataTransaction.java

public static ListenableFuture<RpcResult<TransactionStatus>> convertToLegacyCommitFuture(
        final CheckedFuture<Void, TransactionCommitFailedException> from) {
    return Futures.transform(from, new AsyncFunction<Void, RpcResult<TransactionStatus>>() {
        @Override// w  ww.jav a2s  .co m
        public ListenableFuture<RpcResult<TransactionStatus>> apply(final Void input) {
            return SUCCESS_FUTURE;
        }
    });
}

From source file:io.v.impl.google.rpc.ServerRPCHelper.java

static ListenableFuture<byte[][]> prepare(Invoker invoker, VContext ctx, String method) {
    return Futures.transform(invoker.getMethodTags(ctx, method), new AsyncFunction<VdlValue[], byte[][]>() {
        @Override//from   www  .j a  v a  2s .  c om
        public ListenableFuture<byte[][]> apply(VdlValue[] tags) throws Exception {
            byte[][] vomTags = new byte[tags.length][];
            for (int i = 0; i < tags.length; ++i) {
                vomTags[i] = VomUtil.encode(tags[i], tags[i].vdlType());
            }
            return Futures.immediateFuture(vomTags);
        }
    });
}

From source file:io.v.android.apps.namespace_browser.Methods.java

static ListenableFuture<List<String>> get(VContext ctx, String name) {
    Client client = V.getClient(ctx);/*from   w  w  w  .ja  v a  2  s . c  o  m*/
    VContext ctxT = ctx.withTimeout(new Duration(20000)); // 20s
    ListenableFuture<ClientCall> callFuture = client.startCall(ctxT, name, "__Signature", new Object[0],
            new Type[0]);
    final Type[] resultTypes = new Type[] { new TypeToken<Interface[]>() {
    }.getType() };
    ListenableFuture<Interface[]> sign = Futures.transform(callFuture,
            new AsyncFunction<ClientCall, Interface[]>() {
                @Override
                public ListenableFuture<Interface[]> apply(ClientCall call) throws Exception {
                    return Futures.transform(call.finish(resultTypes), new Function<Object[], Interface[]>() {
                        @Override
                        public Interface[] apply(Object[] input) {
                            return (Interface[]) (input[0]);
                        }
                    });
                }
            });
    return Futures.transform(sign, new Function<Interface[], List<String>>() {
        @Override
        public List<String> apply(Interface[] input) {
            List<String> ret = new ArrayList<String>();
            for (Interface iface : input) {
                if (iface.getMethods() != null) {
                    for (Method method : iface.getMethods()) {
                        ret.add(method.getName());
                    }
                }
            }
            return ret;
        }
    });
}

From source file:co.cask.cdap.common.async.AsyncFunctions.java

/**
 * Converts a {@link Function} into {@link AsyncFunction} by performing the operation in the given executor.
 *
 * @param function Function to apply/* ww w  .j  a v a  2  s .co m*/
 * @param executor Executor for the function to execute in
 * @param <I> Input type
 * @param <O> Output type
 * @return A {@link AsyncFunction} that will call the function in the given executor.
 */
public static <I, O> AsyncFunction<I, O> asyncWrap(final Function<I, O> function, final Executor executor) {
    return new AsyncFunction<I, O>() {
        @Override
        public ListenableFuture<O> apply(final I input) throws Exception {
            final SettableFuture<O> resultFuture = SettableFuture.create();
            executor.execute(new Runnable() {

                @Override
                public void run() {
                    try {
                        resultFuture.set(function.apply(input));
                    } catch (Throwable t) {
                        resultFuture.setException(t);
                    }
                }
            });
            return resultFuture;
        }
    };
}

From source file:de.dfki.kiara.impl.AsyncCall.java

public static ListenableFuture<Message> performRemoteAsyncCall(final MessageConnection messageConnection,
        final Message request, ListeningExecutorService executor) {
    final ListenableFuture<Message> result = messageConnection.receive(request.getMessageId());
    final ListenableFuture<Void> reqSent = messageConnection.send(request);

    AsyncFunction<Void, Message> f = new AsyncFunction<Void, Message>() {

        @Override/*from   w w  w.j  a v a 2  s.c o m*/
        public ListenableFuture<Message> apply(Void input) throws Exception {
            return result;
        }
    };
    return Futures.transform(reqSent, f);
}

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

private static AsyncFunction<Boolean, Void> getRetryFn(final VContext ctx, final Database db,
        final BatchOptions opts, final BatchOperation op, final int round) {
    return new AsyncFunction<Boolean, Void>() {
        @Override/* www .j  av a2s.com*/
        public ListenableFuture<Void> apply(Boolean success) throws Exception {
            if (success) {
                return Futures.immediateFuture(null);
            }
            if (round >= 3) {
                throw new ConcurrentBatchException(ctx);
            }
            return Futures.transform(tryBatch(ctx, db, opts, op), getRetryFn(ctx, db, opts, op, round + 1));
        }
    };
}

From source file:com.continuuity.weave.internal.ZKMessages.java

/**
 * Creates a message node in zookeeper. The message node created is a PERSISTENT_SEQUENTIAL node.
 *
 * @param zkClient The ZooKeeper client for interacting with ZooKeeper.
 * @param messagePathPrefix ZooKeeper path prefix for the message node.
 * @param message The {@link Message} object for the content of the message node.
 * @param completionResult Object to set to the result future when the message is processed.
 * @param <V> Type of the completion result.
 * @return A {@link ListenableFuture} that will be completed when the message is consumed, which indicated
 *         by deletion of the node. If there is exception during the process, it will be reflected
 *         to the future returned./*from   www.  j  a  va  2s  .co  m*/
 */
public static <V> ListenableFuture<V> sendMessage(final ZKClient zkClient, String messagePathPrefix,
        final Message message, final V completionResult) {
    return Futures.transform(
            zkClient.create(messagePathPrefix, MessageCodec.encode(message), CreateMode.PERSISTENT_SEQUENTIAL),
            new AsyncFunction<String, V>() {
                @Override
                public ListenableFuture<V> apply(String path) throws Exception {
                    return Futures.transform(ZKOperations.watchDeleted(zkClient, path),
                            new Function<String, V>() {
                                @Override
                                public V apply(String path) {
                                    return completionResult;
                                }
                            });
                }
            });
}

From source file:io.v.impl.google.rpc.ServerRPCHelper.java

static ListenableFuture<byte[][]> invoke(final Invoker invoker, final VContext ctx, final StreamServerCall call,
        final String method, final byte[][] vomArgs) {
    return Futures.transform(invoker.getArgumentTypes(ctx, method), new AsyncFunction<Type[], byte[][]>() {
        @Override//from  ww  w. jav a 2  s . co m
        public ListenableFuture<byte[][]> apply(Type[] argTypes) throws Exception {
            if (argTypes.length != vomArgs.length) {
                throw new VException(String.format("Wrong number of args, want %d, got %d", argTypes.length,
                        vomArgs.length));
            }
            final Object[] args = new Object[argTypes.length];
            for (int i = 0; i < argTypes.length; ++i) {
                args[i] = VomUtil.decode(vomArgs[i], argTypes[i]);
            }
            return Futures.transform(
                    Futures.<Object>allAsList(invoker.getResultTypes(ctx, method),
                            invoker.invoke(ctx, call, method, args)),
                    new AsyncFunction<List<Object>, byte[][]>() {
                        @Override
                        public ListenableFuture<byte[][]> apply(List<Object> input) throws Exception {
                            Type[] resultTypes = (Type[]) input.get(0);
                            Object[] results = (Object[]) input.get(1);
                            if (resultTypes.length != results.length) {
                                throw new VException(String.format("Wrong number of results, want %d, got %d",
                                        resultTypes.length, results.length));
                            }
                            byte[][] vomResults = new byte[resultTypes.length][];
                            for (int i = 0; i < resultTypes.length; ++i) {
                                vomResults[i] = VomUtil.encode(results[i], resultTypes[i]);
                            }
                            return Futures.immediateFuture(vomResults);
                        }
                    });
        }
    });
}