io.vertx.core.Context Java Examples

The following examples show how to use io.vertx.core.Context. 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: BlockFile.java    From sfs with Apache License 2.0 6 votes vote down vote up
public Observable<Optional<ChecksummedPositional<byte[]>>> getBlock(SfsVertx vertx, final long position) {
    Context context = vertx.getOrCreateContext();
    return getBlock0(context, position)
            .map(buffer -> {
                Optional<Block.Frame<byte[]>> oFrame = decodeFrame(buffer, false);
                if (oFrame.isPresent()) {
                    Block.Frame<byte[]> frame = oFrame.get();
                    return of(new ChecksummedPositional<byte[]>(position, frame.getData(), frame.getChecksum()) {
                        @Override
                        public boolean isChecksumValid() {
                            return frame.isChecksumValid();
                        }
                    });
                } else {
                    return absent();
                }
            });
}
 
Example #2
Source File: MongoClientTestBase.java    From vertx-mongo-client with Apache License 2.0 6 votes vote down vote up
@Test
public void testContexts() {
  vertx.runOnContext(v -> {
    Context currentContext = Vertx.currentContext();
    assertNotNull(currentContext);

    String collection = randomCollection();
    JsonObject document = new JsonObject().put("title", "The Hobbit");
    document.put("_id", 123456);
    document.put("foo", "bar");

    mongoClient.insert(collection, document, onSuccess(id -> {
      Context resultContext = Vertx.currentContext();
      assertSame(currentContext, resultContext);
      testComplete();
    }));

  });
  await();
}
 
Example #3
Source File: EventInitializer.java    From vxms with Apache License 2.0 6 votes vote down vote up
protected static void initCallback(
    VxmsShared vxmsShared,
    Object service,
    Method eventBusMethod,
    Consume path,
    Optional<Method> errorMethod) {
  final Vertx vertx = vxmsShared.getVertx();
  final String contexRoot =
      URIUtil.getCleanContextRoot(
          ConfigurationUtil.getContextRoot(
              vertx.getOrCreateContext().config(), service.getClass()));
  final String route = contexRoot + URIUtil.cleanPath(path.value());
  final Context context = vertx.getOrCreateContext();
  final String methodId =
      path.value() + EVENTBUS + ConfigurationUtil.getCircuitBreakerIDPostfix(context.config());
  registerCallback(methodId, route, vxmsShared, service, eventBusMethod, errorMethod);
}
 
Example #4
Source File: SfsFileSystem.java    From sfs with Apache License 2.0 6 votes vote down vote up
public Observable<Void> open(VertxContext<Server> vertxContext, Path workingDirectory) {
    this.workingDirectory = workingDirectory;
    this.tmpDirectory = Paths.get(workingDirectory.toString(), "tmp");
    this.backupDirectory = Paths.get(workingDirectory.toString(), "backup");
    SfsVertx vertx = vertxContext.vertx();
    Context context = vertx.getOrCreateContext();
    return RxHelper.executeBlocking(context, vertx.getBackgroundPool(), () -> {
        try {
            Files.createDirectories(workingDirectory);
            Files.createDirectories(tmpDirectory);
            Files.createDirectories(backupDirectory);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return null;
    });
}
 
Example #5
Source File: ContextScheduler.java    From vertx-rx with Apache License 2.0 6 votes vote down vote up
private void execute(Object arg) {
  if (workerExecutor != null) {
    workerExecutor.executeBlocking(fut -> {
      run(null);
      fut.complete();
    }, ordered, null);
  } else {
    Context ctx = context != null ? context : vertx.getOrCreateContext();
    if (blocking) {
      ctx.executeBlocking(fut -> {
        run(null);
        fut.complete();
      }, ordered, null);
    } else {
      ctx.runOnContext(this::run);
    }
  }
}
 
Example #6
Source File: AdminAPI.java    From raml-module-builder with Apache License 2.0 6 votes vote down vote up
@Validate
@Override
public void getAdminSlowQueries(int querytimerunning, Map<String, String> okapiHeaders,
    Handler<AsyncResult<Response>> asyncResultHandler, Context vertxContext) {

  /** the queries returned are of this backend's most recent query. If state is active this field shows the currently
   * executing query. In all other states, it shows the last query that was executed.*/
  PostgresClient.getInstance(vertxContext.owner()).select(
    "SELECT EXTRACT(EPOCH FROM now() - query_start) as runtime, client_addr, usename, datname, state, query "+
    "FROM  pg_stat_activity " +
    "WHERE now() - query_start > '"+querytimerunning+" seconds'::interval "+
    "ORDER BY runtime DESC;", reply -> {
      if(reply.succeeded()){

        OutStream stream = new OutStream(reply.result());

        asyncResultHandler.handle(io.vertx.core.Future.succeededFuture(GetAdminSlowQueriesResponse.
          respond200WithApplicationJson(stream)));
      }
      else{
        log.error(reply.cause().getMessage(), reply.cause());
        asyncResultHandler.handle(io.vertx.core.Future.failedFuture(reply.cause().getMessage()));
      }
    });
}
 
Example #7
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 #8
Source File: VertxCompletableFuture.java    From gravitee-gateway with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a new CompletableFuture that is asynchronously completed by a action running in the worker thread pool of
 * Vert.x
 * <p>
 * This method is different from {@link CompletableFuture#runAsync(Runnable)} as it does not use a fork join
 * executor, but the worker thread pool.
 *
 * @param context  the Vert.x context
 * @param runnable the action, when its execution completes, it completes the returned CompletableFuture. If the
 *                 execution throws an exception, the returned CompletableFuture is completed exceptionally.
 * @return the new CompletableFuture
 */
public static VertxCompletableFuture<Void> runBlockingAsync(Context context, Runnable runnable) {
    Objects.requireNonNull(runnable);
    VertxCompletableFuture<Void> future = new VertxCompletableFuture<>(Objects.requireNonNull(context));
    context.executeBlocking(
            fut -> {
                try {
                    runnable.run();
                    future.complete(null);
                } catch (Throwable e) {
                    future.completeExceptionally(e);
                }
            },
            null
    );
    return future;
}
 
Example #9
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 #10
Source File: ContextTest.java    From vertx-sql-client with Apache License 2.0 6 votes vote down vote up
@Test
public void testConnection(TestContext testCtx) {
  Async async = testCtx.async();
  Context connCtx = vertx.getOrCreateContext();
  connCtx.runOnContext(v1 -> {
    PgConnection.connect(vertx, options, testCtx.asyncAssertSuccess(conn -> {
      testCtx.assertEquals(connCtx, Vertx.currentContext());
      conn
        .query("SELECT *  FROM (VALUES ('Hello world')) t1 (col1) WHERE 1 = 1")
        .execute(testCtx.asyncAssertSuccess(result -> {
        testCtx.assertEquals(connCtx, Vertx.currentContext());
        async.complete();
      }));
    }));
  });
}
 
Example #11
Source File: RestVerticle.java    From raml-module-builder with Apache License 2.0 6 votes vote down vote up
/**
 * only one impl allowed
 * @param resultHandler
 * @throws Exception
 */
private void runShutdownHook(Handler<AsyncResult<Void>> resultHandler) throws Exception {
  try {
    ArrayList<Class<?>> aClass = InterfaceToImpl.convert2Impl(RTFConsts.PACKAGE_OF_IMPLEMENTATIONS, RTFConsts.PACKAGE_OF_HOOK_INTERFACES + ".ShutdownAPI", false);
    for (int i = 0; i < aClass.size(); i++) {
      Class<?>[] paramArray = new Class[] { Vertx.class, Context.class, Handler.class };
      Method method = aClass.get(i).getMethod("shutdown", paramArray);
      method.invoke(aClass.get(i).newInstance(), vertx, context, resultHandler);
      LogUtil.formatLogMessage(getClass().getName(), "runShutdownHook",
        "shutdown hook called with implemented class " + "named " + aClass.get(i).getName());
    }
  } catch (ClassNotFoundException e) {
    // no hook implemented, this is fine, just startup normally then
    LogUtil.formatLogMessage(getClass().getName(), "runShutdownHook", "no shutdown hook implementation found, continuing with shutdown");
    resultHandler.handle(io.vertx.core.Future.succeededFuture());
  }
}
 
Example #12
Source File: AtomixClusterManager.java    From atomix-vertx with Apache License 2.0 6 votes vote down vote up
@Override
public void getLockWithTimeout(String name, long timeout, Handler<AsyncResult<Lock>> handler) {
  Context context = vertx.getOrCreateContext();
  lockCache.getUnchecked(name).whenComplete((lock, error) -> {
    if (error == null) {
      lock.async().tryLock(Duration.ofMillis(timeout)).whenComplete((lockResult, lockError) -> {
        if (lockError == null) {
          if (lockResult.isPresent()) {
            context.runOnContext(v -> Future.<Lock>succeededFuture(new AtomixLock(vertx, lock)).setHandler(handler));
          } else {
            context.runOnContext(v -> Future.<Lock>failedFuture(new VertxException("Timed out waiting to get lock " + name)).setHandler(handler));
          }
        } else {
          context.runOnContext(v -> Future.<Lock>failedFuture(lockError).setHandler(handler));
        }
      });
    } else {
      context.runOnContext(v -> Future.<Lock>failedFuture(error).setHandler(handler));
    }
  });
}
 
Example #13
Source File: RunTestOnContext.java    From vertx-unit with Apache License 2.0 6 votes vote down vote up
@Override
public Statement apply(Statement base, Description description) {
  return new Statement() {
    @Override
    public void evaluate() throws Throwable {
      vertx = createVertx.get();
      try {
        Context context = vertx != null ? vertx.getOrCreateContext() : null;
        VertxUnitRunner.pushContext(context);
        base.evaluate();
      } finally {
        VertxUnitRunner.popContext();
        CountDownLatch latch = new CountDownLatch(1);
        closeVertx.accept(vertx, latch);
        try {
          if (!latch.await(30 * 1000, TimeUnit.MILLISECONDS)) {
            Logger logger = LoggerFactory.getLogger(description.getTestClass());
            logger.warn("Could not close Vert.x in tme");
          }
        } catch (InterruptedException e) {
          Thread.currentThread().interrupt();
        }
      }
    }
  };
}
 
Example #14
Source File: VertxCompletableFuture.java    From vertx-completable-future with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a new CompletableFuture that is asynchronously completed by a action running in the worker thread pool of
 * Vert.x
 * <p>
 * This method is different from {@link CompletableFuture#runAsync(Runnable)} as it does not use a fork join
 * executor, but the worker thread pool.
 *
 * @param context  the Vert.x context
 * @param runnable the action, when its execution completes, it completes the returned CompletableFuture. If the
 *                 execution throws an exception, the returned CompletableFuture is completed exceptionally.
 * @return the new CompletableFuture
 */
public static VertxCompletableFuture<Void> runBlockingAsync(Context context, Runnable runnable) {
  Objects.requireNonNull(runnable);
  VertxCompletableFuture<Void> future = new VertxCompletableFuture<>(Objects.requireNonNull(context));
  context.<Void>executeBlocking(
      fut -> {
        try {
          runnable.run();
          fut.complete(null);
        } catch (Throwable e) {
          fut.fail(e);
        }
      },
      false,
      ar -> {
        if (ar.failed()) {
          future.completeExceptionally(ar.cause());
        } else {
          future.complete(ar.result());
        }
      }
  );
  return future;
}
 
Example #15
Source File: TestPumpFromPart.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
private void run(Context context, boolean closeOutput) throws Throwable {
  inputStream.reset();
  part = new InputStreamPart("name", inputStream);

  outputStream = new BufferOutputStream() {
    @Override
    public void close() {
      super.close();
      outputStreamClosed = true;
    }
  };

  new PumpFromPart(context, part).toOutputStream(outputStream, closeOutput).get();
}
 
Example #16
Source File: RedisClusterTest.java    From vertx-redis-client with Apache License 2.0 5 votes vote down vote up
@Test
public void testContextReturn(TestContext should) {
  final Async test = should.async();
  Context context = rule.vertx().getOrCreateContext();
  client.connect(onCreate -> {
    should.assertEquals(context, rule.vertx().getOrCreateContext());
    test.complete();
  });
}
 
Example #17
Source File: AdminAPI.java    From raml-module-builder with Apache License 2.0 5 votes vote down vote up
@Validate
@Override
public void postAdminSetAESKey(String key, Map<String, String> okapiHeaders,
    Handler<AsyncResult<Response>> asyncResultHandler, Context vertxContext) {

  AES.setSecretKey(key);
  asyncResultHandler.handle(io.vertx.core.Future.succeededFuture(PostAdminSetAESKeyResponse.respond204()));
}
 
Example #18
Source File: HystrixTest.java    From vertx-circuit-breaker with Apache License 2.0 5 votes vote down vote up
@Test
public void testObservable() throws Exception {
  AtomicReference<String> result = new AtomicReference<>();

  vertx.runOnContext(v -> {
    Context context = vertx.getOrCreateContext();
    HttpClientCommand command = new HttpClientCommand(client, "/");
    command.observe().subscribe(s -> {
      context.runOnContext(v2 -> checkSetter(result, s));
    });
  });

  await().until(() -> result.get() != null);
  assertThat(result.get()).isEqualToIgnoringCase("hello");
}
 
Example #19
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 #20
Source File: AbstractVertxBasedCoapAdapterTest.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Creates a protocol adapter for a given HTTP server.
 *
 * @param server The coap server.
 * @param complete {@code true}, if that adapter should be created with all Hono service clients set, {@code false}, if the
 *            adapter should be created, and all Hono service clients set, but the credentials client is not set.
 * @param onStartupSuccess The handler to invoke on successful startup.
 *
 * @return The adapter.
 */
private AbstractVertxBasedCoapAdapter<CoapAdapterProperties> getAdapter(
        final CoapServer server,
        final boolean complete,
        final Handler<Void> onStartupSuccess) {

    final AbstractVertxBasedCoapAdapter<CoapAdapterProperties> adapter = new AbstractVertxBasedCoapAdapter<>() {

        @Override
        protected String getTypeName() {
            return ADAPTER_TYPE;
        }

        @Override
        protected void onStartupSuccess() {
            if (onStartupSuccess != null) {
                onStartupSuccess.handle(null);
            }
        }
    };

    adapter.setConfig(config);
    adapter.setCoapServer(server);
    adapter.setTenantClientFactory(tenantClientFactory);
    adapter.setDownstreamSenderFactory(downstreamSenderFactory);
    adapter.setRegistrationClientFactory(registrationClientFactory);
    if (complete) {
        adapter.setCredentialsClientFactory(credentialsClientFactory);
    }
    adapter.setCommandConsumerFactory(commandConsumerFactory);
    adapter.setDeviceConnectionClientFactory(deviceConnectionClientFactory);
    adapter.setCommandTargetMapper(commandTargetMapper);
    adapter.setMetrics(metrics);
    adapter.setResourceLimitChecks(resourceLimitChecks);
    adapter.init(vertx, mock(Context.class));

    return adapter;
}
 
Example #21
Source File: TestHighwayVerticle.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@Test
public void testHighwayVerticle(@Mocked Transport transport, @Mocked Vertx vertx, @Mocked Context context,
    @Mocked JsonObject json) {
  HighwayServerVerticle highwayVerticle = new HighwayServerVerticle();
  URIEndpointObject endpiontObject = new URIEndpointObject("highway://127.0.0.1:9090");
  new Expectations() {
    {
      transport.parseAddress(anyString);
      result = endpiontObject;
    }
  };

  Endpoint endpoint = new Endpoint(transport, "highway://127.0.0.1:9090");

  new Expectations() {
    {
      context.config();
      result = json;
      json.getValue(anyString);
      result = endpoint;
    }
  };

  highwayVerticle.init(vertx, context);
  @SuppressWarnings("unchecked")
  Future<Void> startFuture = Mockito.mock(Future.class);
  highwayVerticle.startListen(startFuture);
  MockUtil.getInstance().mockHighwayConfig();
  try {
    highwayVerticle.startListen(startFuture);
    assertTrue(true);
  } catch (Exception e) {
    Assert.fail();
  }
}
 
Example #22
Source File: BlockFile.java    From sfs with Apache License 2.0 5 votes vote down vote up
protected AsyncFileWriter createWriteStream(Context context, long startPosition) {
    checkAligned(startPosition, blockSize);
    AsyncFileWriter writer =
            new AsyncFileWriterImpl(
                    startPosition,
                    writeQueueSupport,
                    context,
                    channel,
                    LOGGER);
    return writer;
}
 
Example #23
Source File: TestPumpFromPart.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
public void do_pump_succ(Context context) throws Throwable {
  run(context, true);

  Assert.assertEquals(src, outputStream.getBuffer().toString());
  Assert.assertTrue(inputStreamClosed);
  Assert.assertTrue(outputStreamClosed);
}
 
Example #24
Source File: AbstractTcpClientPoolFactory.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@Override
public CLIENT_POOL createClientPool(Context context) {
  Vertx vertx = context.owner();

  NetClientWrapper netClientWrapper = new NetClientWrapper(vertx, normalClientConfig, sslClientConfig);
  return doCreateClientPool(context, netClientWrapper);
}
 
Example #25
Source File: UseEventLoopTest.java    From vertx-unit with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void testWitVertx() {
  Vertx vertx = Vertx.vertx();
  List<Context> contexts = Collections.synchronizedList(new ArrayList<>());
  TestSuiteImpl suite = (TestSuiteImpl) TestSuite.create("my_suite").test("my_test", context -> {
    contexts.add(Vertx.currentContext());
  });
  TestReporter reporter = new TestReporter();
  suite.runner().setReporter(reporter).setUseEventLoop(true).setVertx(vertx).run();
  reporter.await();
  assertEquals(0, reporter.exceptions.size());
  assertEquals(1, reporter.results.size());
  assertTrue(reporter.results.get(0).succeeded());
  assertEquals(1, contexts.size());
  assertNotNull(contexts.get(0));
  reporter = new TestReporter();
  suite.runner().setReporter(reporter).setUseEventLoop(false).setVertx(vertx).run();
  reporter.await();
  assertEquals(0, reporter.exceptions.size());
  assertEquals(1, reporter.results.size());
  assertTrue(reporter.results.get(0).succeeded());
  assertEquals(2, contexts.size());
  assertNull(contexts.get(1));
  reporter = new TestReporter();
  suite.runner().setReporter(reporter).setUseEventLoop(null).setVertx(vertx).run();
  reporter.await();
  assertEquals(0, reporter.exceptions.size());
  assertEquals(1, reporter.results.size());
  assertTrue(reporter.results.get(0).succeeded());
  assertEquals(3, contexts.size());
  assertNotNull(contexts.get(2));
  vertx.close();
}
 
Example #26
Source File: AdminAPI.java    From raml-module-builder with Apache License 2.0 5 votes vote down vote up
@Validate
@Override
public void postAdminImportSQL(InputStream entity, Map<String, String> okapiHeaders,
    Handler<AsyncResult<Response>> asyncResultHandler, Context vertxContext) {

  //TODO BUG, if database is down, this wont get caught and will return an OK
  //THE sql file must be tenant specific, meaning, to insert into a table the file should
  //have any table name prefixed with the schema - schema.table_name

  try {
    String tenantId = TenantTool.tenantId(okapiHeaders);
    String sqlFile = IOUtils.toString(entity, "UTF8");
    PostgresClient.getInstance(vertxContext.owner(), tenantId).runSQLFile(sqlFile, false, reply -> {
      if (! reply.succeeded()) {
        log.error(reply.cause().getMessage(), reply.cause());
        asyncResultHandler.handle(Future.failedFuture(reply.cause().getMessage()));
        return;
      }
      if (! reply.result().isEmpty()) {
        // some statements failed, transaction aborted
        String msg = "postAdminImportSQL failed:\n  " + String.join("\n  ", reply.result());
        log.error(msg);
        asyncResultHandler.handle(io.vertx.core.Future.succeededFuture(
          PostAdminImportSQLResponse.respond400WithTextPlain(msg)));
        return;
      }
      asyncResultHandler.handle(io.vertx.core.Future.succeededFuture(PostAdminImportSQLResponse.respond200(null)));
    });
  } catch (Exception e) {
    log.error(e.getMessage(), e);
    asyncResultHandler.handle(io.vertx.core.Future.failedFuture(e.getMessage()));
  }
}
 
Example #27
Source File: ConsumerTestBase.java    From vertx-kafka-client with Apache License 2.0 5 votes vote down vote up
@Test
public void testSubscription(TestContext ctx) throws Exception {
  String topicName = "testSubscription";
  String consumerId = topicName;
  kafkaCluster.createTopic(topicName, 1, 1);
  Properties config = kafkaCluster.useTo().getConsumerProperties(consumerId, consumerId, OffsetResetStrategy.EARLIEST);
  config.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
  config.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
  Context context = vertx.getOrCreateContext();
  consumer = createConsumer(context, config);

  Async done = ctx.async();

  consumer.handler(record -> {
    // no need for handling incoming records in this test
  });

  consumer.subscribe(Collections.singleton(topicName), asyncResult -> {

    if (asyncResult.succeeded()) {

      consumer.subscription(asyncResult1 -> {

        if (asyncResult1.succeeded()) {

          ctx.assertTrue(asyncResult1.result().contains(topicName));
          done.complete();

        } else {
          ctx.fail();
        }
      });

    } else {
      ctx.fail();
    }

  });
}
 
Example #28
Source File: VertxCompletableFuture.java    From vertx-completable-future 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 #29
Source File: VertxCompletableFutureTest.java    From vertx-completable-future with Apache License 2.0 5 votes vote down vote up
@Test
public void testHandleAsync(TestContext tc) {
  Async async1 = tc.async();
  Async async2 = tc.async();

  VertxCompletableFuture<Integer> failure = new VertxCompletableFuture<>(vertx);
  VertxCompletableFuture<Integer> success = new VertxCompletableFuture<>(vertx);

  vertx.runOnContext(v -> {
    String thread = Thread.currentThread().getName();
    Context context = Vertx.currentContext();

    failure.withContext(context).handleAsync((r, t) -> {
      tc.assertEquals(thread, Thread.currentThread().getName());
      if (t != null) {
        return 43;
      }
      return r;
    }).thenAccept(i -> {
      tc.assertEquals(i, 43);
      async1.complete();
    });

    success.withContext(context).handleAsync((r, t) -> {
      tc.assertEquals(Thread.currentThread().getName(), thread);
      if (t != null) {
        return 43;
      }
      return r;
    }).thenAccept(i -> {
      tc.assertEquals(i, 42);
      async2.complete();
    });
  });
  success.complete(42);
  failure.completeExceptionally(new RuntimeException("my bad"));

}
 
Example #30
Source File: KafkaProducerImpl.java    From vertx-kafka-client with Apache License 2.0 5 votes vote down vote up
public KafkaProducerImpl<K, V> registerCloseHook() {
  Context context = Vertx.currentContext();
  if (context == null) {
    return this;
  }
  closeHandler.registerCloseHook((ContextInternal) context);
  return this;
}