Utility methods for use in generated producer code.
| 39 | * Utility methods for use in generated producer code. |
| 40 | */ |
| 41 | public final class Producers { |
| 42 | /** |
| 43 | * Returns a future of {@link Produced} that represents the completion (either success or failure) |
| 44 | * of the given future. If the input future succeeds, then the resulting future also succeeds with |
| 45 | * a successful {@code Produced}; if the input future fails, then the resulting future succeeds |
| 46 | * with a failing {@code Produced}. |
| 47 | * |
| 48 | * <p>Cancelling the resulting future will propagate the cancellation to the input future; but |
| 49 | * cancelling the input future will trigger the resulting future to succeed with a failing |
| 50 | * {@code Produced}. |
| 51 | */ |
| 52 | // TODO(beder): Document what happens with an InterruptedException after you figure out how to |
| 53 | // trigger one in a test. |
| 54 | public static <T> ListenableFuture<Produced<T>> createFutureProduced(ListenableFuture<T> future) { |
| 55 | return catchingAsync( |
| 56 | transform(future, Producers.<T>resultToProduced(), directExecutor()), |
| 57 | Throwable.class, |
| 58 | Producers.<T>futureFallbackForProduced(), |
| 59 | directExecutor()); |
| 60 | } |
| 61 | |
| 62 | private static final Function<Object, Produced<Object>> RESULT_TO_PRODUCED = |
| 63 | new Function<Object, Produced<Object>>() { |
| 64 | @Override |
| 65 | public Produced<Object> apply(Object result) { |
| 66 | return Produced.successful(result); |
| 67 | } |
| 68 | }; |
| 69 | |
| 70 | @SuppressWarnings({"unchecked", "rawtypes"}) // bivariant implementation |
| 71 | private static <T> Function<T, Produced<T>> resultToProduced() { |
| 72 | return (Function) RESULT_TO_PRODUCED; |
| 73 | } |
| 74 | |
| 75 | private static final AsyncFunction<Throwable, Produced<Object>> FUTURE_FALLBACK_FOR_PRODUCED = |
| 76 | new AsyncFunction<Throwable, Produced<Object>>() { |
| 77 | @Override |
| 78 | public ListenableFuture<Produced<Object>> apply(Throwable t) throws Exception { |
| 79 | Produced<Object> produced = Produced.failed(t); |
| 80 | return Futures.immediateFuture(produced); |
| 81 | } |
| 82 | }; |
| 83 | |
| 84 | @SuppressWarnings({"unchecked", "rawtypes"}) // bivariant implementation |
| 85 | private static <T> AsyncFunction<Throwable, Produced<T>> futureFallbackForProduced() { |
| 86 | return (AsyncFunction) FUTURE_FALLBACK_FOR_PRODUCED; |
| 87 | } |
| 88 | |
| 89 | /** |
| 90 | * Returns a future of a {@code Set} that contains a single element: the result of the input |
| 91 | * future. |
| 92 | */ |
| 93 | public static <T> ListenableFuture<Set<T>> createFutureSingletonSet(ListenableFuture<T> future) { |
| 94 | return transform( |
| 95 | future, |
| 96 | new Function<T, Set<T>>() { |
| 97 | @Override |
| 98 | public Set<T> apply(T value) { |
nothing calls this directly
no test coverage detected