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

The following examples show how to use io.vertx.core.Vertx#currentContext() . 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: MicroserviceManager.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
public CompletableFuture<MicroserviceVersions> getOrCreateMicroserviceVersionsAsync(String microserviceName) {
  MicroserviceVersions microserviceVersions = versionsByName.get(microserviceName);
  if (microserviceVersions == null) {
    if (Vertx.currentContext() == null) {
      // not in event-loop, execute in current thread
      return CompletableFuture.completedFuture(getOrCreateMicroserviceVersions(microserviceName));
    } else {
      // execute in an single thread pool to make sure make less requests to service center
      return CompletableFuture.supplyAsync(() -> getOrCreateMicroserviceVersions(microserviceName),
          SinglePoolBlockingExecutor.create());
    }
  } else {
    // here do not need switch to another thread, can improve performance
    tryRemoveInvalidMicroservice(microserviceVersions);
    return CompletableFuture.completedFuture(microserviceVersions);
  }
}
 
Example 2
Source File: TestClientPoolManager.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
@Test
public void findByContext_otherVertx(@Mocked VertxImpl otherVertx, @Mocked Context otherContext) {
  HttpClientWithContext pool = new HttpClientWithContext(null, null);
  pools.add(pool);

  new Expectations() {
    {
      Vertx.currentContext();
      result = otherContext;
      otherContext.owner();
      result = otherVertx;
    }
  };

  Assert.assertSame(pool, poolMgr.findByContext());
}
 
Example 3
Source File: TestClientPoolManager.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
@Test
public void findByContext_wrongContext_reverse() {
  HttpClientWithContext pool1 = new HttpClientWithContext(null, null);
  HttpClientWithContext pool2 = new HttpClientWithContext(null, null);
  pools.add(pool1);
  pools.add(pool2);

  new Expectations() {
    {
      Vertx.currentContext();
      result = null;
    }
  };

  AtomicInteger reactiveNextIndex = Deencapsulation.getField(poolMgr, "reactiveNextIndex");
  reactiveNextIndex.set(Integer.MAX_VALUE);
  // each time invoke find, reactiveNextIndex will inc 1
  Assert.assertSame(pool2, poolMgr.findByContext());
  Assert.assertSame(pool1, poolMgr.findByContext());
  Assert.assertSame(pool2, poolMgr.findByContext());
  Assert.assertSame(pool1, poolMgr.findByContext());
}
 
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: TestSuiteReportImpl.java    From vertx-unit with Apache License 2.0 5 votes vote down vote up
public void run(Boolean useEventLoop) {
  Context context = null;
  if (useEventLoop == null) {
    context = Vertx.currentContext();
  } else if (useEventLoop) {
    context = Vertx.currentContext();
    if (context == null) {
      throw new IllegalStateException("No event loop, your test should either provide a Vertx instance or " +
          "be executed in a Verticle");
    }
  }
  new ExecutionContext(context).run(buildTask());
}
 
Example 6
Source File: VertxHttpTransportContext.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
public VertxHttpTransportContext(RoutingContext routingContext, HttpServletRequestEx requestEx,
    HttpServletResponseEx responseEx, ProduceProcessor produceProcessor) {
  super(requestEx, responseEx, produceProcessor);

  this.routingContext = routingContext;
  this.vertxContext = Vertx.currentContext();
}
 
Example 7
Source File: DB2Pool.java    From vertx-sql-client with Apache License 2.0 5 votes vote down vote up
/**
 * Create a connection pool to the DB2 server configured with the given
 * {@code connectOptions} and {@code poolOptions}.
 *
 * @param connectOptions the options for the connection
 * @param poolOptions    the options for creating the pool
 * @return the connection pool
 */
static DB2Pool pool(DB2ConnectOptions connectOptions, PoolOptions poolOptions) {
  if (Vertx.currentContext() != null) {
    throw new IllegalStateException(
        "Running in a Vertx context => use DB2Pool#pool(Vertx, DB2ConnectOptions, PoolOptions) instead");
  }
  VertxOptions vertxOptions = new VertxOptions();
  Vertx vertx = Vertx.vertx(vertxOptions);
  return DB2PoolImpl.create((ContextInternal) vertx.getOrCreateContext(), true, connectOptions, poolOptions);
}
 
Example 8
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;
}
 
Example 9
Source File: VertxContextPRNG.java    From vertx-auth with Apache License 2.0 5 votes vote down vote up
/**
 * Get or create a secure non blocking random number generator using the current vert.x instance. Since the context
 * might be different this method will attempt to use the current context first if available and then fall back to
 * create a new instance of the PRNG.
 *
 * @param vertx a Vert.x instance.
 * @return A secure non blocking random number generator.
 */
static VertxContextPRNG current(final Vertx vertx) {
  final Context currentContext = Vertx.currentContext();
  if (currentContext != null) {
    return current(currentContext);
  }

  // we are not running on a vert.x context, fallback to create a new instance
  return new PRNG(vertx);
}
 
Example 10
Source File: SubsOpSerializer.java    From vertx-infinispan with Apache License 2.0 5 votes vote down vote up
public void execute(BiFunction<String, RegistrationInfo, CompletableFuture<Void>> op, String address, RegistrationInfo registrationInfo, Promise<Void> promise) {
  if (Vertx.currentContext() != context) {
    context.runOnContext(v -> execute(op, address, registrationInfo, promise));
    return;
  }
  tasks.add(new Task(op, address, registrationInfo, promise));
  if (tasks.size() == 1) {
    processTask(tasks.peek());
  }
}
 
Example 11
Source File: VertxServerResponseToHttpServletResponse.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@Override
public void flushBuffer() {
  if (context == Vertx.currentContext()) {
    internalFlushBuffer();
    return;
  }

  context.runOnContext(V -> internalFlushBuffer());
}
 
Example 12
Source File: VertxUtils.java    From raml-module-builder with Apache License 2.0 5 votes vote down vote up
/**
 * Return the Vertx of the current context; if there isn't a current context
 * create and return a new Vertx using getVertxWithExceptionHandler().
 * @return the Vertx
 */
public static Vertx getVertxFromContextOrNew() {
  Context context = Vertx.currentContext();

  if (context == null) {
    return getVertxWithExceptionHandler();
  }

  return context.owner();
}
 
Example 13
Source File: Wrappers.java    From quarkus with Apache License 2.0 5 votes vote down vote up
static <T> Uni<List<T>> toUniOfList(Publisher<T> publisher) {
    Context context = Vertx.currentContext();
    Uni<List<T>> uni = Multi.createFrom().publisher(publisher)
            .collectItems().asList();

    if (context != null) {
        return uni.emitOn(command -> context.runOnContext(x -> command.run()));
    }
    return uni;
}
 
Example 14
Source File: Wrappers.java    From quarkus with Apache License 2.0 5 votes vote down vote up
static <T> Multi<T> toMulti(Publisher<T> publisher) {
    Context context = Vertx.currentContext();
    if (context != null) {
        return Multi.createFrom().publisher(publisher).emitOn(command -> context.runOnContext(x -> command.run()));
    } else {
        return Multi.createFrom().publisher(publisher);
    }
}
 
Example 15
Source File: RedisConfigStore.java    From vertx-config with Apache License 2.0 5 votes vote down vote up
@Override
public void close(Handler<Void> completionHandler) {
  if (Vertx.currentContext() == ctx) {
    if (!closed) {
      closed = true;
      redis.close();
    }
    completionHandler.handle(null);
  } else {
    ctx.runOnContext(v -> close(completionHandler));
  }
}
 
Example 16
Source File: AmqpAdapterSaslAuthenticatorFactory.java    From hono with Eclipse Public License 2.0 4 votes vote down vote up
@Override
public void process(final Handler<Boolean> completionHandler) {
    final String[] remoteMechanisms = sasl.getRemoteMechanisms();
    if (remoteMechanisms.length == 0) {
        LOG.trace("client device provided an empty list of SASL mechanisms [hostname: {}, state: {}]",
                sasl.getHostname(), sasl.getState());
        completionHandler.handle(Boolean.FALSE);
        return;
    }

    final String remoteMechanism = remoteMechanisms[0];
    LOG.debug("client device wants to authenticate using SASL [mechanism: {}, host: {}, state: {}]",
            remoteMechanism, sasl.getHostname(), sasl.getState());

    final Context currentContext = Vertx.currentContext();

    final byte[] saslResponse = new byte[sasl.pending()];
    sasl.recv(saslResponse, 0, saslResponse.length);

    buildSaslResponseContext(remoteMechanism, saslResponse)
            .compose(saslResponseContext -> invokePreAuthenticationHandler(saslResponseContext, currentSpan))
            .compose(saslResponseContext -> verify(saslResponseContext))
            .onComplete(outcome -> {
                if (outcome.succeeded()) {
                    currentSpan.log("credentials verified successfully");
                    // add span to connection so that it can be used during the
                    // remaining connection establishment process
                    protonConnection.attachments().set(AmqpAdapterConstants.KEY_CURRENT_SPAN, Span.class,
                            currentSpan);
                    final Device authenticatedDevice = outcome.result();
                    protonConnection.attachments().set(AmqpAdapterConstants.KEY_CLIENT_DEVICE, Device.class,
                            authenticatedDevice);
                    succeeded = true;
                    sasl.done(SaslOutcome.PN_SASL_OK);

                } else {
                    TracingHelper.logError(currentSpan, outcome.cause());
                    currentSpan.finish();
                    LOG.debug("SASL handshake failed: {}", outcome.cause().getMessage());
                    sasl.done(SaslOutcome.PN_SASL_AUTH);
                }

                if (currentContext == null) {
                    completionHandler.handle(Boolean.TRUE);
                } else {
                    // invoke the completion handler on the calling context.
                    currentContext.runOnContext(action -> completionHandler.handle(Boolean.TRUE));
                }
            });
}
 
Example 17
Source File: TestSuiteUseVertxEventLoopTest.java    From vertx-unit with Apache License 2.0 4 votes vote down vote up
@Override
protected boolean checkTest(TestContext test) {
  return Vertx.currentContext() != null;
}
 
Example 18
Source File: HighwayTransportContext.java    From servicecomb-java-chassis with Apache License 2.0 4 votes vote down vote up
public HighwayTransportContext() {
  this.vertxContext = Vertx.currentContext();
}
 
Example 19
Source File: VertxCompletableFuture.java    From gravitee-management-rest-api with Apache License 2.0 2 votes vote down vote up
/**
 * Creates a new {@link VertxCompletableFuture} using the current {@link Context}. This method
 * <strong>must</strong> be used from a Vert.x thread, or fails.
 */
public VertxCompletableFuture() {
    this(Vertx.currentContext());
}
 
Example 20
Source File: VertxCompletableFuture.java    From gravitee-management-rest-api with Apache License 2.0 2 votes vote down vote up
/**
 * Creates a new {@link VertxCompletableFuture} using the current {@link Context}. This method
 * <strong>must</strong> be used from a Vert.x thread, or fails.
 */
public VertxCompletableFuture() {
    this(Vertx.currentContext());
}