package org.sagebionetworks.web.client.utils;

import java.util.function.Consumer;

import com.google.common.util.concurrent.FluentFuture;
import com.google.common.util.concurrent.SettableFuture;
import com.google.gwt.user.client.rpc.AsyncCallback;

public class FutureUtils {
	/**
	 * Calls the given closure, passing it an AsyncCallback that transmits the success
	 * failure scenarios to a FluentFuture; then it returns the future.
	 *
	 * @param closure
	 * @param <T>
	 * @return a FluentFuture that represents the outcome of calling the closure
	 */
	public static <T> FluentFuture<T> getFuture(Consumer<AsyncCallback<T>> closure) {
		SettableFuture<T> future = SettableFuture.create();
		closure.accept(new AsyncCallback<T>() {
			@Override
			public void onFailure(Throwable caught) {
				future.setException(caught);
			}

			@Override
			public void onSuccess(T result) {
				future.set(result);
			}
		});
		return FluentFuture.from(future);
	}

	/**
	 * Returns a future that is already completed with the given value as the result.
	 *
	 * @param result
	 * @param <T>
	 * @return a future that is already completed with the given value as the result
	 */
	public static <T> FluentFuture<T> getDoneFuture(T result) {
		SettableFuture<T> future = SettableFuture.create();
		future.set(result);
		return FluentFuture.from(future);
	}

	/**
	 * Returns a failed future with its exception set to a new Throwable.
	 *
	 * @return a failed future with its exception set to a new Throwable
	 */
	public static <T> FluentFuture<T> getFailedFuture() {
		SettableFuture<T> future = SettableFuture.create();
		future.setException(new Throwable());
		return FluentFuture.from(future);
	}
}

@@ -1331,32 +1331,380 @@
 om(future);%0A%09%7D%0A%0A
+%09/**%0A%09 * Returns a failed future with its exception set to the given Throwable%0A%09 *%0A%09 * @return a failed future with its exception set to the given Throwable%0A%09 */%0A%09public static %3CT%3E FluentFuture%3CT%3E getFailedFuture(Throwable e) %7B%0A%09%09SettableFuture%3CT%3E future = SettableFuture.create();%0A%09%09future.setException(e);%0A%09%09return FluentFuture.from(future);%0A%09%7D%0A%0A
 %09/**%0A%09 * Returns
@@ -1763,16 +1763,16 @@
 owable.%0A
-
 %09 *%0A%09 * 
@@ -1903,133 +1903,46 @@
 %7B%0A%09%09
-SettableFuture%3CT%3E future = Settab
+return getFai
 le
+d
 Future
-.create();%0A%09%09future.setException(new Throwable());%0A%09%09return FluentFuture.from(future
+(new Throwable()
 );%0A%09

Allow passing in a Throwable to getFailedFuture