io.vertx.core.impl.VertxInternal Java Examples

The following examples show how to use io.vertx.core.impl.VertxInternal. 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: TestHttpClientPoolFactory.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
@Test
public void createClientPool(@Mocked VertxInternal vertx, @Mocked ContextInternal context,
    @Mocked HttpClient httpClient) {
  new Expectations(VertxImpl.class) {
    {
      context.owner();
      result = vertx;
      vertx.createHttpClient(httpClientOptions);
      result = httpClient;
    }
  };
  HttpClientWithContext pool = factory.createClientPool(context);

  Assert.assertSame(context, pool.context());
  Assert.assertSame(httpClient, pool.getHttpClient());
}
 
Example #2
Source File: MetricsTest.java    From vertx-dropwizard-metrics with Apache License 2.0 6 votes vote down vote up
@Test
public void testClientMetricsReporting() {
  SocketAddress address = SocketAddress.inetSocketAddress(8080, "localhost");
  ClientMetrics metrics = ((VertxInternal) vertx).metricsSPI().createClientMetrics(address, "backend", null);

  // Queue
  Object queueMetric = metrics.enqueueRequest();
  JsonObject snapshot = metricsService.getMetricsSnapshot("vertx.backend.clients.localhost:8080");
  assertEquals(1, (int)snapshot.getJsonObject("vertx.backend.clients.localhost:8080.queue-size").getInteger("count"));
  metrics.dequeueRequest(queueMetric);
  snapshot = metricsService.getMetricsSnapshot("vertx.backend.clients.localhost:8080");
  assertEquals(0, (int)snapshot.getJsonObject("vertx.backend.clients.localhost:8080.queue-size").getInteger("count"));
  assertEquals(1, (int)snapshot.getJsonObject("vertx.backend.clients.localhost:8080.queue-delay").getInteger("count"));

  // Request
  Object request = new Object();
  Object response = new Object();
  Object requestMetric = metrics.requestBegin("some-uri", request);
  metrics.requestEnd(requestMetric);
  metrics.responseBegin(requestMetric, response);
  snapshot = metricsService.getMetricsSnapshot("vertx.backend.clients.localhost:8080");
  assertEquals(0, (int)snapshot.getJsonObject("vertx.backend.clients.localhost:8080.requests").getInteger("count"));
  metrics.responseEnd(requestMetric, response);
  snapshot = metricsService.getMetricsSnapshot("vertx.backend.clients.localhost:8080");
  assertEquals(1, (int)snapshot.getJsonObject("vertx.backend.clients.localhost:8080.requests").getInteger("count"));
}
 
Example #3
Source File: PgConnectionFactory.java    From vertx-sql-client with Apache License 2.0 6 votes vote down vote up
PgConnectionFactory(VertxInternal vertx, ContextInternal context, PgConnectOptions options) {

    NetClientOptions netClientOptions = new NetClientOptions(options);

    // Make sure ssl=false as we will use STARTLS
    netClientOptions.setSsl(false);

    this.context = context;
    this.sslMode = options.getSslMode();
    this.socketAddress = options.getSocketAddress();
    this.hostnameVerificationAlgorithm = netClientOptions.getHostnameVerificationAlgorithm();
    this.trustOptions = netClientOptions.getTrustOptions();
    this.database = options.getDatabase();
    this.username = options.getUser();
    this.password = options.getPassword();
    this.properties = new HashMap<>(options.getProperties());
    this.cachePreparedStatements = options.getCachePreparedStatements();
    this.pipeliningLimit = options.getPipeliningLimit();
    this.preparedStatementCacheSize = options.getPreparedStatementCacheMaxSize();
    this.preparedStatementCacheSqlFilter = options.getPreparedStatementCacheSqlFilter();
    this.client = vertx.createNetClient(netClientOptions);
  }
 
Example #4
Source File: MetricsTest.java    From vertx-dropwizard-metrics with Apache License 2.0 6 votes vote down vote up
@Test
public void testClientMetricsLifecycle() {
  VertxMetrics spi = ((VertxInternal) vertx).metricsSPI();
  SocketAddress address = SocketAddress.inetSocketAddress(8080, "localhost");
  ClientMetrics[] metrics = new ClientMetrics[2];
  for (int i = 0;i < metrics.length;i++) {
    metrics[i] = spi.createClientMetrics(address, "backend", "acme");
  }
  JsonObject snapshot = metricsService.getMetricsSnapshot("vertx.backend.clients.acme.localhost:8080");
  assertTrue(snapshot.size() > 0);
  metrics[0].close();
  snapshot = metricsService.getMetricsSnapshot("vertx.backend.clients.acme.localhost:8080");
  assertTrue(snapshot.size() > 0);
  metrics[1].close();
  snapshot = metricsService.getMetricsSnapshot("vertx.backend.clients.acme.localhost:8080");
  assertTrue(snapshot.size() == 0);
}
 
Example #5
Source File: ConfigRetrieverImpl.java    From vertx-config with Apache License 2.0 5 votes vote down vote up
private String getDefaultConfigPath() {
  String value = System.getenv("VERTX_CONFIG_PATH");
  if (value == null  || value.trim().isEmpty()) {
    value = System.getProperty("vertx-config-path");
  }
  if (value != null  && ! value.trim().isEmpty()) {
    return value.trim();
  }
  File file = ((VertxInternal) vertx).resolveFile(DEFAULT_CONFIG_PATH);
  boolean exists = file != null && file.exists();
  if (exists) {
    return file.getAbsolutePath();
  }
  return null;
}
 
Example #6
Source File: Lifecycle.java    From vertx-infinispan with Apache License 2.0 5 votes vote down vote up
public static void closeClustered(List<Vertx> clustered) throws Exception {
  for (Vertx vertx : clustered) {
    VertxInternal vertxInternal = (VertxInternal) vertx;

    InfinispanClusterManager clusterManager = getInfinispanClusterManager(vertxInternal.getClusterManager());

    ComponentStatus status = null;
    if (clusterManager != null) {
      EmbeddedCacheManager cacheManager = (EmbeddedCacheManager) clusterManager.getCacheContainer();
      status = cacheManager.getStatus();

      Health health = cacheManager.getHealth();

      SECONDS.sleep(2); // Make sure rebalancing has been triggered

      long start = System.currentTimeMillis();
      try {
        while (health.getClusterHealth().getHealthStatus() != HealthStatus.HEALTHY
          && System.currentTimeMillis() - start < MILLISECONDS.convert(2, MINUTES)) {
          MILLISECONDS.sleep(100);
        }
      } catch (Exception ignore) {
      }
    }

    if (status == null || status.compareTo(STOPPING) >= 0) {
      vertxInternal.close();
    } else {
      CountDownLatch latch = new CountDownLatch(1);
      vertxInternal.close(ar -> {
        if (ar.failed()) {
          log.error("Failed to shutdown vert.x", ar.cause());
        }
        latch.countDown();
      });
      latch.await(2, TimeUnit.MINUTES);
    }
  }
}
 
Example #7
Source File: ClusterHealthCheckImpl.java    From vertx-infinispan with Apache License 2.0 5 votes vote down vote up
@Override
public void handle(Promise<Status> promise) {
  VertxInternal vertxInternal = (VertxInternal) vertx;
  InfinispanClusterManager clusterManager = (InfinispanClusterManager) vertxInternal.getClusterManager();
  EmbeddedCacheManager cacheManager = (EmbeddedCacheManager) clusterManager.getCacheContainer();
  Health health = cacheManager.getHealth();
  HealthStatus healthStatus = health.getClusterHealth().getHealthStatus();
  Status status = new Status().setOk(healthStatus == HealthStatus.HEALTHY);
  if (detailed) {
    status.setData(convert(health));
  }
  promise.complete(status);
}
 
Example #8
Source File: CassandraClientImpl.java    From vertx-cassandra-client with Apache License 2.0 5 votes vote down vote up
public CassandraClientImpl(Vertx vertx, String clientName, CassandraClientOptions options) {
  Objects.requireNonNull(vertx, "vertx");
  Objects.requireNonNull(clientName, "clientName");
  Objects.requireNonNull(options, "options");
  this.vertx = (VertxInternal) vertx;
  this.clientName = clientName;
  this.options = options;
  this.creatingContext = ((VertxInternal) vertx).getOrCreateContext();
  holders = vertx.sharedData().getLocalMap(HOLDERS_LOCAL_MAP_NAME);
  SessionHolder current = holders.compute(clientName, (k, h) -> h == null ? new SessionHolder() : h.increment());
  creatingContext.addCloseHook(this::close);
}
 
Example #9
Source File: LocalData.java    From vxms with Apache License 2.0 5 votes vote down vote up
/**
 * Get a local counter. The counter will be passed to the handler.
 *
 * @param name the name of the counter.
 * @param resultHandler the handler
 */
public void getCounter(String name, Handler<AsyncResult<Counter>> resultHandler) {
  Objects.requireNonNull(name, "name");
  Objects.requireNonNull(resultHandler, "resultHandler");
  Counter counter = this.localCounters
      .computeIfAbsent(name, (n) -> new AsynchronousCounter((VertxInternal) this.vertx));
  Context context = this.vertx.getOrCreateContext();
  context.runOnContext((v) -> resultHandler.handle(Future.succeededFuture(counter)));
}
 
Example #10
Source File: CommandRegistryImpl.java    From vertx-shell with Apache License 2.0 5 votes vote down vote up
public CommandRegistryImpl(VertxInternal vertx) {
  this.vertx = vertx;
  hook = completionHandler -> {
    try {
      doClose();
      registries.remove(vertx);
    } catch (Exception e) {
      completionHandler.handle(Future.failedFuture(e));
      return;
    }
    completionHandler.handle(Future.succeededFuture());
  };
  vertx.addCloseHook(hook);
}
 
Example #11
Source File: JDBCClientImpl.java    From vertx-jdbc-client with Apache License 2.0 5 votes vote down vote up
/**
 * Create client with specific datasource.
 */
public JDBCClientImpl(Vertx vertx, DataSource dataSource) {
  Objects.requireNonNull(vertx);
  Objects.requireNonNull(dataSource);
  this.vertx = (VertxInternal) vertx;
  datasourceName = UUID.randomUUID().toString();
  config = null;
  holders = vertx.sharedData().getLocalMap(DS_LOCAL_MAP_NAME);
  DataSourceHolder holder = new DataSourceHolder(dataSource, createExecutor(), createMetrics(datasourceName, -1));
  holders.put(datasourceName, holder);
  this.helper = new JDBCStatementHelper();
  setupCloseHook();
}
 
Example #12
Source File: JDBCClientImpl.java    From vertx-jdbc-client with Apache License 2.0 5 votes vote down vote up
/**
 * Create client with shared datasource.
 */
public JDBCClientImpl(Vertx vertx, JsonObject config, String datasourceName) {
  Objects.requireNonNull(vertx);
  Objects.requireNonNull(config);
  Objects.requireNonNull(datasourceName);
  this.vertx = (VertxInternal) vertx;
  this.datasourceName = datasourceName;
  this.config = config;
  holders = vertx.sharedData().getLocalMap(DS_LOCAL_MAP_NAME);
  DataSourceProvider provider = createProvider();
  holders.compute(datasourceName, (k, h) -> h == null ? new DataSourceHolder(provider) : h.increment());
  this.helper = new JDBCStatementHelper(config);
  setupCloseHook();
}
 
Example #13
Source File: MongoClientImpl.java    From vertx-mongo-client with Apache License 2.0 5 votes vote down vote up
public MongoClientImpl(Vertx vertx, JsonObject config, String dataSourceName) {
  Objects.requireNonNull(vertx);
  Objects.requireNonNull(config);
  Objects.requireNonNull(dataSourceName);
  this.vertx = (VertxInternal) vertx;
  this.creatingContext = this.vertx.getOrCreateContext();
  this.holder = lookupHolder(dataSourceName, config);
  this.mongo = holder.mongo(vertx);
  this.useObjectId = config.getBoolean("useObjectId", false);

  creatingContext.addCloseHook(this);
}
 
Example #14
Source File: MongoClientImpl.java    From vertx-mongo-client with Apache License 2.0 5 votes vote down vote up
public MongoClientImpl(Vertx vertx, JsonObject config, String dataSourceName, MongoClientSettings settings) {
  Objects.requireNonNull(vertx);
  Objects.requireNonNull(config);
  Objects.requireNonNull(dataSourceName);
  Objects.requireNonNull(settings);
  this.vertx = (VertxInternal) vertx;
  this.creatingContext = this.vertx.getOrCreateContext();
  this.holder = lookupHolder(dataSourceName, config);
  this.mongo = holder.mongo(vertx, settings);
  this.useObjectId = config.getBoolean("useObjectId", false);

  creatingContext.addCloseHook(this);
}
 
Example #15
Source File: MongoClientTest.java    From vertx-mongo-client with Apache License 2.0 5 votes vote down vote up
private void upsertDoc(String collection, JsonObject docToInsert, JsonObject insertStatement, String expectedId, Consumer<JsonObject> doneFunction) {
  mongoClient.updateCollectionWithOptions(collection,
    new JsonObject()
      .put("foo", docToInsert.getString("foo")),
    insertStatement,
    new UpdateOptions()
      .setUpsert(true),
    onSuccess(res -> {
      assertEquals(0, res.getDocModified());

      if (expectedId == null) {
        assertEquals(0, res.getDocMatched());
        assertNotNull(res.getDocUpsertedId());
      } else {
        assertEquals(1, res.getDocMatched());
        assertNull(res.getDocUpsertedId());
      }

      //need to check actual DB, not through the Vertx client, in order to make sure the id is a string
      Promise<Document> promise = ((VertxInternal) vertx).promise();
      db
        .getCollection(collection)
        .find()
        .first()
        .subscribe(new SingleResultSubscriber<>(promise));

      promise.future()
        .onFailure(Throwable::printStackTrace)
        .onSuccess(savedDoc -> {
          if (expectedId != null) {
            assertEquals(expectedId, savedDoc.getString(MongoClientUpdateResult.ID_FIELD));
          } else {
            assertEquals(res.getDocUpsertedId().getString(MongoClientUpdateResult.ID_FIELD), savedDoc.getString(MongoClientUpdateResult.ID_FIELD));
          }
          doneFunction.accept(new JsonObject(savedDoc.toJson()));
        });
    }));
}
 
Example #16
Source File: ClusterHealthCheck.java    From vertx-hazelcast with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a ready-to-use Vert.x cluster {@link io.vertx.ext.healthchecks.HealthChecks} procedure.
 *
 * @param vertx the instance of Vert.x, must not be {@code null}
 * @return a Vert.x cluster {@link io.vertx.ext.healthchecks.HealthChecks} procedure
 */
static Handler<Promise<Status>> createProcedure(Vertx vertx) {
  Objects.requireNonNull(vertx);
  return future -> {
    VertxInternal vertxInternal = (VertxInternal) vertx;
    HazelcastClusterManager clusterManager = (HazelcastClusterManager) vertxInternal.getClusterManager();
    PartitionService partitionService = clusterManager.getHazelcastInstance().getPartitionService();
    future.complete(new Status().setOk(partitionService.isClusterSafe()));
  };
}
 
Example #17
Source File: Lifecycle.java    From vertx-hazelcast with Apache License 2.0 5 votes vote down vote up
public static void closeClustered(List<Vertx> clustered) throws Exception {
  for (Vertx vertx : clustered) {
    VertxInternal vertxInternal = (VertxInternal) vertx;

    HazelcastClusterManager clusterManager = getHazelcastClusterManager(vertxInternal.getClusterManager());

    if (clusterManager != null) {
      HazelcastInstance hazelcastInstance = clusterManager.getHazelcastInstance();

      SECONDS.sleep(2); // Make sure rebalancing has been triggered

      long start = System.currentTimeMillis();
      try {
        while (!hazelcastInstance.getPartitionService().isClusterSafe()
          && System.currentTimeMillis() - start < MILLISECONDS.convert(2, MINUTES)) {
          MILLISECONDS.sleep(100);
        }
      } catch (Exception ignore) {
      }
    }

    CountDownLatch latch = new CountDownLatch(1);
    vertxInternal.close(ar -> {
      if (ar.failed()) {
        log.error("Failed to shutdown vert.x", ar.cause());
      }
      latch.countDown();
    });
    latch.await(2, TimeUnit.MINUTES);
  }
}
 
Example #18
Source File: AbstractRegistrar.java    From vertx-graphql-service-discovery with Apache License 2.0 5 votes vote down vote up
private static String getNodeId(Vertx vertx) {
    if (vertx.isClustered()) {
        return ((VertxInternal) vertx).getNodeID();
    } else {
        return "localhost";
    }
}
 
Example #19
Source File: MqttClientImpl.java    From vertx-mqtt with Apache License 2.0 5 votes vote down vote up
/**
 * Constructor
 *
 * @param vertx Vert.x instance
 * @param options MQTT client options
 */
public MqttClientImpl(Vertx vertx, MqttClientOptions options) {

  // copy given options
  NetClientOptions netClientOptions = new NetClientOptions(options);
  netClientOptions.setIdleTimeout(DEFAULT_IDLE_TIMEOUT);

  this.vertx = (VertxInternal) vertx;
  this.client = vertx.createNetClient(netClientOptions);
  this.options = options;
}
 
Example #20
Source File: DelegatingAuthenticationService.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Registers a check which succeeds if the configured <em>Authentication</em> service host name
 * can be resolved via DNS.
 * <p>
 * If no DNS resolver is available, then no check will be registered.
 *
 * @param readinessHandler The health check handler to register the checks with.
 */
@Override
public void registerReadinessChecks(final HealthCheckHandler readinessHandler) {

    if (dnsClient != null) {
        log.info("registering readiness check using DNS Client");
        readinessHandler.register("authentication-service-availability", status -> {
            log.trace("checking availability of Authentication service");
            dnsClient.lookup(getConfig().getHost(), lookupAttempt -> {
                if (lookupAttempt.succeeded()) {
                    status.tryComplete(Status.OK());
                } else {
                    log.debug("readiness check failed to resolve Authentication service address [{}]: {}",
                            getConfig().getHost(), lookupAttempt.cause().getMessage());
                    status.tryComplete(Status.KO());
                }
            });
        });
    } else if (VertxInternal.class.isInstance(vertx)) {
        log.info("registering readiness check using vert.x Address Resolver");
        readinessHandler.register("authentication-service-availability", status -> {
            log.trace("checking availability of Authentication service");
            ((VertxInternal) vertx).resolveAddress(getConfig().getHost(), lookupAttempt -> {
                if (lookupAttempt.succeeded()) {
                    status.tryComplete(Status.OK());
                } else {
                    log.debug("readiness check failed to resolve Authentication service address [{}]: {}",
                            getConfig().getHost(), lookupAttempt.cause().getMessage());
                    status.tryComplete(Status.KO());
                }
            });
        });
    } else {
        log.warn("cannot register readiness check, no DNS resolver available");
    }
}
 
Example #21
Source File: DiscoveryImpl.java    From vertx-service-discovery with Apache License 2.0 5 votes vote down vote up
private String getNodeId(Vertx vertx) {
  if (vertx.isClustered()) {
    return ((VertxInternal) vertx).getClusterManager().getNodeId();
  } else {
    return "localhost";
  }
}
 
Example #22
Source File: CircuitBreakerMetrics.java    From vertx-circuit-breaker with Apache License 2.0 5 votes vote down vote up
CircuitBreakerMetrics(Vertx vertx, CircuitBreakerImpl circuitBreaker, CircuitBreakerOptions options) {
  this.circuitBreaker = circuitBreaker;
  this.circuitBreakerTimeout = circuitBreaker.options().getTimeout();
  this.circuitBreakerResetTimeout = circuitBreaker.options().getResetTimeout();
  this.node = vertx.isClustered() ? ((VertxInternal) vertx).getClusterManager().getNodeId() : "local";
  this.rollingWindow = new RollingWindow(options.getMetricsRollingWindow(), options.getMetricsRollingBuckets());
}
 
Example #23
Source File: PgPool.java    From vertx-sql-client with Apache License 2.0 5 votes vote down vote up
/**
 * Create a connection pool to the database configured with the given {@code connectOptions} and {@code poolOptions}.
 *
 * @param poolOptions the options for creating the pool
 * @return the connection pool
 */
static PgPool pool(PgConnectOptions connectOptions, PoolOptions poolOptions) {
  if (Vertx.currentContext() != null) {
    throw new IllegalStateException("Running in a Vertx context => use PgPool#pool(Vertx, PgConnectOptions, PoolOptions) instead");
  }
  VertxOptions vertxOptions = new VertxOptions();
  if (connectOptions.isUsingDomainSocket()) {
    vertxOptions.setPreferNativeTransport(true);
  }
  VertxInternal vertx = (VertxInternal) Vertx.vertx(vertxOptions);
  return PgPoolImpl.create(vertx.getOrCreateContext(), true, connectOptions, poolOptions);
}
 
Example #24
Source File: PgPool.java    From vertx-sql-client with Apache License 2.0 4 votes vote down vote up
/**
 * Like {@link #pool(PgConnectOptions, PoolOptions)} with a specific {@link Vertx} instance.
 */
static PgPool pool(Vertx vertx, PgConnectOptions connectOptions, PoolOptions poolOptions) {
  return PgPoolImpl.create(((VertxInternal)vertx).getOrCreateContext(), false, connectOptions, poolOptions);
}
 
Example #25
Source File: CassandraClientTestBase.java    From vertx-cassandra-client with Apache License 2.0 4 votes vote down vote up
@Before
public void setUp() {
  vertx = (VertxInternal) Vertx.vertx();
  client = CassandraClient.create(vertx, createClientOptions());
}
 
Example #26
Source File: HazelcastClusterManager.java    From vertx-hazelcast with Apache License 2.0 4 votes vote down vote up
@Override
public void init(Vertx vertx, NodeSelector nodeSelector) {
  this.vertx = (VertxInternal) vertx;
  this.nodeSelector = nodeSelector;
}
 
Example #27
Source File: HazelcastAsyncMap.java    From vertx-hazelcast with Apache License 2.0 4 votes vote down vote up
public HazelcastAsyncMap(VertxInternal vertx, IMap<K, V> map) {
  this.vertx = vertx;
  this.map = map;
}
 
Example #28
Source File: SubsOpSerializer.java    From vertx-hazelcast with Apache License 2.0 4 votes vote down vote up
private SubsOpSerializer(VertxInternal vertx) {
  this.vertx = vertx;
  taskQueue = new TaskQueue();
}
 
Example #29
Source File: HazelcastCounter.java    From vertx-hazelcast with Apache License 2.0 4 votes vote down vote up
public HazelcastCounter(VertxInternal vertx, IAtomicLong atomicLong) {
  this.vertx = vertx;
  this.atomicLong = atomicLong;
}
 
Example #30
Source File: SubsMapHelper.java    From vertx-hazelcast with Apache License 2.0 4 votes vote down vote up
public SubsMapHelper(VertxInternal vertx, HazelcastInstance hazelcast, NodeSelector nodeSelector) {
  this.vertx = vertx;
  map = hazelcast.getMultiMap("__vertx.subs");
  this.nodeSelector = nodeSelector;
  listenerId = map.addEntryListener(this, false);
}