Java Code Examples for io.vertx.core.Context#runOnContext()

The following examples show how to use io.vertx.core.Context#runOnContext() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: AsyncInputStreamTest.java    From wisdom with Apache License 2.0 6 votes vote down vote up
@Test
public void testReadSmallFileFromUrl() throws IOException, InterruptedException {
    latch = new CountDownLatch(1);
    final ByteArrayOutputStream bos = new ByteArrayOutputStream();
    File file = new File("src/test/resources/a_file.txt");
    URL url = file.toURI().toURL();
    Context context = vertx.getOrCreateContext();
    final AsyncInputStream async = new AsyncInputStream(vertx, executor,
            url.openStream())
            .endHandler(event -> {
                assertThat(bos.toString()).startsWith("This is a file.");
                latch.countDown();
            }).setContext(context);
    context.runOnContext(event -> async.handler(buffer -> {
        try {
            bos.write(buffer.getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }));
    latch.await(30, TimeUnit.SECONDS);
}
 
Example 2
Source File: AsyncInputStreamTest.java    From wisdom with Apache License 2.0 6 votes vote down vote up
@Test
public void testReadSmallFile() throws FileNotFoundException, InterruptedException {
    latch = new CountDownLatch(1);
    final ByteArrayOutputStream bos = new ByteArrayOutputStream();
    File file = new File("src/test/resources/a_file.txt");
    FileInputStream fis = new FileInputStream(file);
    Context context = vertx.getOrCreateContext();
    final AsyncInputStream async = new AsyncInputStream(vertx, executor, fis)
            .endHandler(event -> {
                assertThat(bos.toString()).startsWith("This is a file.");
                latch.countDown();
            }).setContext(context);
    context.runOnContext(event -> async.handler(event1 -> {
        try {
            bos.write(event1.getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }));
    latch.await(30, TimeUnit.SECONDS);
}
 
Example 3
Source File: FuturesTest.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that the Future returned by the <em>create</em> method
 * will be completed on the vert.x context it was invoked on.
 *
 * @param ctx The vert.x test context.
 * @param vertx The vert.x instance.
 */
@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();
        });
    });
}
 
Example 4
Source File: HonoProtonHelper.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Executes some code on a given context.
 *
 * @param <T> The type of the result that the code produces.
 * @param requiredContext The context to run the code on.
 * @param codeToRun The code to execute. The code is required to either complete or
 *                  fail the promise that is passed into the handler.
 * @return The future containing the result of the promise passed in to the handler for
 *         executing the code. The future thus indicates the outcome of executing
 *         the code. The future will always be failed if the required context is {@code null}.
 */
public static <T> Future<T> executeOnContext(
        final Context requiredContext,
        final Handler<Promise<T>> codeToRun) {

    Objects.requireNonNull(codeToRun);

    final Promise<T> result = Promise.promise();
    if (requiredContext == null) {
        result.fail(new IllegalStateException("no context to run on"));
    } else {
        final Context currentContext = Vertx.currentContext();
        if (currentContext == requiredContext) {
            // we are already running on the correct Context,
            // just execute the code
            codeToRun.handle(result);
        } else {
            // we need to run the code on the Context on which
            // we had originally established the connection,
            // otherwise vertx-proton will yield undefined results
            requiredContext.runOnContext(go -> codeToRun.handle(result));
        }
    }
    return result.future();
}
 
Example 5
Source File: VertxUtil.java    From database with Apache License 2.0 5 votes vote down vote up
/**
 * Wrap a Handler in a way that will preserve the SLF4J MDC context.
 * The context from the current thread at the time of this method call
 * will be cached and restored within the wrapper at the time the
 * handler is invoked. This version delegates the handler call using
 * {@link Context#runOnContext(Handler)} from the current context that
 * calls this method, ensuring the handler call will run on the correct
 * event loop.
 */
public static <T> Handler<T> mdcEventLoop(final Handler<T> handler) {
  if (handler == null) {
    // Throw here instead of getting NPE inside the handler so we can see the stack trace
    throw new IllegalArgumentException("handler may not be null");
  }

  final Map<String, String> mdc = MDC.getCopyOfContextMap();
  final Context context = Vertx.currentContext();

  if (context == null) {
    // Throw here instead of getting NPE inside the handler so we can see the stack trace
    throw new IllegalStateException("Expecting to be on an Vert.x event loop context");
  }

  return t -> context.runOnContext((v) -> {
    Map<String, String> restore = MDC.getCopyOfContextMap();
    try {
      if (mdc == null) {
        MDC.clear();
      } else {
        MDC.setContextMap(mdc);
      }
      handler.handle(t);
    } finally {
      if (restore == null) {
        MDC.clear();
      } else {
        MDC.setContextMap(restore);
      }
    }
  });
}
 
Example 6
Source File: MixedThreading.java    From vertx-in-action with MIT License 5 votes vote down vote up
private void run(Context context) throws InterruptedException {
  CountDownLatch latch = new CountDownLatch(1);
  logger.info("I am in a non-Vert.x thread");
  context.runOnContext(v -> {
    logger.info("I am on the event-loop");
    vertx.setTimer(1000, id -> {
      logger.info("This is the final countdown");
      latch.countDown();
    });
  });
  logger.info("Waiting on the countdown latch...");
  latch.await();
  logger.info("Bye!");
}
 
Example 7
Source File: VertxCompletableFuture.java    From gravitee-gateway with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a new CompletableFuture that is asynchronously completed by a task running in the current Vert.x
 * {@link Context} with the value obtained by calling the given Supplier.
 * <p>
 * This method is different from {@link CompletableFuture#supplyAsync(Supplier)} as it does not use a fork join
 * executor, but use the Vert.x context.
 *
 * @param context  the context in which the supplier is executed.
 * @param supplier a function returning the value to be used to complete the returned CompletableFuture
 * @param <T>      the function's return type
 * @return the new CompletableFuture
 */
public static <T> VertxCompletableFuture<T> supplyAsync(Context context, Supplier<T> supplier) {
    Objects.requireNonNull(supplier);
    VertxCompletableFuture<T> future = new VertxCompletableFuture<>(Objects.requireNonNull(context));
    context.runOnContext(v -> {
        try {
            future.complete(supplier.get());
        } catch (Throwable e) {
            future.completeExceptionally(e);
        }
    });
    return future;
}
 
Example 8
Source File: VertxCompletableFuture.java    From gravitee-management-rest-api with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a new CompletableFuture that is asynchronously completed by a task running in the current Vert.x
 * {@link Context} with the value obtained by calling the given Supplier.
 * <p>
 * This method is different from {@link CompletableFuture#supplyAsync(Supplier)} as it does not use a fork join
 * executor, but use the Vert.x context.
 *
 * @param context  the context in which the supplier is executed.
 * @param supplier a function returning the value to be used to complete the returned CompletableFuture
 * @param <T>      the function's return type
 * @return the new CompletableFuture
 */
public static <T> VertxCompletableFuture<T> supplyAsync(Context context, Supplier<T> supplier) {
    Objects.requireNonNull(supplier);
    VertxCompletableFuture<T> future = new VertxCompletableFuture<>(Objects.requireNonNull(context));
    context.runOnContext(v -> {
        try {
            future.complete(supplier.get());
        } catch (Throwable e) {
            future.completeExceptionally(e);
        }
    });
    return future;
}
 
Example 9
Source File: VertxCompletableFuture.java    From gravitee-management-rest-api with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a new CompletableFuture that is asynchronously completed by a task running in the current Vert.x
 * {@link Context} with the value obtained by calling the given Supplier.
 * <p>
 * This method is different from {@link CompletableFuture#supplyAsync(Supplier)} as it does not use a fork join
 * executor, but use the Vert.x context.
 *
 * @param context  the context in which the supplier is executed.
 * @param supplier a function returning the value to be used to complete the returned CompletableFuture
 * @param <T>      the function's return type
 * @return the new CompletableFuture
 */
public static <T> VertxCompletableFuture<T> supplyAsync(Context context, Supplier<T> supplier) {
    Objects.requireNonNull(supplier);
    VertxCompletableFuture<T> future = new VertxCompletableFuture<>(Objects.requireNonNull(context));
    context.runOnContext(v -> {
        try {
            future.complete(supplier.get());
        } catch (Throwable e) {
            future.completeExceptionally(e);
        }
    });
    return future;
}
 
Example 10
Source File: CommandBuilderImpl.java    From vertx-shell with Apache License 2.0 5 votes vote down vote up
@Override
public Command build(Vertx vertx) {
  Context context = vertx.getOrCreateContext();
  return new Command() {
    @Override
    public String name() {
      return name;
    }
    @Override
    public CLI cli() {
      return cli;
    }

    @Override
    public Process createProcess(List<CliToken> args) {
      return new ProcessImpl(vertx, context, this, args, processHandler);
    }

    @Override
    public void complete(Completion completion) {
      if (completeHandler != null) {
        context.runOnContext(v -> {
          try {
            completeHandler.handle(completion);
          } catch (Throwable t) {
            completion.complete(Collections.emptyList());
            throw t;
          }
        });
      } else {
        Command.super.complete(completion);
      }
    }
  };
}
 
Example 11
Source File: VertxFutures.java    From atomix-vertx with Apache License 2.0 5 votes vote down vote up
/**
 * Wraps a void Vert.x handler.
 */
static <T> BiConsumer<T, Throwable> voidHandler(Handler<AsyncResult<Void>> handler, Context context) {
  checkNotNull(handler, "handler cannot be null");
  checkNotNull(context, "context cannot be null");
  return (result, error) -> {
    if (error == null) {
      context.runOnContext(v -> Future.<Void>succeededFuture().setHandler(handler));
    } else {
      context.runOnContext(v -> Future.<Void>failedFuture(error).setHandler(handler));
    }
  };
}
 
Example 12
Source File: BaseTestVerticle.java    From sfs with Apache License 2.0 5 votes vote down vote up
public void runOnServerContext(TestContext testContext, Callable<Observable<Void>> callable) {
    Async async = testContext.async();
    Context c = vertxContext().verticle().getContext();
    c.runOnContext(event -> {
        try {
            callable.call().subscribe(new TestSubscriber(testContext, async));
        } catch (Exception e) {
            testContext.fail(e);
        }
    });
}
 
Example 13
Source File: VertxCompletableFuture.java    From gravitee-management-rest-api with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a new CompletableFuture that is asynchronously completed by a task running in the current Vert.x
 * {@link Context} with the value obtained by calling the given Supplier.
 * <p>
 * This method is different from {@link CompletableFuture#supplyAsync(Supplier)} as it does not use a fork join
 * executor, but use the Vert.x context.
 *
 * @param context  the context in which the supplier is executed.
 * @param supplier a function returning the value to be used to complete the returned CompletableFuture
 * @param <T>      the function's return type
 * @return the new CompletableFuture
 */
public static <T> VertxCompletableFuture<T> supplyAsync(Context context, Supplier<T> supplier) {
    Objects.requireNonNull(supplier);
    VertxCompletableFuture<T> future = new VertxCompletableFuture<>(Objects.requireNonNull(context));
    context.runOnContext(v -> {
        try {
            future.complete(supplier.get());
        } catch (Throwable e) {
            future.completeExceptionally(e);
        }
    });
    return future;
}
 
Example 14
Source File: VertxCompletableFuture.java    From gravitee-management-rest-api with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a new CompletableFuture that is asynchronously completed by a task running in the
 * current Vert.x {@link Context} after it runs the given action.
 * <p>
 * This method is different from {@link CompletableFuture#runAsync(Runnable)} as it does not use a fork join
 * executor, but use the Vert.x context.
 *
 * @param context  the context
 * @param runnable the action to run before completing the returned CompletableFuture
 * @return the new CompletableFuture
 */
public static VertxCompletableFuture<Void> runAsync(Context context, Runnable runnable) {
    Objects.requireNonNull(runnable);
    VertxCompletableFuture<Void> future = new VertxCompletableFuture<>(context);
    context.runOnContext(v -> {
        try {
            runnable.run();
            future.complete(null);
        } catch (Throwable e) {
            future.completeExceptionally(e);
        }
    });
    return future;
}
 
Example 15
Source File: VertxProtonExamples.java    From vertx-proton with Apache License 2.0 5 votes vote down vote up
public void example5(Vertx vertx, ProtonClient client) {
  Context myContext = vertx.getOrCreateContext();

  myContext.runOnContext(x -> {
    client.connect("hostname", 5672, connectResult -> {
      // In this case the context will be 'myContext' from earlier
    });
  });
}
 
Example 16
Source File: VertxCompletableFuture.java    From gravitee-management-rest-api with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a new CompletableFuture that is asynchronously completed by a task running in the current Vert.x
 * {@link Context} with the value obtained by calling the given Supplier.
 * <p>
 * This method is different from {@link CompletableFuture#supplyAsync(Supplier)} as it does not use a fork join
 * executor, but use the Vert.x context.
 *
 * @param context  the context in which the supplier is executed.
 * @param supplier a function returning the value to be used to complete the returned CompletableFuture
 * @param <T>      the function's return type
 * @return the new CompletableFuture
 */
public static <T> VertxCompletableFuture<T> supplyAsync(Context context, Supplier<T> supplier) {
    Objects.requireNonNull(supplier);
    VertxCompletableFuture<T> future = new VertxCompletableFuture<>(Objects.requireNonNull(context));
    context.runOnContext(v -> {
        try {
            future.complete(supplier.get());
        } catch (Throwable e) {
            future.completeExceptionally(e);
        }
    });
    return future;
}
 
Example 17
Source File: VertxFutures.java    From atomix-vertx with Apache License 2.0 5 votes vote down vote up
/**
 * Wraps a Vert.x handler.
 */
static <T> BiConsumer<T, Throwable> resultHandler(Handler<AsyncResult<T>> handler, Context context) {
  checkNotNull(handler, "handler cannot be null");
  checkNotNull(context, "context cannot be null");
  return (result, error) -> {
    if (error == null) {
      context.runOnContext(v -> Future.succeededFuture(result).setHandler(handler));
    } else {
      context.runOnContext(v -> Future.<T>failedFuture(error).setHandler(handler));
    }
  };
}
 
Example 18
Source File: VertxCompletableFuture.java    From gravitee-management-rest-api with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a new CompletableFuture that is asynchronously completed by a task running in the
 * current Vert.x {@link Context} after it runs the given action.
 * <p>
 * This method is different from {@link CompletableFuture#runAsync(Runnable)} as it does not use a fork join
 * executor, but use the Vert.x context.
 *
 * @param context  the context
 * @param runnable the action to run before completing the returned CompletableFuture
 * @return the new CompletableFuture
 */
public static VertxCompletableFuture<Void> runAsync(Context context, Runnable runnable) {
    Objects.requireNonNull(runnable);
    VertxCompletableFuture<Void> future = new VertxCompletableFuture<>(context);
    context.runOnContext(v -> {
        try {
            runnable.run();
            future.complete(null);
        } catch (Throwable e) {
            future.completeExceptionally(e);
        }
    });
    return future;
}
 
Example 19
Source File: VertxCompletableFuture.java    From gravitee-management-rest-api with Apache License 2.0 2 votes vote down vote up
/**
 * Creates an instance of {@link VertxCompletableFuture}, using the given {@link Context}.
 *
 * @param context the context
 */
public VertxCompletableFuture(Context context) {
    this.context = Objects.requireNonNull(context);
    this.executor = command -> context.runOnContext(v -> command.run());
}
 
Example 20
Source File: VertxCompletableFuture.java    From gravitee-management-rest-api with Apache License 2.0 2 votes vote down vote up
/**
 * Creates an instance of {@link VertxCompletableFuture}, using the given {@link Context}.
 *
 * @param context the context
 */
public VertxCompletableFuture(Context context) {
    this.context = Objects.requireNonNull(context);
    this.executor = command -> context.runOnContext(v -> command.run());
}