Java Code Examples for io.vertx.core.http.HttpServerOptions#setPort()

The following examples show how to use io.vertx.core.http.HttpServerOptions#setPort() . 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: 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 2
Source File: HandlerTest.java    From orion with Apache License 2.0 6 votes vote down vote up
private void setupClientServer(final Router router) throws Exception {
  final HttpUrl clientHTTP =
      new HttpUrl.Builder().scheme("http").host("localhost").port(clientHTTPServerPort).build();
  clientBaseUrl = clientHTTP.toString();

  final HttpServerOptions privateServerOptions = new HttpServerOptions();
  privateServerOptions.setPort(clientHTTPServerPort);

  final CompletableAsyncCompletion completion = AsyncCompletion.incomplete();
  clientHttpServer = vertx.createHttpServer(privateServerOptions).requestHandler(router::accept).listen(result -> {
    if (result.succeeded()) {
      completion.complete();
    } else {
      completion.completeExceptionally(result.cause());
    }
  });
  completion.join();
}
 
Example 3
Source File: PortCustomizer.java    From vertx-spring-boot with Apache License 2.0 5 votes vote down vote up
@Override
public HttpServerOptions apply(HttpServerOptions options) {
    if (factory.getPort() >= 0) {
        options.setPort(factory.getPort());
    }

    return options;
}
 
Example 4
Source File: HandlerTest.java    From orion with Apache License 2.0 5 votes vote down vote up
private void setupNodeServer(final Router router) throws Exception {
  final HttpServerOptions publicServerOptions = new HttpServerOptions();
  publicServerOptions.setPort(nodeHTTPServerPort);

  final CompletableAsyncCompletion completion = AsyncCompletion.incomplete();
  nodeHttpServer = vertx.createHttpServer(publicServerOptions).requestHandler(router::accept).listen(result -> {
    if (result.succeeded()) {
      completion.complete();
    } else {
      completion.completeExceptionally(result.cause());
    }
  });
  completion.join();
}
 
Example 5
Source File: NubesServer.java    From nubes with Apache License 2.0 5 votes vote down vote up
@Override
public void init(Vertx vertx, Context context) {
  super.init(vertx, context);
  JsonObject config = context.config();
  options = new HttpServerOptions();
  options.setHost(config.getString("host", "localhost"));
  options.setPort(config.getInteger("port", 9000));
  nubes = new VertxNubes(vertx, config);
}
 
Example 6
Source File: TestBase.java    From vertx-sse with Apache License 2.0 5 votes vote down vote up
@BeforeEach
public void createServer(VertxTestContext context) {
	vertx = Vertx.vertx();
	HttpServerOptions options = new HttpServerOptions();
	options.setHost(HOST);
	options.setPort(PORT);
	server = vertx.createHttpServer(options);
	Router router = Router.router(vertx);
	sseHandler = SSEHandler.create();
	sseHandler.connectHandler(connection -> {
		final HttpServerRequest request = connection.request();
		final String token = request.getParam("token");
		if (token == null) {
			connection.reject(401);
		} else if (!TOKEN.equals(token)) {
			connection.reject(403);
		} else {
			this.connection = connection; // accept
		}
	});
	sseHandler.closeHandler(connection -> {
		if (this.connection != null) {
			this.connection = null;
		}
	});
	router.get("/sse").handler(sseHandler);
	addBridge(router);
	server.requestHandler(router);
	server.listen(context.completing());
}
 
Example 7
Source File: IntegrationTestBase.java    From ethsigner with Apache License 2.0 4 votes vote down vote up
static void setupEthSigner(final long chainId, final String downstreamHttpRequestPath)
    throws IOException, CipherException {
  clientAndServer = startClientAndServer();

  final File keyFile = createKeyFile();
  final File passwordFile = createFile("password");
  credentials = WalletUtils.loadCredentials("password", keyFile);

  final TransactionSignerProvider transactionSignerProvider =
      new SingleTransactionSignerProvider(transactionSigner(keyFile, passwordFile));

  final HttpClientOptions httpClientOptions = new HttpClientOptions();
  httpClientOptions.setDefaultHost(LOCALHOST);
  httpClientOptions.setDefaultPort(clientAndServer.getLocalPort());

  final HttpServerOptions httpServerOptions = new HttpServerOptions();
  httpServerOptions.setPort(0);
  httpServerOptions.setHost("localhost");

  // Force TransactionDeserialisation to fail
  final ObjectMapper jsonObjectMapper = new ObjectMapper();
  jsonObjectMapper.configure(DeserializationFeature.FAIL_ON_NULL_CREATOR_PROPERTIES, true);
  jsonObjectMapper.configure(DeserializationFeature.FAIL_ON_MISSING_CREATOR_PROPERTIES, true);

  final JsonDecoder jsonDecoder = new JsonDecoder(jsonObjectMapper);

  vertx = Vertx.vertx();
  runner =
      new Runner(
          chainId,
          transactionSignerProvider,
          httpClientOptions,
          httpServerOptions,
          downstreamTimeout,
          new DownstreamPathCalculator(downstreamHttpRequestPath),
          jsonDecoder,
          dataPath,
          vertx,
          singletonList("sample.com"));
  runner.start();

  final Path portsFile = dataPath.resolve(PORTS_FILENAME);
  waitForNonEmptyFileToExist(portsFile);
  final int ethSignerPort = httpJsonRpcPort(portsFile);
  RestAssured.port = ethSignerPort;

  LOG.info(
      "Started ethSigner on port {}, eth stub node on port {}",
      ethSignerPort,
      clientAndServer.getLocalPort());

  unlockedAccount =
      transactionSignerProvider.availableAddresses().stream().findAny().orElseThrow();
}
 
Example 8
Source File: TlsEnabledHttpServerFactory.java    From ethsigner with Apache License 2.0 4 votes vote down vote up
public HttpServer create(
    final TlsCertificateDefinition serverCert,
    final TlsCertificateDefinition acceptedClientCerts,
    final Path workDir) {
  try {

    final Path serverFingerprintFile = workDir.resolve("server_known_clients");
    populateFingerprintFile(serverFingerprintFile, acceptedClientCerts, Optional.empty());

    final HttpServerOptions web3HttpServerOptions = new HttpServerOptions();
    web3HttpServerOptions.setSsl(true);
    web3HttpServerOptions.setClientAuth(ClientAuth.REQUIRED);
    web3HttpServerOptions.setTrustOptions(
        VertxTrustOptions.whitelistClients(serverFingerprintFile));
    web3HttpServerOptions.setPort(0);
    web3HttpServerOptions.setPfxKeyCertOptions(
        new PfxOptions()
            .setPath(serverCert.getPkcs12File().toString())
            .setPassword(serverCert.getPassword()));

    final Router router = Router.router(vertx);
    final JsonDecoder jsonDecoder = createJsonDecoder();
    final RequestMapper requestMapper = new RequestMapper(new MockBalanceReporter());
    router
        .route(HttpMethod.POST, "/")
        .produces(HttpHeaderValues.APPLICATION_JSON.toString())
        .handler(BodyHandler.create())
        .handler(ResponseContentTypeHandler.create())
        .failureHandler(new JsonRpcErrorHandler(new HttpResponseFactory(), jsonDecoder))
        .handler(new JsonRpcHandler(null, requestMapper, jsonDecoder));

    final HttpServer web3ProviderHttpServer = vertx.createHttpServer(web3HttpServerOptions);

    final CompletableFuture<Boolean> serverConfigured = new CompletableFuture<>();
    web3ProviderHttpServer
        .requestHandler(router)
        .listen(result -> serverConfigured.complete(true));

    serverConfigured.get();

    serversCreated.add(web3ProviderHttpServer);
    return web3ProviderHttpServer;
  } catch (final KeyStoreException
      | NoSuchAlgorithmException
      | CertificateException
      | IOException
      | ExecutionException
      | InterruptedException e) {
    throw new RuntimeException("Failed to construct a TLS Enabled Server", e);
  }
}
 
Example 9
Source File: TlsEnabledHttpServerFactory.java    From besu with Apache License 2.0 4 votes vote down vote up
HttpServer create(
    final TlsCertificateDefinition serverCert,
    final TlsCertificateDefinition acceptedClientCerts,
    final Path workDir,
    final boolean tlsEnabled) {
  try {

    final Path serverFingerprintFile = workDir.resolve("server_known_clients");
    populateFingerprintFile(serverFingerprintFile, acceptedClientCerts, Optional.empty());

    final HttpServerOptions web3HttpServerOptions = new HttpServerOptions();
    web3HttpServerOptions.setPort(0);
    if (tlsEnabled) {
      web3HttpServerOptions.setSsl(true);
      web3HttpServerOptions.setClientAuth(ClientAuth.REQUIRED);
      web3HttpServerOptions.setTrustOptions(
          VertxTrustOptions.whitelistClients(serverFingerprintFile));
      web3HttpServerOptions.setPfxKeyCertOptions(
          new PfxOptions()
              .setPath(serverCert.getPkcs12File().toString())
              .setPassword(serverCert.getPassword()));
    }
    final Router router = Router.router(vertx);
    router
        .route(HttpMethod.GET, "/upcheck")
        .produces(HttpHeaderValues.APPLICATION_JSON.toString())
        .handler(TlsEnabledHttpServerFactory::handleRequest);

    final HttpServer mockOrionHttpServer = vertx.createHttpServer(web3HttpServerOptions);

    final CompletableFuture<Boolean> serverConfigured = new CompletableFuture<>();
    mockOrionHttpServer.requestHandler(router).listen(result -> serverConfigured.complete(true));

    serverConfigured.get();

    serversCreated.add(mockOrionHttpServer);
    return mockOrionHttpServer;
  } catch (final KeyStoreException
      | NoSuchAlgorithmException
      | CertificateException
      | IOException
      | ExecutionException
      | InterruptedException e) {
    throw new RuntimeException("Failed to construct a TLS Enabled Server", e);
  }
}
 
Example 10
Source File: BrokerManageExportServer.java    From joyqueue with Apache License 2.0 4 votes vote down vote up
protected RoutingVerticle initRoutingVerticle(BrokerManageConfig config) {
    HttpServerOptions httpServerOptions = new HttpServerOptions();
    httpServerOptions.setPort(config.getExportPort());
    return new RoutingVerticle(new Environment.MapEnvironment(), httpServerOptions);
}
 
Example 11
Source File: VertxHttpServerFactory.java    From graviteeio-access-management with Apache License 2.0 4 votes vote down vote up
@Override
public HttpServer getObject() throws Exception {
    HttpServerOptions options = new HttpServerOptions();

    // Binding port
    options.setPort(httpServerConfiguration.getPort());
    options.setHost(httpServerConfiguration.getHost());

    // Netty pool buffers must be enabled by default
    options.setUsePooledBuffers(true);

    if (httpServerConfiguration.isSecured()) {
        options.setSsl(httpServerConfiguration.isSecured());
        options.setUseAlpn(httpServerConfiguration.isAlpn());

        if (httpServerConfiguration.getClientAuth() == VertxHttpServerConfiguration.ClientAuthMode.NONE) {
            options.setClientAuth(ClientAuth.NONE);
        } else if (httpServerConfiguration.getClientAuth() == VertxHttpServerConfiguration.ClientAuthMode.REQUEST) {
            options.setClientAuth(ClientAuth.REQUEST);
        } else if (httpServerConfiguration.getClientAuth() == VertxHttpServerConfiguration.ClientAuthMode.REQUIRED) {
            options.setClientAuth(ClientAuth.REQUIRED);
        }

        if (httpServerConfiguration.getTrustStorePath() != null) {
            if (httpServerConfiguration.getTrustStoreType() == null || httpServerConfiguration.getTrustStoreType().isEmpty() ||
                    httpServerConfiguration.getTrustStoreType().equalsIgnoreCase(CERTIFICATE_FORMAT_JKS)) {
                options.setTrustStoreOptions(new JksOptions()
                        .setPath(httpServerConfiguration.getTrustStorePath())
                        .setPassword(httpServerConfiguration.getTrustStorePassword()));
            } else if (httpServerConfiguration.getTrustStoreType().equalsIgnoreCase(CERTIFICATE_FORMAT_PEM)) {
                options.setPemTrustOptions(new PemTrustOptions()
                        .addCertPath(httpServerConfiguration.getTrustStorePath()));
            } else if (httpServerConfiguration.getTrustStoreType().equalsIgnoreCase(CERTIFICATE_FORMAT_PKCS12)) {
                options.setPfxTrustOptions(new PfxOptions()
                        .setPath(httpServerConfiguration.getTrustStorePath())
                        .setPassword(httpServerConfiguration.getTrustStorePassword()));
            }
        }

        if (httpServerConfiguration.getKeyStorePath() != null) {
            if (httpServerConfiguration.getKeyStoreType() == null || httpServerConfiguration.getKeyStoreType().isEmpty() ||
                    httpServerConfiguration.getKeyStoreType().equalsIgnoreCase(CERTIFICATE_FORMAT_JKS)) {
                options.setKeyStoreOptions(new JksOptions()
                        .setPath(httpServerConfiguration.getKeyStorePath())
                        .setPassword(httpServerConfiguration.getKeyStorePassword()));
            } else if (httpServerConfiguration.getKeyStoreType().equalsIgnoreCase(CERTIFICATE_FORMAT_PEM)) {
                options.setPemKeyCertOptions(new PemKeyCertOptions()
                        .addCertPath(httpServerConfiguration.getKeyStorePath()));
            } else if (httpServerConfiguration.getKeyStoreType().equalsIgnoreCase(CERTIFICATE_FORMAT_PKCS12)) {
                options.setPfxKeyCertOptions(new PfxOptions()
                        .setPath(httpServerConfiguration.getKeyStorePath())
                        .setPassword(httpServerConfiguration.getKeyStorePassword()));
            }
        }
    }

    // Customizable configuration
    options.setCompressionSupported(httpServerConfiguration.isCompressionSupported());
    options.setIdleTimeout(httpServerConfiguration.getIdleTimeout());
    options.setTcpKeepAlive(httpServerConfiguration.isTcpKeepAlive());

    return vertx.createHttpServer(options);
}
 
Example 12
Source File: VertxHttpServerFactory.java    From gravitee-gateway with Apache License 2.0 4 votes vote down vote up
@Override
public HttpServer getObject() throws Exception {
    HttpServerOptions options = new HttpServerOptions();

    // Binding port
    options.setPort(httpServerConfiguration.getPort());
    options.setHost(httpServerConfiguration.getHost());

    // Netty pool buffers must be enabled by default
    options.setUsePooledBuffers(true);

    if (httpServerConfiguration.isSecured()) {
        options.setSsl(httpServerConfiguration.isSecured());
        options.setUseAlpn(httpServerConfiguration.isAlpn());

        if (httpServerConfiguration.isClientAuth() == VertxHttpServerConfiguration.ClientAuthMode.NONE) {
            options.setClientAuth(ClientAuth.NONE);
        } else if (httpServerConfiguration.isClientAuth() == VertxHttpServerConfiguration.ClientAuthMode.REQUEST) {
            options.setClientAuth(ClientAuth.REQUEST);
        } else if (httpServerConfiguration.isClientAuth() == VertxHttpServerConfiguration.ClientAuthMode.REQUIRED) {
            options.setClientAuth(ClientAuth.REQUIRED);
        }

        if (httpServerConfiguration.getTrustStorePath() != null) {
            if (httpServerConfiguration.getTrustStoreType() == null || httpServerConfiguration.getTrustStoreType().isEmpty() ||
                    httpServerConfiguration.getTrustStoreType().equalsIgnoreCase(CERTIFICATE_FORMAT_JKS)) {
                options.setTrustStoreOptions(new JksOptions()
                        .setPath(httpServerConfiguration.getTrustStorePath())
                        .setPassword(httpServerConfiguration.getTrustStorePassword()));
            } else if (httpServerConfiguration.getTrustStoreType().equalsIgnoreCase(CERTIFICATE_FORMAT_PEM)) {
                options.setPemTrustOptions(new PemTrustOptions()
                        .addCertPath(httpServerConfiguration.getTrustStorePath()));
            } else if (httpServerConfiguration.getTrustStoreType().equalsIgnoreCase(CERTIFICATE_FORMAT_PKCS12)) {
                options.setPfxTrustOptions(new PfxOptions()
                        .setPath(httpServerConfiguration.getTrustStorePath())
                        .setPassword(httpServerConfiguration.getTrustStorePassword()));
            }
        }

        if (httpServerConfiguration.getKeyStorePath() != null) {
            if (httpServerConfiguration.getKeyStoreType() == null || httpServerConfiguration.getKeyStoreType().isEmpty() ||
                    httpServerConfiguration.getKeyStoreType().equalsIgnoreCase(CERTIFICATE_FORMAT_JKS)) {
                options.setKeyStoreOptions(new JksOptions()
                        .setPath(httpServerConfiguration.getKeyStorePath())
                        .setPassword(httpServerConfiguration.getKeyStorePassword()));
            } else if (httpServerConfiguration.getKeyStoreType().equalsIgnoreCase(CERTIFICATE_FORMAT_PEM)) {
                options.setPemKeyCertOptions(new PemKeyCertOptions()
                        .addCertPath(httpServerConfiguration.getKeyStorePath()));
            } else if (httpServerConfiguration.getKeyStoreType().equalsIgnoreCase(CERTIFICATE_FORMAT_PKCS12)) {
                options.setPfxKeyCertOptions(new PfxOptions()
                        .setPath(httpServerConfiguration.getKeyStorePath())
                        .setPassword(httpServerConfiguration.getKeyStorePassword()));
            }
        }
    }

    options.setHandle100ContinueAutomatically(true);
    
    // Customizable configuration
    options.setCompressionSupported(httpServerConfiguration.isCompressionSupported());
    options.setIdleTimeout(httpServerConfiguration.getIdleTimeout());
    options.setTcpKeepAlive(httpServerConfiguration.isTcpKeepAlive());
    options.setMaxChunkSize(httpServerConfiguration.getMaxChunkSize());
    options.setMaxHeaderSize(httpServerConfiguration.getMaxHeaderSize());

    // Configure websocket
    System.setProperty("vertx.disableWebsockets", Boolean.toString(!httpServerConfiguration.isWebsocketEnabled()));

    return vertx.createHttpServer(options);
}
 
Example 13
Source File: TestVerticle.java    From nubes with Apache License 2.0 4 votes vote down vote up
@Override
public void start(Future<Void> startFuture) throws Exception {
  HttpServerOptions options = new HttpServerOptions();
  options.setPort(PORT);
  options.setHost(HOST);
  HttpServer server = vertx.createHttpServer(options);
  JsonObject config = createTestConfig();
  config.put("templates", new JsonArray().add("mvel").add("hbs"));
  //config.put("relectionprovider", "reflections");
  nubes = new VertxNubes(vertx, config);
  nubes.registerService(DOG_SERVICE_NAME, dogService);
  nubes.registerService(SNOOPY_SERVICE_NAME, SNOOPY);
  nubes.registerServiceProxy(new ParrotServiceImpl());
  if (nubes.getService(DOG_SERVICE_NAME) == null) {
    startFuture.fail("Services should not be null");
    return;
  }
  List<Locale> locales = new ArrayList<>();
  locales.add(Locale.FRENCH);
  locales.add(Locale.US);
  locales.add(Locale.JAPANESE);
  locales.add(Locale.ENGLISH);
  nubes.setAvailableLocales(locales);
  nubes.setDefaultLocale(Locale.GERMAN);
  nubes.setAuthProvider(new MockAuthProvider());
  nubes.registerInterceptor("setDateBefore", context -> {
    context.response().headers().add("X-Date-Before", Long.toString(new Date().getTime()));
    context.next();
  });
  nubes.registerInterceptor("setDateAfter", context -> {
    context.response().headers().add("X-Date-After", Long.toString(new Date().getTime()));
    context.next();
  });
  nubes.registerTemplateEngine("hbs", HandlebarsTemplateEngine.create());
  nubes.bootstrap(onSuccessOnly(startFuture, router -> {
    server.requestHandler(router::accept);
    server.listen(res -> {
      if (res.failed()) {
        startFuture.fail(res.cause());
        return;
      }
      startFuture.complete();
    });
  }));
}
 
Example 14
Source File: TestVerticle.java    From vertx-sse with Apache License 2.0 4 votes vote down vote up
private HttpServerOptions serverOptions() {
	final HttpServerOptions options = new HttpServerOptions();
	options.setHost(HOST);
	options.setPort(PORT);
	return options;
}