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

The following examples show how to use io.vertx.core.Vertx#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: AsyncCompletion.java    From incubator-tuweni with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a completion that, after the given function executes on a vertx context and returns a completion, completes
 * when the completion from the function does.
 *
 * @param vertx The vertx context.
 * @param fn The function returning a completion.
 * @return A completion.
 */
static AsyncCompletion runOnContext(Vertx vertx, Supplier<? extends AsyncCompletion> fn) {
  requireNonNull(fn);
  CompletableAsyncCompletion completion = AsyncCompletion.incomplete();
  vertx.runOnContext(ev -> {
    try {
      fn.get().whenComplete(ex2 -> {
        if (ex2 == null) {
          try {
            completion.complete();
          } catch (Throwable ex3) {
            completion.completeExceptionally(ex3);
          }
        } else {
          completion.completeExceptionally(ex2);
        }
      });
    } catch (Throwable ex1) {
      completion.completeExceptionally(ex1);
    }
  });
  return completion;
}
 
Example 2
Source File: AsyncResult.java    From incubator-tuweni with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a result that, after the given function executes on a vertx context and returns a result, completes when
 * the returned result completes, with the same value or exception.
 *
 * <p>
 * Note that the given function is run directly on the context and should not block.
 *
 * @param vertx The vertx context.
 * @param fn The function returning a result.
 * @param <T> The type of the returned result's value.
 * @return A new result.
 */
static <T> AsyncResult<T> runOnContext(Vertx vertx, Supplier<? extends AsyncResult<T>> fn) {
  requireNonNull(fn);
  CompletableAsyncResult<T> asyncResult = AsyncResult.incomplete();
  vertx.runOnContext(ev -> {
    try {
      fn.get().whenComplete((u, ex2) -> {
        if (ex2 == null) {
          try {
            asyncResult.complete(u);
          } catch (Throwable ex3) {
            asyncResult.completeExceptionally(ex3);
          }
        } else {
          asyncResult.completeExceptionally(ex2);
        }
      });
    } catch (Throwable ex1) {
      asyncResult.completeExceptionally(ex1);
    }
  });
  return asyncResult;
}
 
Example 3
Source File: AsyncCompletion.java    From cava with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a completion that, after the given function executes on a vertx context and returns a completion, completes
 * when the completion from the function does.
 *
 * @param vertx The vertx context.
 * @param fn The function returning a completion.
 * @return A completion.
 */
static AsyncCompletion runOnContext(Vertx vertx, Supplier<? extends AsyncCompletion> fn) {
  requireNonNull(fn);
  CompletableAsyncCompletion completion = AsyncCompletion.incomplete();
  vertx.runOnContext(ev -> {
    try {
      fn.get().whenComplete(ex2 -> {
        if (ex2 == null) {
          try {
            completion.complete();
          } catch (Throwable ex3) {
            completion.completeExceptionally(ex3);
          }
        } else {
          completion.completeExceptionally(ex2);
        }
      });
    } catch (Throwable ex1) {
      completion.completeExceptionally(ex1);
    }
  });
  return completion;
}
 
Example 4
Source File: AsyncResult.java    From cava with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a result that, after the given function executes on a vertx context and returns a result, completes when
 * the returned result completes, with the same value or exception.
 *
 * <p>
 * Note that the given function is run directly on the context and should not block.
 *
 * @param vertx The vertx context.
 * @param fn The function returning a result.
 * @param <T> The type of the returned result's value.
 * @return A new result.
 */
static <T> AsyncResult<T> runOnContext(Vertx vertx, Supplier<? extends AsyncResult<T>> fn) {
  requireNonNull(fn);
  CompletableAsyncResult<T> asyncResult = AsyncResult.incomplete();
  vertx.runOnContext(ev -> {
    try {
      fn.get().whenComplete((u, ex2) -> {
        if (ex2 == null) {
          try {
            asyncResult.complete(u);
          } catch (Throwable ex3) {
            asyncResult.completeExceptionally(ex3);
          }
        } else {
          asyncResult.completeExceptionally(ex2);
        }
      });
    } catch (Throwable ex1) {
      asyncResult.completeExceptionally(ex1);
    }
  });
  return asyncResult;
}
 
Example 5
Source File: StateConsumerTest.java    From vertx-consul-client with Apache License 2.0 6 votes vote down vote up
@Test
public void test1() throws InterruptedException {
  final Vertx vertx = Vertx.vertx();
  final StateConsumer<Integer> consumer = new StateConsumer<>(false);
  final CountDownLatch latch = new CountDownLatch(1);
  final int n = 100000;
  vertx.runOnContext(v -> {
    latch.countDown();
    for (int i = 0; i < n; i++) {
      consumer.consume(i);
    }
  });
  latch.await();
  for (int i = 0; i < n; i++) {
    consumer.await(i);
  }
  consumer.check();
  vertx.close();
}
 
Example 6
Source File: VertxTest.java    From cyclops with Apache License 2.0 5 votes vote down vote up
@Test @Ignore
public void downloadUrls(){

 //cyclops2-react async.Queues
    Queue<String> downloadQueue = new Queue<String>();
    Queue<String> completedQueue = new Queue<String>();

    //vert.x meets cyclops2-react
    Vertx vertx = Vertx.factory.vertx();
    LazyReact react = new LazyReact(c->vertx.runOnContext(v -> c.run()));


    //populate the download queue asynchronously
    ReactiveSeq.of("www.aol.com","www.rte.ie","www.aol.com")
               .peek(next->System.out.println("adding toNested download queue " + next))
               .runFuture(c->vertx.runOnContext(v -> c.run()),t->t.forEach(downloadQueue::add,System.err::println));

    //download asynchronously : all cyclops2-react tasks are passed into vert.x
    react.fromStream(downloadQueue.stream())
         .peek(System.out::println)
         .map(url->vertx.createHttpClient().getNow(url,"",resp->resp.bodyHandler(body-> completedQueue.add(body.getString(0, body.length())))))
         .run();


    //handle the results
    completedQueue.stream()
                  .peek(next->System.out.println("just downloaded" + next))
                  .forEach(System.out::println);



}
 
Example 7
Source File: VertxTest.java    From cyclops with Apache License 2.0 5 votes vote down vote up
@Test
public void sum(){
    Vertx vertx = Vertx.factory.vertx();

	LazyReact react = new LazyReact(c->vertx.runOnContext(v -> c.run()));
	int number = react.of(1, 2, 3).map(i -> i + 1).reduce((a,b) -> a + b).orElse(Integer.MIN_VALUE);
	System.out.println("sum = " + number); // 2 + 3 + 4 = 9

	assertThat(number,equalTo(9));
}
 
Example 8
Source File: JUnitTest.java    From vertx-unit with Apache License 2.0 5 votes vote down vote up
@Test
public void failWithAsync(TestContext context) {
  Vertx vertx = Vertx.vertx();
  Async async = context.async();
  vertx.runOnContext(v -> {
    try {
      context.verify(v2 -> fail("Testing async failure"));
    } finally {
      async.complete();
    }
  });
  async.await();
}
 
Example 9
Source File: JUnitTest.java    From vertx-unit with Apache License 2.0 5 votes vote down vote up
@Test
public void testMethod1(TestContext context) {
  Async async = context.async();
  Vertx vertx = Vertx.vertx().exceptionHandler(context.exceptionHandler());
  vertx.runOnContext(v -> {
    count.incrementAndGet();
    fail();
  });
}
 
Example 10
Source File: HystrixExamples.java    From vertx-circuit-breaker with Apache License 2.0 5 votes vote down vote up
public void exampleHystrix3(Vertx vertx) {
  vertx.runOnContext(v -> {
    Context context = vertx.getOrCreateContext();
    HystrixCommand<String> command = getSomeCommandInstance();
    command.observe().subscribe(result -> {
      context.runOnContext(v2 -> {
        // Back on context (event loop or worker)
        String r = result;
      });
    });
  });
}
 
Example 11
Source File: TestVertxUtils.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetOrCreateVertx() throws InterruptedException {
  Vertx vertx = VertxUtils.getOrCreateVertxByName("ut", null);

  Holder<String> name = new Holder<>();
  CountDownLatch latch = new CountDownLatch(1);
  vertx.runOnContext(v -> {
    name.value = Thread.currentThread().getName();
    latch.countDown();
  });
  latch.await();

  Assert.assertEquals(name.value, "ut-vert.x-eventloop-thread-0");
  VertxUtils.blockCloseVertxByName("ut");
}
 
Example 12
Source File: InfluxDbTestHelper.java    From vertx-micrometer-metrics with Apache License 2.0 5 votes vote down vote up
static void simulateInfluxServer(Vertx vertx, TestContext context, int port, Consumer<String> onRequest) {
  Async ready = context.async();
  vertx.runOnContext(v -> vertx.createHttpServer(new HttpServerOptions()
    .setCompressionSupported(true)
    .setDecompressionSupported(true)
    .setLogActivity(true)
    .setHost("localhost")
    .setPort(port))
    .requestHandler(req -> {
      req.exceptionHandler(context.exceptionHandler());
      req.bodyHandler(buffer -> {
        String str = buffer.toString();
        if (str.isEmpty()) {
          req.response().setStatusCode(200).end();
          return;
        }
        try {
          onRequest.accept(str);
        } finally {
          req.response().setStatusCode(200).end();
        }
      });
    })
    .exceptionHandler(System.err::println)
    .listen(port, "localhost", res -> {
      if (res.succeeded()) {
        ready.complete();
      } else {
        context.fail(res.cause());
      }
    }));
  ready.await(10000);
}
 
Example 13
Source File: AsyncCompletion.java    From cava with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a completion that completes after the given action executes on a vertx context.
 *
 * <p>
 * Note that the given function is run directly on the context and should not block.
 *
 * @param vertx The vertx context.
 * @param action The action to execute.
 * @return A completion.
 */
static AsyncCompletion runOnContext(Vertx vertx, Runnable action) {
  requireNonNull(action);
  CompletableAsyncCompletion completion = AsyncCompletion.incomplete();
  vertx.runOnContext(ev -> {
    try {
      action.run();
      completion.complete();
    } catch (Throwable ex) {
      completion.completeExceptionally(ex);
    }
  });
  return completion;
}
 
Example 14
Source File: AsyncCompletion.java    From incubator-tuweni with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a completion that completes after the given action executes on a vertx context.
 *
 * <p>
 * Note that the given function is run directly on the context and should not block.
 *
 * @param vertx The vertx context.
 * @param action The action to execute.
 * @return A completion.
 */
static AsyncCompletion runOnContext(Vertx vertx, Runnable action) {
  requireNonNull(action);
  CompletableAsyncCompletion completion = AsyncCompletion.incomplete();
  vertx.runOnContext(ev -> {
    try {
      action.run();
      completion.complete();
    } catch (Throwable ex) {
      completion.completeExceptionally(ex);
    }
  });
  return completion;
}
 
Example 15
Source File: ExecuteEventbusObject.java    From vxms with Apache License 2.0 4 votes vote down vote up
/** Execute the reply chain */
@SuppressWarnings("unchecked")
public void execute() {
  final Vertx vertx = vxmsShared.getVertx();
  vertx.runOnContext(
      action -> {
        ofNullable(excecuteEventBusAndReply)
            .ifPresent(
                evFunction -> {
                  try {
                    evFunction.execute(
                        methodId,
                        vxmsShared,
                        errorMethodHandler,
                        message,
                        encoder,
                        errorHandler,
                        onFailureRespond,
                        deliveryOptions,
                        retryCount,
                        timeout,
                        circuitBreakerTimeout);
                  } catch (Exception e) {
                    e.printStackTrace();
                  }
                });
        ofNullable(objectConsumer)
            .ifPresent(
                userOperation -> ResponseExecution.createResponse(
                    methodId,
                    retryCount,
                    timeout,
                    circuitBreakerTimeout,
                    userOperation,
                    errorHandler,
                    onFailureRespond,
                    errorMethodHandler,
                    vxmsShared,
                    failure,
                    value -> {
                      if (value.succeeded()) {
                        respond(value.getResult());
                      } else {
                        fail(
                            value.getCause().getMessage(),
                            HttpResponseStatus.INTERNAL_SERVER_ERROR.code());
                      }
                    }));

        ofNullable(chain)
            .ifPresent(
                chainList -> {
                  if (!chainList.isEmpty()) {
                    final ExecutionStep executionStep = chainList.get(0);
                    ofNullable(executionStep.getChainconsumer())
                        .ifPresent(
                            initialConsumer -> {
                              int retry = retryCount;
                              ResponseExecution.createResponse(
                                  methodId,
                                  retry,
                                  timeout,
                                  circuitBreakerTimeout,
                                  initialConsumer,
                                  errorHandler,
                                  onFailureRespond,
                                  errorMethodHandler,
                                  vxmsShared,
                                  failure,
                                  value ->
                                      getResultHandler(
                                          methodId,
                                          vxmsShared,
                                          failure,
                                          errorMethodHandler,
                                          chainList,
                                          errorHandler,
                                          onFailureRespond,
                                          timeout,
                                          circuitBreakerTimeout,
                                          retry,
                                          value));
                            });
                  }
                });
      });
}
 
Example 16
Source File: ExecuteEventbusString.java    From vxms with Apache License 2.0 4 votes vote down vote up
/** Execute the reply chain */
@SuppressWarnings("unchecked")
public void execute() {
  final Vertx vertx = vxmsShared.getVertx();
  vertx.runOnContext(
      action -> {
        ofNullable(excecuteEventBusAndReply)
            .ifPresent(
                evFunction -> {
                  try {
                    evFunction.execute(
                        methodId,
                        vxmsShared,
                        errorMethodHandler,
                        message,
                        errorHandler,
                        onFailureRespond,
                        deliveryOptions,
                        retryCount,
                        timeout,
                        circuitBreakerTimeout);
                  } catch (Exception e) {
                    e.printStackTrace();
                  }
                });

        ofNullable(stringConsumer)
            .ifPresent(
                userOperation -> ResponseExecution.createResponse(
                    methodId,
                    retryCount,
                    timeout,
                    circuitBreakerTimeout,
                    userOperation,
                    errorHandler,
                    onFailureRespond,
                    errorMethodHandler,
                    vxmsShared,
                    failure,
                    value -> {
                      if (value.succeeded()) {
                        respond(value.getResult());
                      } else {
                        fail(
                            value.getCause().getMessage(),
                            HttpResponseStatus.INTERNAL_SERVER_ERROR.code());
                      }
                    }));

        ofNullable(chain)
            .ifPresent(
                chainList -> {
                  if (!chainList.isEmpty()) {
                    final ExecutionStep executionStep = chainList.get(0);
                    ofNullable(executionStep.getChainconsumer())
                        .ifPresent(
                            initialConsumer -> {
                              int retry = retryCount;
                              ResponseExecution.createResponse(
                                  methodId,
                                  retry,
                                  timeout,
                                  circuitBreakerTimeout,
                                  initialConsumer,
                                  errorHandler,
                                  onFailureRespond,
                                  errorMethodHandler,
                                  vxmsShared,
                                  failure,
                                  value -> getResultHandler(
                                      methodId,
                                      vxmsShared,
                                      failure,
                                      errorMethodHandler,
                                      chainList,
                                      errorHandler,
                                      onFailureRespond,
                                      timeout,
                                      circuitBreakerTimeout,
                                      retry,
                                      value));
                            });
                  }
                });
      });
}
 
Example 17
Source File: ExecuteEventbusByte.java    From vxms with Apache License 2.0 4 votes vote down vote up
/** Execute the reply chain */
@SuppressWarnings("unchecked")
public void execute() {
  final Vertx vertx = vxmsShared.getVertx();
  vertx.runOnContext(
      action -> {
        ofNullable(excecuteEventBusAndReply)
            .ifPresent(
                evFunction -> {
                  try {
                    evFunction.execute(
                        methodId,
                        vxmsShared,
                        errorMethodHandler,
                        message,
                        errorHandler,
                        onFailureRespond,
                        deliveryOptions,
                        retryCount,
                        timeout,
                        circuitBreakerTimeout);
                  } catch (Exception e) {
                    e.printStackTrace();
                  }
                });

        ofNullable(byteConsumer)
            .ifPresent(
                userOperation -> ResponseExecution.createResponse(
                    methodId,
                    retryCount,
                    timeout,
                    circuitBreakerTimeout,
                    userOperation,
                    errorHandler,
                    onFailureRespond,
                    errorMethodHandler,
                    vxmsShared,
                    failure,
                    value -> {
                      if (value.succeeded()) {
                        respond(value.getResult());
                      } else {
                        fail(
                            value.getCause().getMessage(),
                            HttpResponseStatus.INTERNAL_SERVER_ERROR.code());
                      }
                    }));

        ofNullable(chain)
            .ifPresent(
                chainList -> {
                  if (!chainList.isEmpty()) {
                    final ExecutionStep executionStep = chainList.get(0);
                    ofNullable(executionStep.getChainconsumer())
                        .ifPresent(
                            initialConsumer -> {
                              int retry = retryCount;
                              ResponseExecution.createResponse(
                                  methodId,
                                  retry,
                                  timeout,
                                  circuitBreakerTimeout,
                                  initialConsumer,
                                  errorHandler,
                                  onFailureRespond,
                                  errorMethodHandler,
                                  vxmsShared,
                                  failure,
                                  value ->
                                      getResultHandler(
                                          methodId,
                                          vxmsShared,
                                          failure,
                                          errorMethodHandler,
                                          chainList,
                                          errorHandler,
                                          onFailureRespond,
                                          timeout,
                                          circuitBreakerTimeout,
                                          retry,
                                          value));
                            });
                  }
                });
      });
}
 
Example 18
Source File: VertxTest.java    From cyclops with Apache License 2.0 4 votes vote down vote up
@Test @Ignore
public void httpServer(){

    Vertx vertx = Vertx.factory.vertx();
    CompletableFuture<HttpServer> server =new CompletableFuture<>();



    Queue<HttpServerRequest> reqs = QueueFactories.<HttpServerRequest>boundedNonBlockingQueue(1000,
                                                        WaitStrategy.spinWait())
                                                        .build();


    vertx.createHttpServer(new HttpServerOptions().
            setPort(8080).
            setHost("localhost")
        )
    .requestHandler(event-> {
        reqs.add(event);
        System.out.println(event.absoluteURI());
    }).listen(e->{
           if(e.succeeded())
               server.complete(e.result());
           else
               server.completeExceptionally(e.cause());
    });

    LazyReact react = new LazyReact(c->vertx.runOnContext(v -> c.run()));

    react.fromStream(reqs.stream())
         .filter(req->req.getParam("num")!=null)
         .peek(i->System.out.println("grouping " + i))
         .grouped(2)
         .map(list-> tuple(list.getOrElse(0,null).response(),list.getOrElse(1,null).response(),getParam(list.getOrElse(0,null)),
                getParam(list.getOrElse(1,null))))
         .peek(i->System.out.println("peeking + "+i))
         .peek(t->t._1().end("adding "+(t._3()+t._4())))
         .peek(t->t._2().end("multiplying "+t._3()*t._4()))
         .run();


       new SimpleReact(c->vertx.runOnContext(v -> c.run())).from(server)
                       .then(s->"server started")
                       .onFail(e->"failed toNested skip "+e.getMessage())
                       .peek(System.out::println);

    while(true){

    }



}