Util { public static <T> ListenableFuture<T> asFuture(CompletionStage<T> stage) { SettableFuture<T> future = SettableFuture.create(); stage.whenComplete((result, throwable) -> { if (throwable != null) { future.setException(throwable); } else { future.set(result); } }); return future; } private  Util(); static CompletionStage<T> asStage(ListenableFuture<T> future); static ListenableFuture<T> asFuture(CompletionStage<T> stage);  }
@Test public void shouldConvertToFuture() throws Exception { ListenableFuture<Integer> converted = Util.asFuture(stage); stage.complete(9834); assertThat(converted.get(), equalTo(9834)); }
@Test public void shouldHandleNullsFromStage() throws Exception { ListenableFuture<Integer> converted = Util.asFuture(stage); stage.complete(null); assertThat(converted.get(), is(nullValue())); }
@Test public void shouldPropagateExceptionsToFuture() throws Throwable { ListenableFuture<Integer> converted = Util.asFuture(stage); NullPointerException expected = new NullPointerException("expected"); stage.completeExceptionally(expected); thrown.expect(is(expected)); try { converted.get(); } catch (ExecutionException ee) { throw ee.getCause(); } fail("should throw"); }