io.vertx.core.http.HttpServerOptions Java Examples

The following examples show how to use io.vertx.core.http.HttpServerOptions. 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: ServerRecordTest.java    From incubator-tuweni with 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 #2
Source File: ServiceEntryPoint.java    From vert.x-microservice with 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 #3
Source File: PullTest.java    From okapi with 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 #4
Source File: Ball.java    From demo-mesh-arena with 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 #5
Source File: JsonRpcHttpService.java    From besu with 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 #6
Source File: Main.java    From mewbase with 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 #7
Source File: ServerCaOrRecordTest.java    From cava with 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 #8
Source File: ExternalConfigurationTest.java    From vertx-micrometer-metrics with Apache License 2.0 6 votes vote down vote up
@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 #9
Source File: EthSigner.java    From ethsigner with 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 #10
Source File: EthSigner.java    From ethsigner with 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 #11
Source File: ExternalConfigurationTest.java    From vertx-micrometer-metrics with Apache License 2.0 6 votes vote down vote up
@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 #12
Source File: PrometheusMetricsITest.java    From vertx-micrometer-metrics with Apache License 2.0 6 votes vote down vote up
@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 #13
Source File: OkapiClientTest.java    From okapi with 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 #14
Source File: ServerTofaTest.java    From incubator-tuweni with 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 #15
Source File: VertxHttp11ClientReconnectTest.java    From feign-vertx with Apache License 2.0 6 votes vote down vote up
/**
 * 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 #16
Source File: HystrixDashboardVerticle.java    From standalone-hystrix-dashboard with MIT License 6 votes vote down vote up
/**
 * <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 #17
Source File: ClientWhitelistTest.java    From incubator-tuweni with 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 #18
Source File: VertxHttpRecorder.java    From quarkus with 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 #19
Source File: ServerCaOrRecordTest.java    From incubator-tuweni with 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 #20
Source File: ClientCaOrWhitelistTest.java    From cava with 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 #21
Source File: WebClientTest.java    From vertx-rx with 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 File: DataObjectTest.java    From vertx-codetrans with 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 #23
Source File: ClientRecordTest.java    From cava with 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 #24
Source File: MainVerticle.java    From nassh-relay with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void start(final Promise<Void> startPromise) {
    final JsonObject webserviceConfig = config().getJsonObject("webservice");
    if (webserviceConfig.containsKey("hostname")) {
        logger.warn("webservice.hostname will be deprecated in future releases, please use webservice.host instead");
        webserviceConfig.put("host", webserviceConfig.getString("hostname", webserviceConfig.getString("host")));
    }
    final HttpServerOptions options = new HttpServerOptions(webserviceConfig);
    if (options.isSsl() && options.getKeyCertOptions() == null) {
        logger.warn("no certificate configured, creating self-signed");
        final SelfSignedCertificate certificate = SelfSignedCertificate.create();
        options.setKeyCertOptions(certificate.keyCertOptions());
        options.setTrustOptions(certificate.trustOptions());
    }
    server = vertx.createHttpServer(options);
    final Router router = Router.router(vertx);
    router.route().handler(CorsHandler
        .create(".*")
        .allowCredentials(true)
    );
    router.get("/cookie").handler(new CookieHandler(config().getJsonObject("application").copy().put("auth", config().getJsonObject("google-sso"))));
    router.post("/cookie").handler(new CookiePostHandler(vertx, new JsonObject().put("auth", config().getJsonObject("google-sso"))));
    router.get("/proxy").handler(new ProxyHandler(vertx, config()));
    router.get("/write").handler(new WriteHandler(vertx));
    router.get("/read").handler(new ReadHandler(vertx));
    server.requestHandler(router);
    server.webSocketHandler(new ConnectHandler(vertx));
    server.listen(result -> {
            if (result.succeeded()) {
                logger.info("nassh-relay listening on port " + result.result().actualPort());
                startPromise.complete();
            } else {
                startPromise.fail(result.cause());
            }
        }
    );
}
 
Example #25
Source File: GrpcSslUtils.java    From quarkus with Apache License 2.0 5 votes vote down vote up
private static void createPemKeyCertOptions(Path certFile, Path keyFile,
        HttpServerOptions serverOptions) throws IOException {
    final byte[] cert = getFileContent(certFile);
    final byte[] key = getFileContent(keyFile);
    PemKeyCertOptions pemKeyCertOptions = new PemKeyCertOptions()
            .setCertValue(Buffer.buffer(cert))
            .setKeyValue(Buffer.buffer(key));
    serverOptions.setPemKeyCertOptions(pemKeyCertOptions);
}
 
Example #26
Source File: ClientCaOrRecordTest.java    From cava with 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 File: JUnitTest.java    From vertx-unit with Apache License 2.0 5 votes vote down vote up
@Before
public void before(TestContext context) {
  vertx = Vertx.vertx().exceptionHandler(context.exceptionHandler());
  vertx.createHttpServer(new HttpServerOptions().setReuseAddress(true)).
      requestHandler(req -> {
        requestCount.incrementAndGet();
        fail("Don't freak out");
      }).listen(8080, "localhost", context.asyncAssertSuccess(s -> {
  }));
}
 
Example #28
Source File: VertxHttpRecorder.java    From quarkus with Apache License 2.0 5 votes vote down vote up
private void setupUnixDomainSocketHttpServer(HttpServer httpServer, HttpServerOptions options, Future<Void> startFuture,
        AtomicInteger remainingCount) {
    httpServer.listen(SocketAddress.domainSocketAddress(options.getHost()), event -> {
        if (event.succeeded()) {
            if (remainingCount.decrementAndGet() == 0) {
                startFuture.complete(null);
            }
        } else {
            startFuture.fail(event.cause());
        }
    });
}
 
Example #29
Source File: VertxHttpRecorder.java    From quarkus with Apache License 2.0 5 votes vote down vote up
private static void createPemKeyCertOptions(Path certFile, Path keyFile,
        HttpServerOptions serverOptions) throws IOException {
    final byte[] cert = getFileContent(certFile);
    final byte[] key = getFileContent(keyFile);
    PemKeyCertOptions pemKeyCertOptions = new PemKeyCertOptions()
            .setCertValue(Buffer.buffer(cert))
            .setKeyValue(Buffer.buffer(key));
    serverOptions.setPemKeyCertOptions(pemKeyCertOptions);
}
 
Example #30
Source File: VertxHttpRecorder.java    From quarkus with Apache License 2.0 5 votes vote down vote up
public WebDeploymentVerticle(HttpServerOptions httpOptions, HttpServerOptions httpsOptions,
        HttpServerOptions domainSocketOptions, LaunchMode launchMode,
        HttpConfiguration.InsecureRequests insecureRequests) {
    this.httpOptions = httpOptions;
    this.httpsOptions = httpsOptions;
    this.launchMode = launchMode;
    this.domainSocketOptions = domainSocketOptions;
    this.insecureRequests = insecureRequests;
}