Futures { public static <T> Future<T> create(final Supplier<CompletionStage<T>> futureSupplier) { final Context originalContext = Vertx.currentContext(); final CompletionStage<T> future; try { future = futureSupplier.get(); } catch (final Exception e) { return Future.failedFuture(e); } final Promise<T> result = Promise.promise(); future.whenComplete((r, e) -> { final AsyncResult<T> asyncResult = e != null ? Future.failedFuture(e) : Future.succeededFuture(r); if (originalContext != null && originalContext != Vertx.currentContext()) { originalContext.runOnContext(go -> result.handle(asyncResult)); } else { result.handle(asyncResult); } }); return result.future(); } private  Futures(); static Future<T> create(final Supplier<CompletionStage<T>> futureSupplier); static Future<T> executeBlocking(final Vertx vertx, final BlockingCode<T> blocking);  }
@Test @Timeout(value = 5, timeUnit = TimeUnit.SECONDS) public void testCreateGetsCompletedOnOriginalContext(final VertxTestContext ctx, final Vertx vertx) { final Context context = vertx.getOrCreateContext(); context.runOnContext(v -> { LOG.trace("run on context"); Futures.create(() -> CompletableFuture.runAsync(() -> { LOG.trace("run async"); })).onComplete(r -> { LOG.trace("after run async"); ctx.verify(() -> { assertTrue(r.succeeded()); assertEquals(context, vertx.getOrCreateContext()); }); ctx.completeNow(); }); }); }
@Test @Timeout(value = 5, timeUnit = TimeUnit.SECONDS) public void testCreateWithNoVertxContext(final VertxTestContext ctx) { Futures.create(() -> CompletableFuture.runAsync(() -> { LOG.trace("run async"); })).onComplete(r -> { LOG.trace("after run async"); ctx.verify(() -> { assertTrue(r.succeeded()); assertNull(Vertx.currentContext()); }); ctx.completeNow(); }); }
@Test @Timeout(value = 5, timeUnit = TimeUnit.SECONDS) public void testCreatePropagatesFailure() { final Exception expectedException = new Exception("expected exception"); Futures.create(() -> { final CompletableFuture<Void> completableFuture = new CompletableFuture<>(); completableFuture.completeExceptionally(expectedException); return completableFuture; }).onComplete(r -> { assertTrue(r.failed()); assertEquals(expectedException, r.cause()); }); }