Java Code Examples for io.vertx.core.http.HttpServerOptions

The following examples show how to use io.vertx.core.http.HttpServerOptions. 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: ServerTofaTest.java    License: Apache License 2.0 6 votes vote down vote up
@BeforeEach
void startServer(@TempDirectory Path tempDir, @VertxInstance Vertx vertx) throws Exception {
  knownClientsFile = tempDir.resolve("known-clients.txt");
  Files.write(knownClientsFile, Arrays.asList("#First line", "foobar.com " + DUMMY_FINGERPRINT));

  SelfSignedCertificate serverCert = SelfSignedCertificate.create();
  HttpServerOptions options = new HttpServerOptions();
  options
      .setSsl(true)
      .setClientAuth(ClientAuth.REQUIRED)
      .setPemKeyCertOptions(serverCert.keyCertOptions())
      .setTrustOptions(VertxTrustOptions.trustClientOnFirstAccess(knownClientsFile, false))
      .setIdleTimeout(1500)
      .setReuseAddress(true)
      .setReusePort(true);
  httpServer = vertx.createHttpServer(options);
  SecurityTestUtils.configureAndStartTestServer(httpServer);
}
 
Example 2
Source Project: incubator-tuweni   Source File: ServerRecordTest.java    License: Apache License 2.0 6 votes vote down vote up
@BeforeEach
void startServer(@TempDirectory Path tempDir, @VertxInstance Vertx vertx) throws Exception {
  knownClientsFile = tempDir.resolve("known-clients.txt");
  Files.write(knownClientsFile, Arrays.asList("#First line", "foobar.com " + DUMMY_FINGERPRINT));

  SelfSignedCertificate serverCert = SelfSignedCertificate.create();
  HttpServerOptions options = new HttpServerOptions();
  options
      .setSsl(true)
      .setClientAuth(ClientAuth.REQUIRED)
      .setPemKeyCertOptions(serverCert.keyCertOptions())
      .setTrustOptions(VertxTrustOptions.recordClientFingerprints(knownClientsFile, false))
      .setIdleTimeout(1500)
      .setReuseAddress(true)
      .setReusePort(true);
  httpServer = vertx.createHttpServer(options);
  SecurityTestUtils.configureAndStartTestServer(httpServer);
}
 
Example 3
Source Project: incubator-tuweni   Source File: ClientWhitelistTest.java    License: Apache License 2.0 6 votes vote down vote up
@BeforeAll
static void startServers(@TempDirectory Path tempDir, @VertxInstance Vertx vertx) throws Exception {
  SelfSignedCertificate caSignedCert = SelfSignedCertificate.create("localhost");
  caValidFingerprint = certificateHexFingerprint(Paths.get(caSignedCert.keyCertOptions().getCertPath()));
  SecurityTestUtils.configureJDKTrustStore(tempDir, caSignedCert);
  caValidServer = vertx
      .createHttpServer(new HttpServerOptions().setSsl(true).setPemKeyCertOptions(caSignedCert.keyCertOptions()))
      .requestHandler(context -> context.response().end("OK"));
  startServer(caValidServer);

  SelfSignedCertificate fooCert = SelfSignedCertificate.create("foo.com");
  fooFingerprint = certificateHexFingerprint(Paths.get(fooCert.keyCertOptions().getCertPath()));
  fooServer = vertx
      .createHttpServer(new HttpServerOptions().setSsl(true).setPemKeyCertOptions(fooCert.keyCertOptions()))
      .requestHandler(context -> context.response().end("OK"));
  startServer(fooServer);

  SelfSignedCertificate barCert = SelfSignedCertificate.create("bar.com");
  barFingerprint = certificateHexFingerprint(Paths.get(barCert.keyCertOptions().getCertPath()));
  barServer = vertx
      .createHttpServer(new HttpServerOptions().setSsl(true).setPemKeyCertOptions(barCert.keyCertOptions()))
      .requestHandler(context -> context.response().end("OK"));
  startServer(barServer);
}
 
Example 4
Source Project: incubator-tuweni   Source File: ServerCaOrRecordTest.java    License: Apache License 2.0 6 votes vote down vote up
@BeforeEach
void startServer(@TempDirectory Path tempDir, @VertxInstance Vertx vertx) throws Exception {
  knownClientsFile = tempDir.resolve("known-clients.txt");
  Files.write(knownClientsFile, Arrays.asList("#First line", "foobar.com " + DUMMY_FINGERPRINT));

  SelfSignedCertificate serverCert = SelfSignedCertificate.create();
  HttpServerOptions options = new HttpServerOptions();
  options
      .setSsl(true)
      .setClientAuth(ClientAuth.REQUIRED)
      .setPemKeyCertOptions(serverCert.keyCertOptions())
      .setTrustOptions(VertxTrustOptions.recordClientFingerprints(knownClientsFile))
      .setIdleTimeout(1500)
      .setReuseAddress(true)
      .setReusePort(true);
  httpServer = vertx.createHttpServer(options);
  SecurityTestUtils.configureAndStartTestServer(httpServer);
}
 
Example 5
Source Project: okapi   Source File: OkapiClientTest.java    License: Apache License 2.0 6 votes vote down vote up
@Before
public void setUp(TestContext context) {
  logger.debug("setUp");
  vertx = Vertx.vertx();
  Async async = context.async();

  Router router = Router.router(vertx);
  router.get("/test1").handler(this::myStreamHandle1);
  router.head("/test1").handler(this::myStreamHandle1);
  router.post("/test1").handler(this::myStreamHandle1);
  router.delete("/test1").handler(this::myStreamHandle1);
  router.get("/test2").handler(this::myStreamHandle2);

  HttpServerOptions so = new HttpServerOptions().setHandle100ContinueAutomatically(true);
  server = vertx.createHttpServer(so)
    .requestHandler(router)
    .listen(
      PORT,
      result -> {
        if (result.failed()) {
          context.fail(result.cause());
        }
        async.complete();
      }
    );
}
 
Example 6
Source Project: vertx-codetrans   Source File: DataObjectTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
  public void testAddToList() throws Exception {
    HashSet<String> expected = new HashSet<>();
    expected.add("foo");
    expected.add("bar");
    o = null;
    runGroovy("dataobject/DataObject", "addToList");
    HttpServerOptions actual = new HttpServerOptions(unwrapJsonObject((Map<String, Object>) o));
    Assert.assertEquals(expected, actual.getEnabledCipherSuites());
    o = null;
//    runScala("dataobject/DataObject", "addToList");
//    actual = new HttpServerOptions(unwrapJsonObject((Map<String, Object>) o));
//    expected = new HashSet<>();
//    expected.add("foo");
//    expected.add("bar");
//    Assert.assertEquals(expected, actual.getEnabledCipherSuites());
  }
 
Example 7
Source Project: ethsigner   Source File: EthSigner.java    License: Apache License 2.0 6 votes vote down vote up
private HttpServerOptions applyConfigTlsSettingsTo(final HttpServerOptions input) {

    if (config.getTlsOptions().isEmpty()) {
      return input;
    }

    HttpServerOptions result = new HttpServerOptions(input);
    result.setSsl(true);
    final TlsOptions tlsConfig = config.getTlsOptions().get();

    result = applyTlsKeyStore(result, tlsConfig);

    if (tlsConfig.getClientAuthConstraints().isPresent()) {
      result = applyClientAuthentication(result, tlsConfig.getClientAuthConstraints().get());
    }

    return result;
  }
 
Example 8
Source Project: ethsigner   Source File: EthSigner.java    License: Apache License 2.0 6 votes vote down vote up
private static HttpServerOptions applyClientAuthentication(
    final HttpServerOptions input, final ClientAuthConstraints constraints) {
  final HttpServerOptions result = new HttpServerOptions(input);

  result.setClientAuth(ClientAuth.REQUIRED);
  try {
    constraints
        .getKnownClientsFile()
        .ifPresent(
            whitelistFile ->
                result.setTrustOptions(
                    VertxTrustOptions.whitelistClients(
                        whitelistFile.toPath(), constraints.isCaAuthorizedClientAllowed())));
  } catch (final IllegalArgumentException e) {
    throw new InitializationException("Illegally formatted client fingerprint file.");
  }

  return result;
}
 
Example 9
Source Project: besu   Source File: JsonRpcHttpService.java    License: Apache License 2.0 6 votes vote down vote up
private void applyTlsConfig(final HttpServerOptions httpServerOptions) {
  if (config.getTlsConfiguration().isEmpty()) {
    return;
  }

  final TlsConfiguration tlsConfiguration = config.getTlsConfiguration().get();
  try {
    httpServerOptions
        .setSsl(true)
        .setPfxKeyCertOptions(
            new PfxOptions()
                .setPath(tlsConfiguration.getKeyStorePath().toString())
                .setPassword(tlsConfiguration.getKeyStorePassword()));

    tlsConfiguration
        .getClientAuthConfiguration()
        .ifPresent(
            clientAuthConfiguration ->
                applyTlsClientAuth(clientAuthConfiguration, httpServerOptions));
  } catch (final RuntimeException re) {
    throw new JsonRpcServiceException(
        String.format(
            "TLS options failed to initialize for Ethereum JSON-RPC listener: %s",
            re.getMessage()));
  }
}
 
Example 10
/**
 * <p>Read configuration for different sources and generate a {@link HttpServerOptions} with the configurations provided.</p>
 * <p>Currently reading configuration options from:
 * <ul>
 * <li>Vert.x Config Option</li>
 * <li>Command Line Option passed with {@code -D}</li>
 * </ul>
 * </p>
 * <p>The list above is from the lesser priority to the highest, so currently the command line options is the highest priority and will
 * override any other configuration option</p>
 *
 * @return {@link HttpServerOptions} with configuration for the server.
 */
private HttpServerOptions getServerOptions() {
  final Integer systemServerPort = Integer.getInteger(Configuration.SERVER_PORT);
  final String systemBindAddress = System.getProperty(Configuration.BIND_ADDRESS);
  final String systemDisableCompression = System.getProperty(Configuration.DISABLE_COMPRESSION);

  final Integer serverPort = systemServerPort != null ? systemServerPort : config().getInteger(Configuration.SERVER_PORT, 7979);
  final String bindAddress = systemBindAddress != null ? systemBindAddress : config().getString(Configuration.BIND_ADDRESS, "0.0.0.0"); // NOPMD
  final boolean disableCompression = systemDisableCompression != null ? Boolean.valueOf(systemDisableCompression) : config().getBoolean(Configuration.DISABLE_COMPRESSION,
                                                                                                                                        Boolean.FALSE);
  final HttpServerOptions options = new HttpServerOptions().setTcpKeepAlive(true)
                                                           .setIdleTimeout(10000)
                                                           .setPort(serverPort)
                                                           .setHost(bindAddress)
                                                           .setCompressionSupported(!disableCompression);

  log.info("Compression support enabled: {}", !disableCompression);
  return options;
}
 
Example 11
/**
 * Create an HTTP Server and return a future for the startup result
 * @return Future for handling the serve open event
 */
protected Future<HttpServer> createServer() {
  Future<HttpServer> ret = Future.future();

  HttpServerOptions serverOptions =
      new HttpServerOptions()
          .setLogActivity(true)
          .setPort(8091)
          .setSsl(false);

  httpServer = this.vertx.createHttpServer(serverOptions);

  // Simple 200 handler
  httpServer.requestHandler( req -> req.response().setStatusCode(200).end("Success!") );

  // Listen! delegating to the future
  httpServer.listen( ret.completer() );

  return ret;
}
 
Example 12
Source Project: cava   Source File: ClientCaOrWhitelistTest.java    License: Apache License 2.0 6 votes vote down vote up
@BeforeAll
static void startServers(@TempDirectory Path tempDir, @VertxInstance Vertx vertx) throws Exception {
  SelfSignedCertificate caSignedCert = SelfSignedCertificate.create("localhost");
  SecurityTestUtils.configureJDKTrustStore(tempDir, caSignedCert);
  caValidServer = vertx
      .createHttpServer(new HttpServerOptions().setSsl(true).setPemKeyCertOptions(caSignedCert.keyCertOptions()))
      .requestHandler(context -> context.response().end("OK"));
  startServer(caValidServer);

  SelfSignedCertificate fooCert = SelfSignedCertificate.create("foo.com");
  fooFingerprint = certificateHexFingerprint(Paths.get(fooCert.keyCertOptions().getCertPath()));
  fooServer = vertx
      .createHttpServer(new HttpServerOptions().setSsl(true).setPemKeyCertOptions(fooCert.keyCertOptions()))
      .requestHandler(context -> context.response().end("OK"));
  startServer(fooServer);

  SelfSignedCertificate barCert = SelfSignedCertificate.create("bar.com");
  barFingerprint = certificateHexFingerprint(Paths.get(barCert.keyCertOptions().getCertPath()));
  barServer = vertx
      .createHttpServer(new HttpServerOptions().setSsl(true).setPemKeyCertOptions(barCert.keyCertOptions()))
      .requestHandler(context -> context.response().end("OK"));
  startServer(barServer);
}
 
Example 13
Source Project: cava   Source File: ServerCaOrRecordTest.java    License: Apache License 2.0 6 votes vote down vote up
@BeforeEach
void startServer(@TempDirectory Path tempDir, @VertxInstance Vertx vertx) throws Exception {
  knownClientsFile = tempDir.resolve("known-clients.txt");
  Files.write(knownClientsFile, Arrays.asList("#First line", "foobar.com " + DUMMY_FINGERPRINT));

  SelfSignedCertificate serverCert = SelfSignedCertificate.create();
  HttpServerOptions options = new HttpServerOptions();
  options
      .setSsl(true)
      .setClientAuth(ClientAuth.REQUIRED)
      .setPemKeyCertOptions(serverCert.keyCertOptions())
      .setTrustOptions(VertxTrustOptions.recordClientFingerprints(knownClientsFile))
      .setIdleTimeout(1500)
      .setReuseAddress(true)
      .setReusePort(true);
  httpServer = vertx.createHttpServer(options);
  SecurityTestUtils.configureAndStartTestServer(httpServer);
}
 
Example 14
Source Project: vert.x-microservice   Source File: ServiceEntryPoint.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * start the server, attach the route matcher
 */
private void initHTTPConnector() {
    HttpServer server = vertx.createHttpServer(new HttpServerOptions().setHost(host)
            .setPort(port));
    registerWebSocketHandler(server);
    // TODO provide a WebSocket and a EventBus access to ServiceInfo ... this must be routed through the Router to enrich the service info with metadata from the router
    routeMatcher.matchMethod(HttpMethod.GET, serviceInfoPath, request -> fetchRegitryAndUpdateMetadata((serviceInfo -> {
        request.response().putHeader("content-type", "text/json");
        request.response().end(serviceInfo.encodePrettily());
    })));
    routeMatcher.matchMethod(HttpMethod.GET,"/metrics",req -> {
        MetricsService metricsService = MetricsService.create(vertx);
        JsonObject metrics = metricsService.getMetricsSnapshot(vertx);
        req.response().putHeader("content-type", "text/json");
        req.response().end(metrics.encodePrettily());
    }) ;
    routeMatcher.noMatch(handler -> handler.response().end("no route found"));
    server.requestHandler(routeMatcher::accept).listen(res -> {

    });


}
 
Example 15
Source Project: okapi   Source File: PullTest.java    License: Apache License 2.0 6 votes vote down vote up
private void setupOtherHttpServer(TestContext context, Async async) {
  Router router = Router.router(vertx);

  HttpServerOptions so = new HttpServerOptions().setHandle100ContinueAutomatically(true);
  vertx.createHttpServer(so)
    .requestHandler(router)
    .listen(
      port3,
      result -> {
        if (result.failed()) {
          context.fail(result.cause());
        }
        async.complete();
      }
    );
}
 
Example 16
Source Project: demo-mesh-arena   Source File: Ball.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void start() {
  // Register ball API
  HttpServerOptions serverOptions = new HttpServerOptions().setPort(Commons.BALL_PORT);
  Router router = Router.router(vertx);

  if (Commons.METRICS_ENABLED == 1) {
    router.route("/metrics").handler(PrometheusScrapingHandler.create());
  }

  router.get("/health").handler(ctx -> ctx.response().end());
  router.put("/shoot").handler(this::shoot);
  router.get("/tryGet").handler(this::tryGet);
  router.put("/setPosition").handler(this::setPosition);
  vertx.createHttpServer().requestHandler(router)
      .listen(serverOptions.getPort(), serverOptions.getHost());

  // Ping-display
  vertx.setPeriodic(2000, loopId -> this.display());

  // Start game loop
  vertx.setPeriodic(DELTA_MS, loopId -> this.update((double)DELTA_MS / 1000.0));
}
 
Example 17
Source Project: mewbase   Source File: Main.java    License: MIT License 6 votes vote down vote up
public static void main(String[] args) {
    String resourceBasename = "example.gettingstarted.projectionrest/configuration.conf";
    final Config config = ConfigFactory.load(resourceBasename);

    // create a Vertx web server
    final Vertx vertx = Vertx.vertx();
    final HttpServerOptions options = new HttpServerOptions().setPort(8080);
    final HttpServer httpServer = vertx.createHttpServer(options);
    final BinderStore binderStore = BinderStore.instance(config);
    final Router router = Router.router(vertx);
    router.route().handler(BodyHandler.create());
    httpServer.requestHandler(router::accept);

    /*
    Expose endpoint to retrieve a document from the binder store
     */
    router.route(HttpMethod.GET, "/summary/:product/:date").handler(routingContext -> {
        final String product = routingContext.pathParams().get("product");
        final String date = routingContext.pathParams().get("date");
        final VertxRestServiceActionVisitor actionVisitor = new VertxRestServiceActionVisitor(routingContext);
        actionVisitor.visit(RestServiceAction.retrieveSingleDocument(binderStore, "sales_summary", product + "_" + date));
    });

    httpServer.listen();
}
 
Example 18
@Test
public void testPrometheusDefaults(TestContext context) throws Exception {
  VertxPrometheusOptions prometheusOptions = new VertxPrometheusOptions()
    .setEnabled(true)
    .setStartEmbeddedServer(true)
    .setEmbeddedServerOptions(new HttpServerOptions().setPort(9999));
  MicrometerMetricsOptions metricsOptions = new MicrometerMetricsOptions()
    .setEnabled(true)
    .setPrometheusOptions(prometheusOptions);

  startVertx(context, metricsOptions);

  Set<String> metrics = PrometheusTestHelper.getMetricNames(vertx, context, 9999, "localhost", "/metrics", 3000);
  assertThat(metrics).contains("vertx_http_client_connections")
    .doesNotContain("jvm_classes_loaded");
}
 
Example 19
@Test
public void testJvmMetricsEnabled(TestContext context) throws Exception {
  VertxPrometheusOptions prometheusOptions = new VertxPrometheusOptions()
    .setEnabled(true)
    .setStartEmbeddedServer(true)
    .setEmbeddedServerOptions(new HttpServerOptions().setPort(9999));
  MicrometerMetricsOptions metricsOptions = new MicrometerMetricsOptions()
    .setEnabled(true)
    .setJvmMetricsEnabled(true)
    .setPrometheusOptions(prometheusOptions);

  startVertx(context, metricsOptions);

  Set<String> metrics = PrometheusTestHelper.getMetricNames(vertx, context, 9999, "localhost", "/metrics", 3000);
  assertThat(metrics).contains(
    "jvm_classes_loaded_classes", // from classloader metrics
    "jvm_buffer_count_buffers", // from JVM memory metrics
    "system_cpu_count", // from processor metrics
    "jvm_threads_live_threads"); // from JVM thread metrics
}
 
Example 20
@Test
public void shouldStartEmbeddedServer(TestContext context) {
  vertx = Vertx.vertx(new VertxOptions()
    .setMetricsOptions(new MicrometerMetricsOptions()
      .setPrometheusOptions(new VertxPrometheusOptions().setEnabled(true)
        .setStartEmbeddedServer(true)
        .setEmbeddedServerOptions(new HttpServerOptions().setPort(9090)))
      .addLabels(Label.LOCAL, Label.HTTP_PATH, Label.REMOTE)
      .setEnabled(true)));

  Async async = context.async();
  // First "blank" connection to trigger some metrics
  PrometheusTestHelper.tryConnect(vertx, context, 9090, "localhost", "/metrics", r1 -> {
    // Delay to make "sure" metrics are populated
    vertx.setTimer(500, l ->
      // Second connection, this time actually reading the metrics content
      PrometheusTestHelper.tryConnect(vertx, context, 9090, "localhost", "/metrics", body -> {
          context.verify(v2 -> assertThat(body.toString())
            .contains("vertx_http_client_requests{local=\"?\",method=\"GET\",path=\"/metrics\",remote=\"localhost:9090\"")
            .doesNotContain("vertx_http_client_responseTime_seconds_bucket"));
          async.complete();
      }));
  });
  async.awaitSuccess(10000);
}
 
Example 21
Source Project: vertx-rx   Source File: WebClientTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testResponseMissingBody() throws Exception {
  int times = 5;
  waitFor(times);
  HttpServer server = vertx.createHttpServer(new HttpServerOptions().setPort(8080));
  server.requestStream().handler(req -> req.response().setStatusCode(403).end());
  try {
    server.listen(ar -> {
      client = WebClient.wrap(vertx.createHttpClient(new HttpClientOptions()));
      Single<HttpResponse<Buffer>> single = client
        .get(8080, "localhost", "/the_uri")
        .rxSend();
      for (int i = 0; i < times; i++) {
        single.subscribe(resp -> {
          assertEquals(403, resp.statusCode());
          assertNull(resp.body());
          complete();
        }, this::fail);
      }
    });
    await();
  } finally {
    server.close();
  }
}
 
Example 22
Source Project: quarkus   Source File: VertxHttpRecorder.java    License: Apache License 2.0 6 votes vote down vote up
private static HttpServerOptions createHttpServerOptions(HttpConfiguration httpConfiguration,
        LaunchMode launchMode, String websocketSubProtocols) {
    if (!httpConfiguration.hostEnabled) {
        return null;
    }
    // TODO other config properties
    HttpServerOptions options = new HttpServerOptions();
    options.setHost(httpConfiguration.host);
    options.setPort(httpConfiguration.determinePort(launchMode));
    setIdleTimeout(httpConfiguration, options);
    options.setMaxHeaderSize(httpConfiguration.limits.maxHeaderSize.asBigInteger().intValueExact());
    Optional<MemorySize> maxChunkSize = httpConfiguration.limits.maxChunkSize;
    if (maxChunkSize.isPresent()) {
        options.setMaxChunkSize(maxChunkSize.get().asBigInteger().intValueExact());
    }
    options.setWebsocketSubProtocols(websocketSubProtocols);
    options.setReusePort(httpConfiguration.soReusePort);
    options.setTcpQuickAck(httpConfiguration.tcpQuickAck);
    options.setTcpCork(httpConfiguration.tcpCork);
    options.setTcpFastOpen(httpConfiguration.tcpFastOpen);
    return options;
}
 
Example 23
Source Project: raml-module-builder   Source File: HttpModuleClient2Test.java    License: Apache License 2.0 5 votes vote down vote up
private Future<Void> startServer() {

    Router router = Router.router(vertx);

    router.routeWithRegex("/.*").handler(this::myPreHandle);

    Promise<Void> promise = Promise.promise();
    HttpServerOptions so = new HttpServerOptions().setHandle100ContinueAutomatically(true);
    vertx.createHttpServer(so)
        .requestHandler(router)
        .listen(port1, x -> promise.handle(x.mapEmpty()));
    return promise.future();

  }
 
Example 24
Source Project: vertx-rx   Source File: RxWebApiContractExamples.java    License: Apache License 2.0 5 votes vote down vote up
public void mainExample(Vertx vertx, Handler<RoutingContext> myValidationFailureHandler, JWTAuth jwtAuth) {
  OpenAPI3RouterFactory
    .rxCreate(vertx, "src/main/resources/petstore.yaml")
    .flatMap(routerFactory -> {
      // Spec loaded with success. router factory contains OpenAPI3RouterFactory
      // Set router factory options.
      RouterFactoryOptions options = new RouterFactoryOptions().setOperationModelKey("openapi_model");
      // Mount the options
      routerFactory.setOptions(options);
      // Add an handler with operationId
      routerFactory.addHandlerByOperationId("listPets", routingContext -> {
        // Handle listPets operation
        routingContext.response().setStatusMessage("Called listPets").end();
      });

      // Add a security handler
      routerFactory.addSecurityHandler("api_key", JWTAuthHandler.create(jwtAuth));

      // Now you have to generate the router
      Router router = routerFactory.getRouter();

      // Now you can use your Router instance
      HttpServer server = vertx.createHttpServer(new HttpServerOptions().setPort(8080).setHost("localhost"));
      return server.requestHandler(router).rxListen();
    })
    .subscribe(httpServer -> {
      // Server up and running
    }, throwable -> {
      // Error during router factory instantiation or http server start
    });
}
 
Example 25
Source Project: hono   Source File: VertxBasedHealthCheckServer.java    License: Eclipse Public License 2.0 5 votes vote down vote up
private Future<Void> bindInsecureHttpServer() {

        final Promise<Void> result = Promise.promise();

        if (Constants.LOOPBACK_DEVICE_ADDRESS.equals(config.getInsecurePortBindAddress())) {
            if (bindInsecureServerToLoopbackDeviceAllowed) {
                LOG.warn("insecure health checks HTTP server will bind to loopback device only");
            } else {
                LOG.info("won't start insecure health checks HTTP server: no bind address configured.");
                return Future.failedFuture("no bind address configured for insecure server");
            }
        }

        final HttpServerOptions options = new HttpServerOptions()
                .setPort(config.getInsecurePort(DEFAULT_PORT))
                .setHost(config.getInsecurePortBindAddress());
        insecureServer = vertx.createHttpServer(options);

        router.get(URI_READINESS_PROBE).handler(readinessHandler);
        router.get(URI_LIVENESS_PROBE).handler(livenessHandler);

        insecureServer.requestHandler(router).listen(startAttempt -> {
            if (startAttempt.succeeded()) {
                LOG.info("successfully started insecure health checks HTTP server");
                LOG.info("readiness probe available at http://{}:{}{}", options.getHost(), insecureServer.actualPort(),
                        URI_READINESS_PROBE);
                LOG.info("liveness probe available at http://{}:{}{}", options.getHost(), insecureServer.actualPort(),
                        URI_LIVENESS_PROBE);
                result.complete();
            } else {
                LOG.warn("failed to start insecure health checks HTTP server: {}",
                        startAttempt.cause().getMessage());
                result.fail(startAttempt.cause());
            }
        });
        return result.future();
    }
 
Example 26
Source Project: incubator-tuweni   Source File: ClientRecordTest.java    License: Apache License 2.0 5 votes vote down vote up
@BeforeAll
static void startServers(@TempDirectory Path tempDir, @VertxInstance Vertx vertx) throws Exception {
  SelfSignedCertificate caSignedCert = SelfSignedCertificate.create("localhost");
  SecurityTestUtils.configureJDKTrustStore(tempDir, caSignedCert);
  caValidFingerprint = certificateHexFingerprint(Paths.get(caSignedCert.keyCertOptions().getCertPath()));
  caValidServer = vertx
      .createHttpServer(new HttpServerOptions().setSsl(true).setPemKeyCertOptions(caSignedCert.keyCertOptions()))
      .requestHandler(context -> context.response().end("OK"));
  startServer(caValidServer);

  SelfSignedCertificate fooCert = SelfSignedCertificate.create("foo.com");
  fooFingerprint = certificateHexFingerprint(Paths.get(fooCert.keyCertOptions().getCertPath()));
  fooServer = vertx
      .createHttpServer(new HttpServerOptions().setSsl(true).setPemKeyCertOptions(fooCert.keyCertOptions()))
      .requestHandler(context -> context.response().end("OK"));
  startServer(fooServer);

  SelfSignedCertificate barCert = SelfSignedCertificate.create("bar.com");
  barFingerprint = certificateHexFingerprint(Paths.get(barCert.keyCertOptions().getCertPath()));
  barServer = vertx
      .createHttpServer(new HttpServerOptions().setSsl(true).setPemKeyCertOptions(barCert.keyCertOptions()))
      .requestHandler(context -> context.response().end("OK"));
  startServer(barServer);

  SelfSignedCertificate foobarCert = SelfSignedCertificate.create("foobar.com");
  foobarFingerprint = certificateHexFingerprint(Paths.get(foobarCert.keyCertOptions().getCertPath()));
  foobarServer = vertx
      .createHttpServer(new HttpServerOptions().setSsl(true).setPemKeyCertOptions(foobarCert.keyCertOptions()))
      .requestHandler(context -> context.response().end("OK"));
  startServer(foobarServer);
}
 
Example 27
Source Project: vertx-service-discovery   Source File: HttpEndpointTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testRecordCreation(TestContext testContext) {
  Record record = HttpEndpoint.createRecord("some-name", "123.456.789.111", 80, null);
  assertThat(record.getLocation().getString(Record.ENDPOINT)).isEqualTo("http://123.456.789.111:80/");

  record = HttpEndpoint.createRecord("some-name", "123.456.789.111", 80, "foo");
  assertThat(record.getLocation().getString(Record.ENDPOINT)).isEqualTo("http://123.456.789.111:80/foo");

  record = HttpEndpoint.createRecord("some-name", "123.456.789.111", 80, "foo", new JsonObject().put("language", "en"));
  assertThat(record.getLocation().getString(Record.ENDPOINT)).isEqualTo("http://123.456.789.111:80/foo");
  assertThat(record.getMetadata().getString("language")).isEqualTo("en");

  record = HttpEndpoint.createRecord("some-name", "acme.org");
  assertThat(record.getLocation().getString(Record.ENDPOINT)).isEqualTo("http://acme.org:80/");

  SelfSignedCertificate selfSignedCertificate = SelfSignedCertificate.create();
  vertx.createHttpServer(new HttpServerOptions()
    .setHost("127.0.0.1")
    .setSsl(true)
    .setKeyCertOptions(selfSignedCertificate.keyCertOptions())
  ).requestHandler(request -> {
    request.response().end(new JsonObject().put("url", request.absoluteURI()).encode());
  }).listen(0, testContext.asyncAssertSuccess(server -> {

    Record sslRecord = HttpEndpoint.createRecord("http-bin", true, "127.0.0.1", server.actualPort(), "/get", null);
    ServiceReference reference = discovery.getReferenceWithConfiguration(sslRecord, new HttpClientOptions()
      .setSsl(true)
      .setTrustAll(true)
      .setVerifyHost(false)
      .toJson());

    WebClient webClient = WebClient.wrap(reference.get());
    webClient.get("/get").as(BodyCodec.jsonObject()).send(testContext.asyncAssertSuccess(resp -> {
      assertEquals("https://127.0.0.1:" + server.actualPort() + "/get", resp.body().getString("url"));
    }));
  }));
}
 
Example 28
Source Project: kiqr   Source File: GenericHttpServerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void builderWithConfig(){
    RestKiqrServerVerticle.Builder builder = RestKiqrServerVerticle.Builder.serverBuilder(new KStreamBuilder(), new Properties());

    AbstractVerticle serverVerticle = builder.withOptions(new HttpServerOptions().setPort(4711)).build();
    assertThat(serverVerticle, is(instanceOf(RestKiqrServerVerticle.class)));

    RestKiqrServerVerticle server = (RestKiqrServerVerticle) serverVerticle;
    assertThat(server.serverOptions.getPort(), is(equalTo(4711)));

}
 
Example 29
Source Project: kiqr   Source File: CountQueryHttpServerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Before
public void setUp(TestContext context) throws Exception{
    rule.vertx().eventBus().registerDefaultCodec(StoreWideQuery.class, new KiqrCodec(StoreWideQuery.class));
    rule.vertx().eventBus().registerDefaultCodec(KeyValueStoreCountQuery.class, new KiqrCodec<>(KeyValueStoreCountQuery.class));


    rule.vertx().deployVerticle(new RestKiqrServerVerticle(new HttpServerOptions().setPort(5762), new DummySuccessfulVerticle()), context.asyncAssertSuccess());
}
 
Example 30
Source Project: kiqr   Source File: SessionWindowQueryHttpServerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Before
public void setUp(TestContext context) throws Exception{
    rule.vertx().eventBus().registerDefaultCodec(KeyBasedQuery.class, new KiqrCodec(KeyBasedQuery.class));
    rule.vertx().eventBus().registerDefaultCodec(SessionQueryResponse.class, new KiqrCodec<>(SessionQueryResponse.class));

    rule.vertx().deployVerticle(new RestKiqrServerVerticle(new HttpServerOptions().setPort(5762), new DummySuccessfulVerticle()), context.asyncAssertSuccess());
}