Creates Guava's {@link FutureCallback} from provided Actions
1977
public static <A> FutureCallback<A> futureCallback(final Action<A> success, final Action<Throwable> failure) {
        return new FutureCallback<A>() {
            @Override public void onSuccess(A result) {
                checkNotNull(success).apply(result);
            }

            @Override public void onFailure(Throwable t) {
                checkNotNull(failure).apply(t);
            }
        };
    }
556462
public ListenableFuture<T> createAsync(final TwilioRestClient client) {
        return Twilio.getExecutorService().submit(new Callable<T>() {
            public T call() {
                return create(client);
            }
        });
    }
68122
public static <Result> TaskBuilder<Result> create(Callable<Result> action) {
        return new TaskBuilder<Result>().action(action);
    }
995343
@SuppressWarnings("rawtypes")
    public static FutureResult create(Throwable t) {
        final SMTPException exception;
        if (t instanceof SMTPException) {
            exception = (SMTPException) t;
        } else if (t instanceof ConnectException) {
            exception = new SMTPConnectionException(t);
        } else {
            exception = new SMTPException("Exception while try to deliver msg", t);
        }
        return new FutureResult(exception) {

            @Override
            public Object getResult() {
                return null;
            }
            
        };
        
    }
820907
private static IAction createAction(String action) {
        IAction actn = null;
        
        if (!StringUtils.isEmpty(action)) {
            if ((actn = ActionRegistry.getRegisteredAction(action)) == null) {
                actn = ActionUtil.createAction(null, action);
            }
        }
        
        return actn;
    }
828869
public ServiceFuture<List<DatabaseAccountInner>> listAsync(final ServiceCallback<List<DatabaseAccountInner>> serviceCallback) {
        return ServiceFuture.fromResponse(listWithServiceResponseAsync(), serviceCallback);
    }
795697
public static <T0, T1> FuncN<Void> fromAction(final Action2<? super T0, ? super T1> f) {
        return new FuncN<Void>() {

            @SuppressWarnings("unchecked")
            @Override
            public Void call(Object... args) {
                if (args.length != 2) {
                    throw new RuntimeException("Action3 expecting 2 arguments.");
                }
                f.call((T0) args[0], (T1) args[1]);
                return null;
            }

        };
    }
849065
public <T> Future<T> fireEventAsynchronously(final Event<?> event) {
        final FutureTask<T> futureTask = new FutureTask<T>(() -> {
            synchronizedEventQueue.fireEvent(event);

            return null; // XXX: Our future????
        });

        Latkes.EXECUTOR_SERVICE.execute(futureTask);

        return futureTask;
    }
1162270
static <T> ContinuableFuture<T> executeOnUiThread(final Callable<T> action, final long delay) {
        return execute(new FutureTask<>(action), _UI_EXECUTOR, delay);
    }
982344
@SuppressWarnings("unchecked")
		public <T,I> Collection<T> startWorking(Collection<Callable<I>> callables) 
		 {
			    List<Future<I>> list = new ArrayList<Future<I>>();
			    
			    for (Callable<I> callable : callables)
			    {
			    	list.add(executor.submit(callable));
			    }
			    
			   
			    ArrayList<T> resultList = new ArrayList<T>(callables.size());
			    
			    // Now retrieve the result
			    I output;
			    for (Future<I> future : list) 
			    {
			      try 
			      {  
			    	  output = future.get();
			    	  
			    	  if(output != null)
			    		  resultList.add((T)output);
			      } 
			      catch (InterruptedException e) 
			      {
			        throw new SystemException(e);
			      } 
			      catch (ExecutionException e) 
			      {
			    	  Throwable cause =  e.getCause();
			    	  if(cause == null)
			    		  cause = e;
			    	  if(cause instanceof RuntimeException)
			    		  throw (RuntimeException)cause;
			    		  
			    	  throw new SystemException(cause);
			      }
			    }
			    
			  return resultList;
		 }
238954
public static CompletableFuture<Void> from(ChannelFuture future) {

        LettuceAssert.notNull(future, "ChannelFuture must not be null");

        CompletableFuture<Void> result = new CompletableFuture<>();
        adapt(future, result);

        return result;
    }
1364554
public ServiceFuture<OperationListResultInner> listAsync(final ServiceCallback<OperationListResultInner> serviceCallback) {
        return ServiceFuture.fromResponse(listWithServiceResponseAsync(), serviceCallback);
    }
113890
public TaskBuilder<Result> action(final Callable<Result> action) {
        if (action instanceof TaskCallable) {
            this.action = (TaskCallable<Result>) action;
        } else {
            this.action = new WrappedCallable<Result>(action);
        }
        return this;
    }
1106089
public static <T> ActionPredicate<T> fromAction
	(final Action<T> action,
	 final boolean predicateResult) {
	
	return new ActionPredicate<T>() {
	    public boolean actionPredicate(T obj) {
		action.action(obj);
		return predicateResult;
	    }
	};
    }
711910
@Beta
  public Future<HttpResponse> executeAsync(Executor executor) {
    FutureTask<HttpResponse> future =
        new FutureTask<HttpResponse>(
            new Callable<HttpResponse>() {

              public HttpResponse call() throws Exception {
                return execute();
              }
            });
    executor.execute(future);
    return future;
  }
878014
private ReceiveMessageFuture issueFuture(int size,
                                             QueueBufferCallback<ReceiveMessageRequest, ReceiveMessageResult> callback) {
        synchronized (futures) {
            ReceiveMessageFuture theFuture = new ReceiveMessageFuture(callback, size);
            futures.addLast(theFuture);
            return theFuture;
        }
    }
708706
@Override
    public <R, T extends Object> Future<R> callMethodAsync(final String methodName, final T argument) {

        try {
            validateMiddleware();
        } catch (InvalidStateException ex) {
            return FutureProcessor.canceledFuture(ex);
        }

        return GlobalCachedExecutorService.submit(new Callable<R>() {

            private Future<R> internalCallFuture;

            @Override
            public R call() throws Exception {

                final String shortArgument = RPCHelper.argumentToString(argument);

                try {
                    try {
                        logger.debug("Calling method async [" + methodName + "(" + shortArgument + ")] on scope: " + remoteServer.getScope().toString());

                        if (!isConnected()) {
                            try {
                                waitForConnectionState(CONNECTED, CONNECTION_TIMEOUT);
                            } catch (TimeoutException ex) {
                                throw new CouldNotPerformException("Cannot not call async method[" + methodName + "(" + shortArgument + ")] on [" + this + "] in connectionState[" + connectionState + "]", ex);

                            }
                        }
                        final long currentTime = System.nanoTime();
                        remoteServerWatchDog.waitForServiceActivation();
                        internalCallFuture = remoteServer.callAsync(methodName, argument);
                        while (true) {

                            if (TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - currentTime) > RPCHelper.RPC_TIMEOUT) {
                                throw new TimeoutException("RPCMethod call timeout");
                            }

                            try {
                                return internalCallFuture.get(REQUEST_TIMEOUT, TimeUnit.MILLISECONDS);
                            } catch (java.util.concurrent.TimeoutException ex) {


                                // validate connection
                                try {
                                    // if reconnecting do not start a ping but just wait for connecting again
                                    if (getConnectionState() != RECONNECTING) {
                                        ping().get(REQUEST_TIMEOUT, TimeUnit.MILLISECONDS);
                                    } else {
                                        waitForConnectionState(CONNECTING);
                                    }
                                } catch (ExecutionException | java.util.concurrent.TimeoutException | CancellationException exx) {
                                    // cancel call if connection is broken
                                    if (internalCallFuture != null) {
                                        internalCallFuture.cancel(true);
                                    }
                                }
                            } catch (ExecutionException ex) {
                                if (ex.getCause() instanceof RSBException) {
                                    throw new RSBResolvedException("Remote call failed!", (RSBException) ex.getCause());
                                }
                                throw ex;
                            } catch (InterruptedException ex) {
                                Thread.currentThread().interrupt();
                            }

                            // check if thread was interrupted during processing
                            if (Thread.currentThread().isInterrupted()) {
                                throw new InterruptedException();
                            }
                        }


                    } catch (final InterruptedException ex) {
                        if (internalCallFuture != null) {
                            internalCallFuture.cancel(true);
                        }
                        throw ex;
                    } catch (final InvalidStateException ex) {
                        // reinit remote service because middleware connection lost!
                        switch (connectionState) {
                            // only if the connection was established before and no reconnect is ongoing.
                            case CONNECTING:
                            case CONNECTED:
                                try {
                                    reinit();
                                } catch (final CouldNotPerformException exx) {
                                    ExceptionPrinter.printHistory("Recovering middleware connection failed!", exx, logger);
                                }
                        }
                        throw ex;
                    }
                } catch (final CouldNotPerformException | CancellationException | InterruptedException ex) {
                    throw new CouldNotPerformException("Could not call remote Method[" + methodName + "(" + shortArgument + ")] on Scope[" + remoteServer.getScope() + "].", ex);
                }
            }
        });
    }