List of usage examples for com.google.common.util.concurrent AsyncFunction apply
ListenableFuture<O> apply(@Nullable I input) throws Exception;
From source file:com.tinspx.util.concurrent.FutureUtils.java
/** * Returns the result of calling//from www.jav a 2 s.c o m * {@link AsyncFunction#apply(java.lang.Object) function.apply(input)}. Any * {@code Throwable} thrown from {@code apply} is returned in an failed * {@code ListenableFuture} instead of throwing the {@code Exception}. */ @SuppressWarnings({ "BroadCatchBlock", "TooBroadCatch", "unchecked" }) public static <I, O> ListenableFuture<O> apply(AsyncFunction<? super I, ? extends O> function, I input) { checkNotNull(function); try { return (ListenableFuture<O>) function.apply(input); } catch (Throwable ex) { return Futures.immediateFailedFuture(ex); } }
From source file:co.cask.cdap.common.zookeeper.ZKExtOperations.java
/** * Performs the create part as described in * {@link #updateOrCreate(ZKClient, String, Function, Codec, List)}. If the creation failed with * {@link KeeperException.NodeExistsException}, the * {@link #getAndSet(ZKClient, String, AsyncFunction, Codec, SettableFuture, List)} will be called. *//* ww w .j ava2 s.c o m*/ private static <V> void createOrGetAndSet(final ZKClient zkClient, final String path, final AsyncFunction<V, V> modifier, final Codec<V> codec, final SettableFuture<V> resultFuture, final List<ACL> createAcl) { try { Futures.addCallback(modifier.apply(null), new FutureCallback<V>() { @Override public void onSuccess(final V content) { if (content == null) { resultFuture.set(null); return; } try { byte[] data = codec.encode(content); OperationFuture<String> future; if (createAcl == null) { future = zkClient.create(path, data, CreateMode.PERSISTENT); } else { future = zkClient.create(path, data, CreateMode.PERSISTENT, createAcl); } Futures.addCallback(future, new FutureCallback<String>() { @Override public void onSuccess(String result) { resultFuture.set(content); } @Override public void onFailure(Throwable t) { if (t instanceof KeeperException.NodeExistsException) { // If failed to create due to node exists, try to do getAndSet. getAndSet(zkClient, path, modifier, codec, resultFuture, createAcl); } else { resultFuture.setException(t); } } }, Threads.SAME_THREAD_EXECUTOR); } catch (Throwable t) { resultFuture.setException(t); } } @Override public void onFailure(Throwable t) { resultFuture.setException(t); } }, Threads.SAME_THREAD_EXECUTOR); } catch (Throwable e) { resultFuture.setException(e); } }
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/*from ww w .j a v a 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); }
From source file:com.yahoo.yqlplus.engine.internal.java.sequences.Sequences.java
public static <ROW, SEQUENCE extends Iterable<ROW>, SET> ListenableFuture<List<ROW>> invokeAsyncSet( final Executor executor, final AsyncFunction<List<SET>, SEQUENCE> source, List<SET> keys, Tracer tracer, Timeout timeout, TimeoutHandler handler) throws Exception { // TODO OPTIMIZE: List not needed in this case List<ListenableFuture<SEQUENCE>> results = Lists.newArrayList(); final Tracer childTracer = tracer.start(tracer.getGroup(), tracer.getName()); ListenableFuture<SEQUENCE> result = source.apply(keys); results.add(result);//w ww . j a v a2 s . c om result.addListener(new Runnable() { @Override public void run() { childTracer.end(); } }, MoreExecutors.sameThreadExecutor()); ListenableFuture<List<SEQUENCE>> gather = Futures.allAsList(results); return handler.withTimeout(gatherResults(executor, gather, 1), timeout.verify(), timeout.getTickUnits()); }
From source file:com.yahoo.yqlplus.engine.internal.java.sequences.Sequences.java
public static <ROW, SEQUENCE extends Iterable<ROW>, KEY> ListenableFuture<List<ROW>> invokeAsyncScatter( final Executor executor, final AsyncFunction<KEY, SEQUENCE> source, List<KEY> keys, Tracer tracer, Timeout timeout, TimeoutHandler handler) throws Exception { List<ListenableFuture<SEQUENCE>> results = Lists.newArrayList(); int idx = -1; for (KEY key : keys) { if (key != null) { final Tracer childTracer = tracer.start(tracer.getGroup(), tracer.getName() + "." + (++idx)); ListenableFuture<SEQUENCE> result = source.apply(key); results.add(result);/*from w w w . j a v a2s. c o m*/ result.addListener(new Runnable() { @Override public void run() { childTracer.end(); } }, MoreExecutors.sameThreadExecutor()); } } ListenableFuture<List<SEQUENCE>> gather = Futures.allAsList(results); final int estimatedResultSize = results.size(); return handler.withTimeout(gatherResults(executor, gather, estimatedResultSize), timeout.verify(), timeout.getTickUnits()); }
From source file:com.yahoo.yqlplus.engine.internal.java.sequences.Sequences.java
public static <ROW, SEQUENCE extends Iterable<ROW>, SET> ListenableFuture<List<ROW>> invokeAsyncBatchSet( final Executor executor, final AsyncFunction<List<SET>, SEQUENCE> source, List<SET> keys, Tracer tracer, Timeout timeout, TimeoutHandler handler) throws Exception { List<ListenableFuture<SEQUENCE>> results = Lists.newArrayList(); final Tracer childTracer = tracer.start(tracer.getGroup(), tracer.getName()); List<SET> methodArgs = Lists.newArrayList(); for (int i = 0; i < keys.size(); i++) { if (keys.get(i) != null) { methodArgs.add(keys.get(i)); } else {/*from www. j av a 2s. c o m*/ ListenableFuture<SEQUENCE> result = source.apply(methodArgs); results.add(result); result.addListener(new Runnable() { @Override public void run() { childTracer.end(); } }, MoreExecutors.sameThreadExecutor()); methodArgs = Lists.newArrayList(); } } ListenableFuture<List<SEQUENCE>> gather = Futures.allAsList(results); return handler.withTimeout(gatherResults(executor, gather, 1), timeout.verify(), timeout.getTickUnits()); }
From source file:co.cask.cdap.common.zookeeper.ZKExtOperations.java
/** * Performs the get and condition set part as described in * {@link #updateOrCreate(ZKClient, String, Function, Codec, List)}. *///from w ww.ja v a2 s. c om private static <V> void getAndSet(final ZKClient zkClient, final String path, final AsyncFunction<V, V> modifier, final Codec<V> codec, final SettableFuture<V> resultFuture, final List<ACL> createAcl) { // Try to fetch the node data Futures.addCallback(zkClient.getData(path), new FutureCallback<NodeData>() { @Override public void onSuccess(final NodeData result) { try { // Node has data. Call modifier to get newer version of content final int version = result.getStat().getVersion(); Futures.addCallback(modifier.apply(codec.decode(result.getData())), new FutureCallback<V>() { @Override public void onSuccess(final V content) { // When modifier calls completed, try to set the content // Modifier decided to abort if (content == null) { resultFuture.set(null); return; } try { byte[] data = codec.encode(content); // No change in content. No need to update and simply set the future to complete. if (Arrays.equals(data, result.getData())) { resultFuture.set(content); return; } Futures.addCallback(zkClient.setData(path, data, version), new FutureCallback<Stat>() { @Override public void onSuccess(Stat result) { resultFuture.set(content); } @Override public void onFailure(Throwable t) { if (t instanceof KeeperException.BadVersionException) { // If the version is not good, get and set again getAndSet(zkClient, path, modifier, codec, resultFuture, createAcl); } else if (t instanceof KeeperException.NoNodeException) { // If the node not exists, try to do create createOrGetAndSet(zkClient, path, modifier, codec, resultFuture, createAcl); } else { resultFuture.setException(t); } } }, Threads.SAME_THREAD_EXECUTOR); } catch (Throwable t) { resultFuture.setException(t); } } @Override public void onFailure(Throwable t) { resultFuture.setException(t); } }, Threads.SAME_THREAD_EXECUTOR); } catch (Throwable t) { resultFuture.setException(t); } } @Override public void onFailure(Throwable t) { // If failed to get data because node not exists, try the create. if (t instanceof KeeperException.NoNodeException) { createOrGetAndSet(zkClient, path, modifier, codec, resultFuture, createAcl); } else { resultFuture.setException(t); } } }, Threads.SAME_THREAD_EXECUTOR); }
From source file:com.tinspx.util.net.Requests.java
/** * Returns a {@code Callable} that submits a {@code Request} acquired from * {@code requestCallable} every time {@code call()} is invoked. *///w ww. java2 s .co m public static Callable<ListenableFuture<Response>> apply( final @NonNull AsyncFunction<? super Request, Response> context, final @NonNull Callable<Request> requestCallable) { return new Callable<ListenableFuture<Response>>() { @Override public ListenableFuture<Response> call() throws Exception { return context.apply(requestCallable.call()); } }; }
From source file:com.tinspx.util.net.Requests.java
private static Runnable apply(final @NonNull AsyncFunction<? super Request, Response> context, final @NonNull Request request, final @NonNull SettableFuture<Response> future) { return new Runnable() { @Override/*from w w w. ja va 2s .c om*/ public void run() { try { ListenableFuture<Response> result = context.apply(request); FutureUtils.linkFutures(result, future); FutureUtils.linkFailure(future, result, false); } catch (Throwable t) { future.setException(t); Throwables.propagateIfInstanceOf(t, Error.class); } } }; }
From source file:com.yahoo.yqlplus.engine.internal.java.sequences.Sequences.java
public static <ROW, SEQUENCE extends Iterable<ROW>, SET> ListenableFuture<List<ROW>> invokeAsyncBatchSet( final Executor executor, final AsyncFunction<List<SET>, SEQUENCE> source, final Tracer tracer, final Timeout timeout, final TimeoutHandler handler, final List<ROW>... inputs) throws Exception { final List<ListenableFuture<SEQUENCE>> results = Lists.newArrayList(); final Tracer childTracer = tracer.start(tracer.getGroup(), tracer.getName()); for (List<ROW> input : inputs) { for (int i = 0; i < input.size(); i++) { Record record = (Record) input.get(i); List methodArgs = Lists.newArrayList(); Iterable<String> fieldNames = record.getFieldNames(); for (String fieldName : fieldNames) { methodArgs.add(record.get(fieldName)); }/*from w ww . j a va2 s. c o m*/ ListenableFuture<SEQUENCE> result = source.apply(methodArgs); results.add(result); result.addListener(new Runnable() { @Override public void run() { childTracer.end(); } }, MoreExecutors.sameThreadExecutor()); } } final ListenableFuture<List<SEQUENCE>> gather = Futures.allAsList(results); return handler.withTimeout(gatherResults(executor, gather, 1), timeout.verify(), timeout.getTickUnits()); }