Java Code Examples for io.vertx.core.Vertx

The following examples show how to use io.vertx.core.Vertx. These examples are extracted from open source projects. 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 Project: incubator-tuweni   Source File: PatchworkIntegrationTest.java    License: Apache License 2.0 6 votes vote down vote up
private RPCHandler makeRPCHandler(Vertx vertx) throws Exception {
  Signature.KeyPair keyPair = getLocalKeys();
  String networkKeyBase64 = "1KHLiKZvAvjbY1ziZEHMXawbCEIM6qwjCDm3VYRan/s=";
  Bytes32 networkKeyBytes32 = Bytes32.wrap(Base64.decode(networkKeyBase64));

  String host = "localhost";
  int port = 8008;

  SecureScuttlebuttVertxClient secureScuttlebuttVertxClient =
      new SecureScuttlebuttVertxClient(vertx, keyPair, networkKeyBytes32);

  AsyncResult<RPCHandler> onConnect =
      secureScuttlebuttVertxClient.connectTo(port, host, keyPair.publicKey(), (sender, terminationFn) -> {

        return new RPCHandler(vertx, sender, terminationFn, new ObjectMapper());
      });

  return onConnect.get();
}
 
Example 2
Source Project: vertx-swagger   Source File: PetStoreTest.java    License: Apache License 2.0 6 votes vote down vote up
@BeforeClass
public static void beforeClass(TestContext context) {
    Async before = context.async();
    
    vertx = Vertx.vertx();
    dog = new Pet(1L, new Category(1L, "dog"), "rex", new ArrayList<>(), new ArrayList<>(), StatusEnum.AVAILABLE);
    orderDog = new Order(1L, 1L, 3, OffsetDateTime.of(2017,4,2,11,8,10,0,ZoneOffset.UTC), io.swagger.server.api.model.Order.StatusEnum.APPROVED, Boolean.TRUE);

    // init Main
    vertx.deployVerticle("io.swagger.server.api.MainApiVerticle", res -> {
        if (res.succeeded()) {
            before.complete();
        } else {
            context.fail(res.cause());
        }
    });

    httpClient = Vertx.vertx().createHttpClient();

}
 
Example 3
Source Project: incubator-tuweni   Source File: VertxRLPxService.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Default constructor.
 *
 * @param vertx Vert.x object used to build the network components
 * @param listenPort the port to listen to
 * @param networkInterface the network interface to bind to
 * @param advertisedPort the port to advertise in HELLO messages to peers
 * @param identityKeyPair the identity of this client
 * @param subProtocols subprotocols supported
 * @param clientId the client identifier, such as "RLPX 1.2/build 389"
 * @param repository a wire connection repository
 */
public VertxRLPxService(
    Vertx vertx,
    int listenPort,
    String networkInterface,
    int advertisedPort,
    KeyPair identityKeyPair,
    List<SubProtocol> subProtocols,
    String clientId,
    WireConnectionRepository repository) {
  checkPort(listenPort);
  checkPort(advertisedPort);
  if (clientId == null || clientId.trim().isEmpty()) {
    throw new IllegalArgumentException("Client ID must contain a valid identifier");
  }
  this.vertx = vertx;
  this.listenPort = listenPort;
  this.networkInterface = networkInterface;
  this.advertisedPort = advertisedPort;
  this.keyPair = identityKeyPair;
  this.subProtocols = subProtocols;
  this.clientId = clientId;
  this.repository = repository;
}
 
Example 4
/**
 * Sets up the fixture.
 */
@BeforeEach
public void setUp() {

    final SpanContext spanContext = mock(SpanContext.class);

    span = mock(Span.class);
    when(span.context()).thenReturn(spanContext);
    final SpanBuilder spanBuilder = HonoClientUnitTestHelper.mockSpanBuilder(span);

    final Tracer tracer = mock(Tracer.class);
    when(tracer.buildSpan(anyString())).thenReturn(spanBuilder);

    final Vertx vertx = mock(Vertx.class);
    final ProtonReceiver receiver = HonoClientUnitTestHelper.mockProtonReceiver();
    sender = HonoClientUnitTestHelper.mockProtonSender();

    final RequestResponseClientConfigProperties config = new RequestResponseClientConfigProperties();
    final HonoConnection connection = HonoClientUnitTestHelper.mockHonoConnection(vertx, config);
    when(connection.getTracer()).thenReturn(tracer);

    client = new DeviceConnectionClientImpl(connection, Constants.DEFAULT_TENANT, sender, receiver);
}
 
Example 5
Source Project: vertx-consul-client   Source File: ChecksBase.java    License: Apache License 2.0 6 votes vote down vote up
GrpcHealthReporter(Vertx vertx) {
  this.port = Utils.getFreePort();
  HealthGrpc.HealthImplBase service = new HealthGrpc.HealthImplBase() {
    @Override
    public void check(HealthCheck.HealthCheckRequest request, StreamObserver<HealthCheck.HealthCheckResponse> response) {
      response.onNext(HealthCheck.HealthCheckResponse.newBuilder()
        .setStatus(status)
        .build());
      response.onCompleted();
    }
  };
  server = VertxServerBuilder
    .forPort(vertx, port)
    .addService(service)
    .build();
}
 
Example 6
Source Project: cava   Source File: ClientCaOrTofuTest.java    License: Apache License 2.0 6 votes vote down vote up
@BeforeEach
void setupClient(@TempDirectory Path tempDir, @VertxInstance Vertx vertx) throws Exception {
  knownServersFile = tempDir.resolve("known-hosts.txt");
  Files.write(
      knownServersFile,
      Arrays.asList("#First line", "localhost:" + foobarServer.actualPort() + " " + DUMMY_FINGERPRINT));

  HttpClientOptions options = new HttpClientOptions();
  options
      .setSsl(true)
      .setTrustOptions(VertxTrustOptions.trustServerOnFirstUse(knownServersFile))
      .setConnectTimeout(1500)
      .setReuseAddress(true)
      .setReusePort(true);
  client = vertx.createHttpClient(options);
}
 
Example 7
Source Project: vertx-sql-client   Source File: DB2ClientExamples.java    License: Apache License 2.0 6 votes vote down vote up
public void configureFromDataObject(Vertx vertx) {

    // Data object
    DB2ConnectOptions connectOptions = new DB2ConnectOptions()
      .setPort(50000)
      .setHost("the-host")
      .setDatabase("the-db")
      .setUser("user")
      .setPassword("secret");

    // Pool Options
    PoolOptions poolOptions = new PoolOptions().setMaxSize(5);

    // Create the pool from the data object
    DB2Pool pool = DB2Pool.pool(vertx, connectOptions, poolOptions);

    pool.getConnection(ar -> {
      // Handling your connection
    });
  }
 
Example 8
Source Project: vertx-web   Source File: WebClientExamples.java    License: Apache License 2.0 6 votes vote down vote up
public void simpleGetAndHead(Vertx vertx) {

    WebClient client = WebClient.create(vertx);

    // Send a GET request
    client
      .get(8080, "myserver.mycompany.com", "/some-uri")
      .send()
      .onSuccess(response -> System.out
        .println("Received response with status code" + response.statusCode()))
      .onFailure(err ->
        System.out.println("Something went wrong " + err.getMessage()));

    // Send a HEAD request
    client
      .head(8080, "myserver.mycompany.com", "/some-uri")
      .send()
      .onSuccess(response -> System.out
        .println("Received response with status code" + response.statusCode()))
      .onFailure(err ->
        System.out.println("Something went wrong " + err.getMessage()));
  }
 
Example 9
Source Project: apiman   Source File: ThreeScaleImmutableRegistry.java    License: Apache License 2.0 6 votes vote down vote up
public OneShotURILoader(Vertx vertx, Map<String, String> config) {
    this.config = config;
    this.vertx = vertx;
    this.defaultOrgName = config.getOrDefault("defaultOrgName", ThreeScaleConstants.DEFAULT_ORGNAME);
    this.defaultVersion = config.getOrDefault("defaultVersion", ThreeScaleConstants.DEFAULT_VERSION);
    this.strategy = RateLimitingStrategy.valueOfOrDefault(config.get("strategy"), RateLimitingStrategy.STANDARD);
    this.apiUri = URI.create(requireOpt("apiEndpoint", "apiEndpoint is required in configuration"));
    this.environment = config.getOrDefault("environment", "production");
    this.backendEndpoint = config.getOrDefault("backendEndpoint", ThreeScaleConstants.DEFAULT_BACKEND);

    if (config.containsKey("policyConfig.overlayUri")) {
        this.policyConfigUri = URI.create(config.get("policyConfig.overlayUri")); // Can be null.
    }

    fetchResource();
}
 
Example 10
/**
 * Verifies that the <em>getCommandHandlingAdapterInstances</em> operation fails
 * if the adapter instance mapping entry has expired.
 *
 * @param vertx The vert.x instance.
 * @param ctx The vert.x context.
 */
@Test
public void testGetCommandHandlingAdapterInstancesWithExpiredEntry(final Vertx vertx, final VertxTestContext ctx) {
    final String deviceId = "testDevice";
    final String adapterInstance = "adapterInstance";

    final Cache<String, String> mockedCache = spy(cache);
    info = new CacheBasedDeviceConnectionInfo(mockedCache, tracer);
    info.setCommandHandlingAdapterInstance(Constants.DEFAULT_TENANT, deviceId, adapterInstance, Duration.ofMillis(1), span)
    .compose(v -> {
        final Promise<JsonObject> instancesPromise = Promise.promise();
        // wait 2ms to make sure entry has expired after that
        vertx.setTimer(2, tid -> {
            info.getCommandHandlingAdapterInstances(Constants.DEFAULT_TENANT, deviceId,
                    Collections.emptySet(), span)
                    .onComplete(instancesPromise.future());
        });
        return instancesPromise.future();
    }).onComplete(ctx.failing(t -> ctx.verify(() -> {
        assertThat(t).isInstanceOf(ServiceInvocationException.class);
        assertThat(((ServiceInvocationException) t).getErrorCode()).isEqualTo(HttpURLConnection.HTTP_NOT_FOUND);
        ctx.completeNow();
    })));
}
 
Example 11
@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 12
Source Project: mewbase   Source File: VertxRestServiceAdapter.java    License: MIT License 5 votes vote down vote up
public VertxRestServiceAdapter(Config cfg) {
    // Get the Vertx rest end point configuration
    final String host = cfg.getString("mewbase.api.rest.vertx.host");
    final int port = cfg.getInt("mewbase.api.rest.vertx.port");
    final Duration timeout = cfg.getDuration("mewbase.api.rest.vertx.timeout");
    final HttpServerOptions opts = new HttpServerOptions().setHost(host).setPort(port);

    // Set up the rest server using the config.
    final Vertx vertx = Vertx.vertx();
    httpServer = vertx.createHttpServer(opts);
    router = Router.router(vertx);
    router.route().handler(BodyHandler.create());
    httpServer.requestHandler(router::accept);
    logger.info("Created Rest Adapter on "+ opts.getHost() + ":" + opts.getPort() );
}
 
Example 13
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 14
public void exampleSharedProducer(Vertx vertx, Map<String, String> config) {
  // Create a shared producer identified by 'the-producer'
  KafkaProducer<String, String> producer1 = KafkaProducer.createShared(vertx, "the-producer", config);

  // Sometimes later you can close it
  producer1.close();
}
 
Example 15
Source Project: vertx-junit5   Source File: VertxExtensionTest.java    License: Apache License 2.0 5 votes vote down vote up
@RepeatedTest(10)
@DisplayName("Test the validity of references and scoping")
void checkDeployments(Vertx vertx, VertxTestContext testContext) {
  assertThat(testContext).isNotSameAs(previousTestContext);
  previousTestContext = testContext;
  assertThat(vertx).isSameAs(currentVertx);
  assertThat(vertx.deploymentIDs()).isNotEmpty().hasSize(1);
  testContext.completeNow();
}
 
Example 16
Source Project: hono   Source File: AuthenticationServerClient.java    License: Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Creates a client for a remote authentication server.
 *
 * @param vertx The Vert.x instance to run on.
 * @param connectionFactory The factory.
 * @throws NullPointerException if any of the parameters is {@code null}.
 */
public AuthenticationServerClient(
        final Vertx vertx,
        final ConnectionFactory connectionFactory) {

    this.vertx = Objects.requireNonNull(vertx);
    this.factory = Objects.requireNonNull(connectionFactory);
}
 
Example 17
Source Project: vertx-web   Source File: OpenAPIHolderTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void loadFromFileNoRef(Vertx vertx, VertxTestContext testContext) {
  OpenAPIHolderImpl parser = new OpenAPIHolderImpl(vertx.createHttpClient(), vertx.fileSystem(), new OpenAPILoaderOptions());

  parser.loadOpenAPI("yaml/valid/simple_spec.yaml").onComplete(testContext.succeeding(container -> {
    testContext.verify(() -> {
      assertThat(container)
          .extracting(JsonPointer.from("/info/title"))
          .isEqualTo("Simple spec no $refs");

      assertThat(container)
          .extracting(JsonPointer.create()
              .append("paths")
              .append("/simple")
              .append("post")
              .append("requestBody")
              .append("content")
              .append("multipart/form-data")
              .append("encoding")
              .append("fileName")
              .append("contentType")
          )
          .isEqualTo("text/plain");

      assertThat(container)
          .extracting(JsonPointer.create()
              .append("paths")
              .append("/simple")
              .append("post")
              .append("responses")
              .append("default")
              .append("description")
          )
          .isEqualTo("unexpected error");
    });
    testContext.completeNow();
  }));
}
 
Example 18
public void register2(Vertx vertx) {
  ServiceDiscovery.create(vertx)
      .registerServiceImporter(new ZookeeperServiceImporter(),
          new JsonObject()
              .put("connection", "127.0.0.1:2181")
              .put("maxRetries", 5)
              .put("baseSleepTimeBetweenRetries", 2000)
              .put("basePath", "/services")
      );
}
 
Example 19
Source Project: vertx-redis-client   Source File: RedisPooledTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test(timeout = 30_000L)
public void acquireConnectionsTest(TestContext should) {
  final Vertx vertx = rule.vertx();
  final Async test = should.async();

  Redis client = Redis.createClient(
    vertx,
    new RedisOptions()
      .addConnectionString("redis://localhost:7006")
      .setMaxPoolSize(10)
      .setMaxPoolWaiting(10));

  final AtomicInteger counter = new AtomicInteger();

  // this test asserts that the pools behaves as expected it shall return 10 new connections
  // and will fail on the 21st call as the 10 waiting slots are taken

  vertx.setPeriodic(500, event -> {
    counter.incrementAndGet();
    client.connect(event1 -> {
      if (event1.succeeded()) {
        System.out.println(counter.get());
        should.assertTrue(counter.get() <= 10);
      } else {
        System.out.println(counter.get());
        should.assertTrue(counter.get() == 21);
        vertx.cancelTimer(event);
        test.complete();
      }
    });
  });
}
 
Example 20
Source Project: weld-vertx   Source File: AsyncWorkerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Before
public void init(TestContext context) throws InterruptedException {
    final WeldVerticle weldVerticle = new WeldVerticle();
    Async async = context.async();
    vertx = Vertx.vertx();
    vertx.deployVerticle(weldVerticle, r -> {
        if (r.succeeded()) {
            weld = weldVerticle.container();
            async.complete();
        } else {
            context.fail(r.cause());
        }
    });
}
 
Example 21
Source Project: vertx-web   Source File: RouterFactorySecurityTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void mountOrAndMixed(Vertx vertx, VertxTestContext testContext) {
  Checkpoint checkpoint = testContext.checkpoint();
  loadFactoryAndStartServer(vertx, SECURITY_TESTS, testContext, routerFactory -> {
    routerFactory.setOptions(FACTORY_OPTIONS);

    routerFactory.operation("listPetsOrAndSecurity").handler(routingContext -> routingContext
      .response()
      .setStatusCode(200)
      .setStatusMessage(concatenateRoutingContextEntries(
        routingContext,
        "api_key",
        "second_api_key",
        "sibling_second_api_key",
        "third_api_key"
      ))
      .end()
    );

    routerFactory.securityHandler("api_key",
      mockFailingAuthHandler(routingContext -> routingContext.put("api_key", "1"))
    );

    routerFactory.securityHandler("second_api_key",
      mockSuccessfulAuthHandler(routingContext -> routingContext.put("second_api_key", "2"))
    );

    routerFactory.securityHandler("sibling_second_api_key",
      mockSuccessfulAuthHandler(routingContext -> routingContext.put("sibling_second_api_key", "3"))
    );

    routerFactory.securityHandler("third_api_key",
      mockFailingAuthHandler(routingContext -> routingContext.put("third_api_key", "4"))
    );
  }).onComplete(h ->
    testRequest(client, HttpMethod.GET, "/pets_or_and_security")
      .expect(statusCode(200), statusMessage("1-2-3-null"))
      .send(testContext, checkpoint)
  );
}
 
Example 22
Source Project: vxms   Source File: EventbusBridgeExecution.java    License: Apache License 2.0 5 votes vote down vote up
private static void resetLockTimer(
    VxmsShared vxmsShared, int retryCount, long circuitBreakerTimeout, Counter counter) {
  final Vertx vertx = vxmsShared.getVertx();
  vertx.setTimer(
      circuitBreakerTimeout,
      timer -> counter.addAndGet(Integer.valueOf(retryCount + 1).longValue(), val -> {}));
}
 
Example 23
Source Project: strimzi-kafka-operator   Source File: TopicOperatorTest.java    License: Apache License 2.0 5 votes vote down vote up
@BeforeAll
public static void before() {
    vertx = Vertx.vertx(new VertxOptions().setMetricsOptions(
            new MicrometerMetricsOptions()
                    .setPrometheusOptions(new VertxPrometheusOptions().setEnabled(true))
                    .setEnabled(true)
    ));
}
 
Example 24
Source Project: quarkus   Source File: DB2PoolRecorder.java    License: Apache License 2.0 5 votes vote down vote up
private DB2Pool initialize(Vertx vertx, DataSourceRuntimeConfig dataSourceRuntimeConfig,
        DataSourceReactiveRuntimeConfig dataSourceReactiveRuntimeConfig,
        DataSourceReactiveDB2Config dataSourceReactiveDB2Config) {
    PoolOptions poolOptions = toPoolOptions(dataSourceRuntimeConfig, dataSourceReactiveRuntimeConfig,
            dataSourceReactiveDB2Config);
    DB2ConnectOptions connectOptions = toConnectOptions(dataSourceRuntimeConfig, dataSourceReactiveRuntimeConfig,
            dataSourceReactiveDB2Config);
    if (dataSourceReactiveRuntimeConfig.threadLocal.isPresent() &&
            dataSourceReactiveRuntimeConfig.threadLocal.get()) {
        return new ThreadLocalDB2Pool(vertx, connectOptions, poolOptions);
    }
    return DB2Pool.pool(vertx, connectOptions, poolOptions);
}
 
Example 25
@Test
public void shouldSendDataToInfluxDb(TestContext context) throws Exception {
  // Mock an influxdb server
  Async asyncInflux = context.async();
  InfluxDbTestHelper.simulateInfluxServer(vertxForSimulatedServer, context, 8086, body -> {
    if (body.contains("vertx_eventbus_handlers,address=test-eb,metric_type=gauge value=1")) {
      asyncInflux.complete();
    }
  });

  vertx = Vertx.vertx(new VertxOptions()
    .setMetricsOptions(new MicrometerMetricsOptions()
      .setInfluxDbOptions(new VertxInfluxDbOptions()
        .setStep(1)
        .setDb("mydb")
        .setEnabled(true))
      .setRegistryName(REGITRY_NAME)
      .addLabels(Label.EB_ADDRESS)
      .setEnabled(true)));

  // Send something on the eventbus and wait til it's received
  Async asyncEB = context.async();
  vertx.eventBus().consumer("test-eb", msg -> asyncEB.complete());
  vertx.eventBus().publish("test-eb", "test message");
  asyncEB.await(2000);

  // Await influx
  asyncInflux.awaitSuccess(2000);
}
 
Example 26
Source Project: vertx-dropwizard-metrics   Source File: MetricsExamples.java    License: Apache License 2.0 5 votes vote down vote up
public void example4() {
  Vertx vertx = Vertx.vertx(new VertxOptions().setMetricsOptions(
      new DropwizardMetricsOptions()
          .setEnabled(true)
          .setJmxEnabled(true)
          .setJmxDomain("vertx-metrics")));
}
 
Example 27
@Test
public void test5(Vertx vertx, VertxTestContext testContext) {
  Checkpoint checkpoint = testContext.checkpoint(3);
  assertRequestOk("/test5", "test5_ok_1.json", vertx, testContext, checkpoint);
  assertRequestOk("/test5", "test5_ok_2.json", vertx, testContext, checkpoint);
  assertRequestFail("/test5", "test5_fail.json", vertx, testContext, checkpoint);
}
 
Example 28
Source Project: apiman   Source File: URILoadingRegistry.java    License: Apache License 2.0 5 votes vote down vote up
public URILoadingRegistry(Vertx vertx, IEngineConfig vxConfig, Map<String, String> options) {
    super();
    this.vertx = vertx;
    this.options = options;
    Arguments.require(options.containsKey("configUri"), "configUri is required in configuration");
    uri = URI.create(options.get("configUri"));
}
 
Example 29
Source Project: vertx-web   Source File: RouterFactoryIntegrationTest.java    License: Apache License 2.0 5 votes vote down vote up
private Future<Void> startFileServer(Vertx vertx, VertxTestContext testContext) {
  Router router = Router.router(vertx);
  router.route().handler(StaticHandler.create("src/test/resources"));
  return testContext.assertComplete(
    vertx.createHttpServer()
      .requestHandler(router)
      .listen(9001)
      .mapEmpty()
  );
}
 
Example 30
Source Project: enode   Source File: EventAppConfig.java    License: MIT License 5 votes vote down vote up
@PostConstruct
public void deployVerticle() {
    vertx = Vertx.vertx();

    vertx.deployVerticle(commandResultProcessor, res -> {

    });
    vertx.deployVerticle(mysqlEventStore, res -> {

    });
    vertx.deployVerticle(publishedVersionStore, res -> {

    });
}