io.vertx.core.net.PemKeyCertOptions Java Examples

The following examples show how to use io.vertx.core.net.PemKeyCertOptions. 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: AmqpBridge.java    From strimzi-kafka-bridge with Apache License 2.0 6 votes vote down vote up
/**
 * Create an options instance for the ProtonClient
 *
 * @return ProtonClient options instance
 */
private ProtonClientOptions createClientOptions() {

    ProtonClientOptions options = new ProtonClientOptions();
    options.setConnectTimeout(1000);
    options.setReconnectAttempts(-1).setReconnectInterval(1000); // reconnect forever, every 1000 millisecs

    if (this.bridgeConfig.getAmqpConfig().getCertDir() != null && this.bridgeConfig.getAmqpConfig().getCertDir().length() > 0) {
        String certDir = this.bridgeConfig.getAmqpConfig().getCertDir();
        log.info("Enabling SSL configuration for AMQP with TLS certificates from {}", certDir);
        options.setSsl(true)
                .addEnabledSaslMechanism("EXTERNAL")
                .setHostnameVerificationAlgorithm("")
                .setPemTrustOptions(new PemTrustOptions()
                        .addCertPath(new File(certDir, "ca.crt").getAbsolutePath()))
                .setPemKeyCertOptions(new PemKeyCertOptions()
                        .addCertPath(new File(certDir, "tls.crt").getAbsolutePath())
                        .addKeyPath(new File(certDir, "tls.key").getAbsolutePath()));
    }

    return options;
}
 
Example #2
Source File: MQTTBroker.java    From vertx-mqtt-broker with Apache License 2.0 6 votes vote down vote up
private void startTcpServer(ConfigParser c) {
    int port = c.getPort();
    String keyPath = c.getTlsKeyPath();
    String certPath = c.getTlsCertPath();
    boolean tlsEnabled = c.isTlsEnabled();
    int idleTimeout = c.getSocketIdleTimeout();

    // MQTT over TCP
    NetServerOptions opt = new NetServerOptions()
            .setTcpKeepAlive(true)
            .setIdleTimeout(idleTimeout) // in seconds; 0 means "don't timeout".
            .setPort(port);

    if(tlsEnabled) {
        opt.setSsl(true).setPemKeyCertOptions(new PemKeyCertOptions()
            .setKeyPath(keyPath)
            .setCertPath(certPath)
        );
    }
    NetServer netServer = vertx.createNetServer(opt);
    Map<String, MQTTSession> sessions = new MonitoredMap<>();
    netServer.connectHandler(netSocket -> {
        MQTTNetSocket mqttNetSocket = new MQTTNetSocket(vertx, c, netSocket, sessions);
        mqttNetSocket.start();
    }).listen();
}
 
Example #3
Source File: VaultConfigStoreWithCertsTest.java    From vertx-config with Apache License 2.0 6 votes vote down vote up
@Override
protected JsonObject getRetrieverConfiguration() {

  JsonObject config = new JsonObject();
  config.put("host", process.getHost());
  config.put("port", process.getPort());
  config.put("ssl", true);
  PemKeyCertOptions options = new PemKeyCertOptions()
    .addCertPath("target/vault/config/ssl/client-cert.pem")
    .addKeyPath("target/vault/config/ssl/client-privatekey.pem");
  config.put("pemKeyCertOptions", options.toJson());

  PemTrustOptions trust = new PemTrustOptions()
    .addCertPath("target/vault/config/ssl/cert.pem");
  config.put("pemTrustStoreOptions", trust.toJson());

  JksOptions jks = new JksOptions()
    .setPath("target/vault/config/ssl/truststore.jks");
  config.put("trustStoreOptions", jks.toJson());

  config.put("auth-backend", "cert");

  return config;
}
 
Example #4
Source File: VaultClientWithCertTest.java    From vertx-config with Apache License 2.0 6 votes vote down vote up
/**
 * Tests authentication with the cert auth backend using PEM file
 */
@Test
public void testLoginByCert_usingPemConfig(TestContext tc) throws VaultException {
  JsonObject config = new JsonObject();
  config.put("host", process.getHost());
  config.put("port", process.getPort());
  config.put("ssl", true);
  PemKeyCertOptions options = new PemKeyCertOptions()
    .addCertPath("target/vault/config/ssl/client-cert.pem")
    .addKeyPath("target/vault/config/ssl/client-privatekey.pem");
  config.put("pemKeyCertOptions", options.toJson());

  PemTrustOptions trust = new PemTrustOptions()
    .addCertPath("target/vault/config/ssl/cert.pem");
  config.put("pemTrustStoreOptions", trust.toJson());

  JksOptions jks = new JksOptions()
    .setPath("target/vault/config/ssl/truststore.jks");
  config.put("trustStoreOptions", jks.toJson());

  client = new SlimVaultClient(vertx, config);

  checkWeCanLoginAndAccessRestrictedSecrets(tc);
}
 
Example #5
Source File: ZookeeperLeaderFinder.java    From strimzi-kafka-operator with Apache License 2.0 6 votes vote down vote up
/**
 * Validate the CO certificate and key passed in the given Secret
 * and return the PemKeyCertOptions for using it for TLS authentication.
 */
protected PemKeyCertOptions keyCertOptions(Secret coCertKeySecret) {
    CertAndKey coCertKey = Ca.asCertAndKey(coCertKeySecret,
                                        "cluster-operator.key", "cluster-operator.crt",
                                    "cluster-operator.p12", "cluster-operator.password");
    if (coCertKey == null) {
        throw Util.missingSecretException(coCertKeySecret.getMetadata().getNamespace(), coCertKeySecret.getMetadata().getName());
    }
    CertificateFactory x509 = x509Factory();
    try {
        x509.generateCertificate(new ByteArrayInputStream(coCertKey.cert()));
    } catch (CertificateException e) {
        throw corruptCertificate(coCertKeySecret, "cluster-operator.crt", e);
    }
    return new PemKeyCertOptions()
            .setCertValue(Buffer.buffer(coCertKey.cert()))
            .setKeyValue(Buffer.buffer(coCertKey.key()));
}
 
Example #6
Source File: AmqpBridge.java    From strimzi-kafka-bridge with Apache License 2.0 6 votes vote down vote up
/**
 * Create an options instance for the ProtonServer
 * based on AMQP-Kafka bridge internal configuration
 *
 * @return ProtonServer options instance
 */
private ProtonServerOptions createServerOptions() {

    ProtonServerOptions options = new ProtonServerOptions();
    options.setHost(this.bridgeConfig.getAmqpConfig().getHost());
    options.setPort(this.bridgeConfig.getAmqpConfig().getPort());

    if (this.bridgeConfig.getAmqpConfig().getCertDir() != null && this.bridgeConfig.getAmqpConfig().getCertDir().length() > 0) {
        String certDir = this.bridgeConfig.getAmqpConfig().getCertDir();
        log.info("Enabling SSL configuration for AMQP with TLS certificates from {}", certDir);
        options.setSsl(true)
                .setPemTrustOptions(new PemTrustOptions()
                        .addCertPath(new File(certDir, "ca.crt").getAbsolutePath()))
                .setPemKeyCertOptions(new PemKeyCertOptions()
                        .addCertPath(new File(certDir, "tls.crt").getAbsolutePath())
                        .addKeyPath(new File(certDir, "tls.key").getAbsolutePath()));
    }

    return options;
}
 
Example #7
Source File: MqttClientSslTest.java    From vertx-mqtt with Apache License 2.0 6 votes vote down vote up
@Before
public void before(TestContext ctx) {
  PemKeyCertOptions pemKeyCertOptions = new PemKeyCertOptions()
    .setKeyPath("tls/server-key.pem")
    .setCertPath("tls/server-cert.pem");

  MqttServerOptions serverOptions = new MqttServerOptions()
    .setPort(MQTT_SERVER_TLS_PORT)
    .setHost(MQTT_SERVER_HOST)
    .setKeyCertOptions(pemKeyCertOptions)
    .setSsl(true);

  server = MqttServer.create(vertx, serverOptions);
  server.exceptionHandler(t -> context.assertTrue(false));
  server.endpointHandler(e -> {
    log.info("Client connected");
    e.disconnectHandler(d -> log.info("Client disconnected"));
    e.accept(false);
  }).listen(ctx.asyncAssertSuccess());
}
 
Example #8
Source File: MySQLTLSTest.java    From vertx-sql-client with Apache License 2.0 6 votes vote down vote up
@Test
public void testSuccessWithVerifyCaSslMode(TestContext ctx) {
  options.setSslMode(SslMode.VERIFY_CA);
  options.setPemTrustOptions(new PemTrustOptions().addCertPath("tls/files/ca.pem"));
  options.setPemKeyCertOptions(new PemKeyCertOptions()
    .setCertPath("tls/files/client-cert.pem")
    .setKeyPath("tls/files/client-key.pem"));

  MySQLConnection.connect(vertx, options, ctx.asyncAssertSuccess(conn -> {
    ctx.assertTrue(conn.isSSL());
    conn.query("SELECT 1").execute(ctx.asyncAssertSuccess(res -> {
      ctx.assertEquals(1, res.size());
      conn.close();
    }));
  }));
}
 
Example #9
Source File: MySQLTLSTest.java    From vertx-sql-client with Apache License 2.0 6 votes vote down vote up
@Test
public void testSuccessWithPreferredSslMode(TestContext ctx) {
  options.setSslMode(SslMode.PREFERRED);
  options.setPemTrustOptions(new PemTrustOptions().addCertPath("tls/files/ca.pem"));
  options.setPemKeyCertOptions(new PemKeyCertOptions()
    .setCertPath("tls/files/client-cert.pem")
    .setKeyPath("tls/files/client-key.pem"));

  MySQLConnection.connect(vertx, options, ctx.asyncAssertSuccess(conn -> {
    ctx.assertTrue(conn.isSSL());
    conn.query("SELECT 1").execute(ctx.asyncAssertSuccess(res -> {
      ctx.assertEquals(1, res.size());
      conn.close();
    }));
  }));
}
 
Example #10
Source File: ClientProducers.java    From smallrye-reactive-messaging with Apache License 2.0 6 votes vote down vote up
@Produces
@Named("my-named-options")
public AmqpClientOptions getNamedOptions() {
    // You can use the produced options to configure the TLS connection
    PemKeyCertOptions keycert = new PemKeyCertOptions()
        .addCertPath("./tls/tls.crt")
        .addKeyPath("./tls/tls.key");
    PemTrustOptions trust =
        new PemTrustOptions().addCertPath("./tlc/ca.crt");

    return new AmqpClientOptions()
        .setSsl(true)
        .setPemKeyCertOptions(keycert)
        .setPemTrustOptions(trust)
        .addEnabledSaslMechanism("EXTERNAL")
        .setHostnameVerificationAlgorithm("")
        .setConnectTimeout(30000)
        .setReconnectInterval(5000)
        .setContainerId("my-container");
}
 
Example #11
Source File: MySQLTLSTest.java    From vertx-sql-client with Apache License 2.0 6 votes vote down vote up
@Test
public void testSuccessWithRequiredSslMode(TestContext ctx) {
  options.setSslMode(SslMode.REQUIRED);
  options.setPemTrustOptions(new PemTrustOptions().addCertPath("tls/files/ca.pem"));
  options.setPemKeyCertOptions(new PemKeyCertOptions()
    .setCertPath("tls/files/client-cert.pem")
    .setKeyPath("tls/files/client-key.pem"));

  MySQLConnection.connect(vertx, options, ctx.asyncAssertSuccess(conn -> {
    ctx.assertTrue(conn.isSSL());
    conn.query("SELECT 1").execute(ctx.asyncAssertSuccess(res -> {
      ctx.assertEquals(1, res.size());
      conn.close();
    }));
  }));
}
 
Example #12
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 #13
Source File: StaticHandlerTest.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
@Test
public void testHttp2Push() throws Exception {
  List<Http2PushMapping> mappings = new ArrayList<>();
  mappings.add(new Http2PushMapping("style.css", "style", false));
  mappings.add(new Http2PushMapping("coin.png", "image", false));
  stat.setHttp2PushMapping(mappings)
      .setWebRoot("webroot/somedir3");
  router.route().handler(stat);
  HttpServer http2Server = vertx.createHttpServer(new HttpServerOptions()
      .setUseAlpn(true)
      .setSsl(true)
      .setPemKeyCertOptions(new PemKeyCertOptions().setKeyPath("tls/server-key.pem").setCertPath("tls/server-cert.pem")));
  http2Server.requestHandler(router).listen(8443);

  HttpClientOptions options = new HttpClientOptions()
    .setSsl(true)
    .setUseAlpn(true)
    .setProtocolVersion(HttpVersion.HTTP_2)
    .setPemTrustOptions(new PemTrustOptions().addCertPath("tls/server-cert.pem"));
  HttpClient client = vertx.createHttpClient(options);
  CountDownLatch latch = new CountDownLatch(2);
  client.request(HttpMethod.GET, 8443, "localhost", "/testLinkPreload.html")
    .onComplete(onSuccess(resp -> {
      assertEquals(200, resp.statusCode());
      assertEquals(HttpVersion.HTTP_2, resp.version());
      resp.bodyHandler(this::assertNotNull);
    }))
    .pushHandler(pushedReq -> pushedReq.onComplete(onSuccess(pushedResp -> {
      assertNotNull(pushedResp);
      pushedResp.bodyHandler(this::assertNotNull);
      latch.countDown();
    })))
    .end();
  latch.await();
}
 
Example #14
Source File: StaticHandlerTest.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
@Test
public void testNoHttp2Push() throws Exception {
  stat.setWebRoot("webroot/somedir3");
  router.route().handler(stat);
  HttpServer http2Server = vertx.createHttpServer(new HttpServerOptions()
    .setUseAlpn(true)
    .setSsl(true)
    .setPemKeyCertOptions(new PemKeyCertOptions().setKeyPath("tls/server-key.pem").setCertPath("tls/server-cert.pem")));
  http2Server.requestHandler(router).listen(8443);

  HttpClientOptions options = new HttpClientOptions()
    .setSsl(true)
    .setUseAlpn(true)
    .setProtocolVersion(HttpVersion.HTTP_2)
    .setPemTrustOptions(new PemTrustOptions().addCertPath("tls/server-cert.pem"));
  HttpClient client = vertx.createHttpClient(options);
  client.request(HttpMethod.GET, 8443, "localhost", "/testLinkPreload.html")
    .onComplete(onSuccess(resp -> {
      assertEquals(200, resp.statusCode());
      assertEquals(HttpVersion.HTTP_2, resp.version());
      resp.bodyHandler(this::assertNotNull);
      testComplete();
    }))
    .pushHandler(pushedReq -> pushedReq.onComplete(pushedResp -> {
      fail();
    }))
    .end();
  await();
}
 
Example #15
Source File: RouterManagement.java    From enmasse with Apache License 2.0 5 votes vote down vote up
public static RouterManagement withCerts(Vertx vertx, String containerId, Duration connectTimeout, Duration queryTimeout, byte[] caCert, byte[] clientCert, byte[] clientKey) {
    ProtonClientOptions clientOptions = new ProtonClientOptions()
            .setSsl(true)
            .addEnabledSaslMechanism("EXTERNAL")
            .setHostnameVerificationAlgorithm("")
            .setPemTrustOptions(new PemTrustOptions()
                    .addCertValue(Buffer.buffer(caCert)))
            .setPemKeyCertOptions(new PemKeyCertOptions()
                    .addCertValue(Buffer.buffer(clientCert))
                    .addKeyValue(Buffer.buffer(clientKey)));
    return new RouterManagement(vertx, containerId, clientOptions, connectTimeout, queryTimeout);
}
 
Example #16
Source File: RouterManagement.java    From enmasse with Apache License 2.0 5 votes vote down vote up
public static RouterManagement withCertsInDir(Vertx vertx, String containerId, Duration connectTimeout, Duration queryTimeout, String certDir) {
    ProtonClientOptions clientOptions = new ProtonClientOptions()
            .setSsl(true)
            .addEnabledSaslMechanism("EXTERNAL")
            .setHostnameVerificationAlgorithm("")
            .setPemTrustOptions(new PemTrustOptions()
                    .addCertPath(new File(certDir, "ca.crt").getAbsolutePath()))
            .setPemKeyCertOptions(new PemKeyCertOptions()
                    .setCertPath(new File(certDir, "tls.crt").getAbsolutePath())
                    .setKeyPath(new File(certDir, "tls.key").getAbsolutePath()));
    return new RouterManagement(vertx, containerId, clientOptions, connectTimeout, queryTimeout);
}
 
Example #17
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 #18
Source File: MySQLTLSTest.java    From vertx-sql-client with Apache License 2.0 5 votes vote down vote up
@Test
public void testConnFailWithVerifyCaSslMode(TestContext ctx) {
  options.setSslMode(SslMode.VERIFY_CA);
  options.setTrustAll(true);
  options.setPemKeyCertOptions(new PemKeyCertOptions()
    .setCertPath("tls/files/client-cert.pem")
    .setKeyPath("tls/files/client-key.pem"));

  MySQLConnection.connect(vertx, options, ctx.asyncAssertFailure(error -> {
    ctx.assertEquals("Trust options must be specified under VERIFY_CA ssl-mode.", error.getMessage());
  }));
}
 
Example #19
Source File: VaultProcess.java    From vertx-config with Apache License 2.0 5 votes vote down vote up
public JsonObject getConfiguration() {
  JsonObject config = new JsonObject();
  config.put("host", getHost());
  config.put("port", getPort());
  config.put("ssl", true);
  PemKeyCertOptions options = new PemKeyCertOptions()
    .addCertPath("target/vault/config/ssl/client-cert.pem")
    .addKeyPath("target/vault/config/ssl/client-privatekey.pem");
  config.put("pemKeyCertOptions", options.toJson());
  JksOptions jks = new JksOptions()
    .setPath("target/vault/config/ssl/truststore.jks");
  config.put("trustStoreOptions", jks.toJson());
  return config;
}
 
Example #20
Source File: ConfigVaultExamples.java    From vertx-config with Apache License 2.0 5 votes vote down vote up
public void exampleWithCerts(Vertx vertx) {
  JsonObject vault_config = new JsonObject();

  // ...

  PemKeyCertOptions certs = new PemKeyCertOptions()
    .addCertPath("target/vault/config/ssl/client-cert.pem")
    .addKeyPath("target/vault/config/ssl/client-privatekey.pem");
  vault_config.put("pemKeyCertOptions", certs.toJson());

  PemTrustOptions trust = new PemTrustOptions()
    .addCertPath("target/vault/config/ssl/cert.pem");
  vault_config.put("pemTrustStoreOptions", trust.toJson());

  JksOptions jks = new JksOptions()
    .setPath("target/vault/config/ssl/truststore.jks");
  vault_config.put("trustStoreOptions", jks.toJson());

  vault_config.put("auth-backend", "cert");

  // Path to the secret to read.
  vault_config.put("path", "secret/my-secret");

  ConfigStoreOptions store = new ConfigStoreOptions()
    .setType("vault")
    .setConfig(vault_config);

  ConfigRetriever retriever = ConfigRetriever.create(vertx,
    new ConfigRetrieverOptions().addStore(store));
}
 
Example #21
Source File: ConfigVaultExamples.java    From vertx-config with Apache License 2.0 5 votes vote down vote up
public void example1WithConfig(Vertx vertx) {
  JsonObject vault_config = new JsonObject()
    .put("host", "127.0.0.1") // The host name
    .put("port", 8200) // The port
    .put("ssl", true); // Whether or not SSL is used (disabled by default)

  // Certificates
  PemKeyCertOptions certs = new PemKeyCertOptions()
    .addCertPath("target/vault/config/ssl/client-cert.pem")
    .addKeyPath("target/vault/config/ssl/client-privatekey.pem");
  vault_config.put("pemKeyCertOptions", certs.toJson());

  // Truststore
  JksOptions jks = new JksOptions()
    .setPath("target/vault/config/ssl/truststore.jks");
  vault_config.put("trustStoreOptions", jks.toJson());

  // Path to the secret to read.
  vault_config.put("path", "secret/my-secret");

  ConfigStoreOptions store = new ConfigStoreOptions()
    .setType("vault")
    .setConfig(vault_config);

  ConfigRetriever retriever = ConfigRetriever.create(vertx,
    new ConfigRetrieverOptions().addStore(store));
}
 
Example #22
Source File: HttpSslIT.java    From vertx-spring-boot with Apache License 2.0 5 votes vote down vote up
@Bean
public HttpServerOptionsCustomizer serverKeyCertCustomizer() {
    return options -> {
        PemKeyCertOptions cert = new PemKeyCertOptions()
            .setKeyPath(KEY_PATH)
            .setCertPath(CERT_PATH);

        options.setKeyCertOptions(cert);

        return options;
    };
}
 
Example #23
Source File: MySQLTLSTest.java    From vertx-sql-client with Apache License 2.0 5 votes vote down vote up
@Test
public void testPoolFailWithVerifyCaSslMode(TestContext ctx) {
  options.setSslMode(SslMode.VERIFY_CA);
  options.setTrustAll(true);
  options.setPemKeyCertOptions(new PemKeyCertOptions()
    .setCertPath("tls/files/client-cert.pem")
    .setKeyPath("tls/files/client-key.pem"));

  try {
    MySQLPool.pool(vertx, options, new PoolOptions());
  } catch (IllegalArgumentException e) {
    ctx.assertEquals("Trust options must be specified under VERIFY_CA ssl-mode.", e.getMessage());
  }
}
 
Example #24
Source File: MySQLTLSTest.java    From vertx-sql-client with Apache License 2.0 5 votes vote down vote up
@Test
public void testConnFailWithVerifyIdentitySslMode(TestContext ctx) {
  options.setSslMode(SslMode.VERIFY_IDENTITY);
  options.setPemTrustOptions(new PemTrustOptions().addCertPath("tls/files/ca.pem"));
  options.setPemKeyCertOptions(new PemKeyCertOptions()
    .setCertPath("tls/files/client-cert.pem")
    .setKeyPath("tls/files/client-key.pem"));

  MySQLConnection.connect(vertx, options, ctx.asyncAssertFailure(error -> {
    ctx.assertEquals("Host verification algorithm must be specified under VERIFY_IDENTITY ssl-mode.", error.getMessage());
  }));
}
 
Example #25
Source File: AbstractConfigTest.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Test a valid PEM configuration.
 */
@Test
public void testPemConfig() {
    cfg.setKeyPath(PREFIX_KEY_PATH + "auth-server-key.pem");
    cfg.setCertPath(PREFIX_KEY_PATH + "auth-server-cert.pem");

    final KeyCertOptions options = cfg.getKeyCertOptions();

    assertThat(options).isNotNull();
    assertThat(options).isInstanceOf(PemKeyCertOptions.class);
}
 
Example #26
Source File: MailConfig.java    From vertx-mail-client with Apache License 2.0 4 votes vote down vote up
public MailConfig setPemKeyCertOptions(PemKeyCertOptions options) {
  super.setPemKeyCertOptions(options);
  return this;
}
 
Example #27
Source File: EventBusBridgeWebsocketServerVerticle.java    From vertx-mqtt-broker with Apache License 2.0 4 votes vote down vote up
@Override
public void start() throws Exception {
    address = MQTTSession.ADDRESS;

    JsonObject conf = config();

    localBridgePort = conf.getInteger("local_bridge_port", 7007);
    idleTimeout = conf.getInteger("socket_idle_timeout", 120);
    ssl_cert_key = conf.getString("ssl_cert_key");
    ssl_cert = conf.getString("ssl_cert");
    ssl_trust = conf.getString("ssl_trust");


    // [WebSocket -> BUS] listen WebSocket publish to BUS
    HttpServerOptions opt = new HttpServerOptions()
            .setTcpKeepAlive(true)
            .setIdleTimeout(idleTimeout)
            .setPort(localBridgePort)
    ;

    if(ssl_cert_key != null && ssl_cert != null && ssl_trust != null) {
        opt.setSsl(true).setClientAuth(ClientAuth.REQUIRED)
            .setPemKeyCertOptions(new PemKeyCertOptions()
                .setKeyPath(ssl_cert_key)
                .setCertPath(ssl_cert)
            )
            .setPemTrustOptions(new PemTrustOptions()
                .addCertPath(ssl_trust)
            )
        ;
    }

    netServer = vertx.createHttpServer(opt);
    netServer.requestHandler(httpServerRequest -> httpServerRequest.response().end() );
    netServer.websocketHandler(sock -> {
        final EventBusWebsocketBridge ebnb = new EventBusWebsocketBridge(sock, vertx.eventBus(), address);
        sock.closeHandler(aVoid -> {
            logger.info("Bridge Server - closed connection from client ip: " + sock.remoteAddress());
            ebnb.stop();
        });
        sock.exceptionHandler(throwable -> {
            logger.error("Bridge Server - Exception: " + throwable.getMessage(), throwable);
            ebnb.stop();
        });

        logger.info("Bridge Server - new connection from client ip: " + sock.remoteAddress());

        RecordParser parser = ebnb.initialHandhakeProtocolParser();
        sock.handler(parser::handle);

    }).listen();
}
 
Example #28
Source File: EventBusBridgeServerVerticle.java    From vertx-mqtt-broker with Apache License 2.0 4 votes vote down vote up
@Override
public void start() throws Exception {
    address = MQTTSession.ADDRESS;

    JsonObject conf = config();

    localBridgePort = conf.getInteger("local_bridge_port", 7007);
    idleTimeout = conf.getInteger("socket_idle_timeout", 120);
    ssl_cert_key = conf.getString("ssl_cert_key");
    ssl_cert = conf.getString("ssl_cert");
    ssl_trust = conf.getString("ssl_trust");


    // [TCP -> BUS] listen TCP publish to BUS
    NetServerOptions opt = new NetServerOptions()
            .setTcpKeepAlive(true)
            .setIdleTimeout(idleTimeout)
            .setPort(localBridgePort)
    ;

    if(ssl_cert_key != null && ssl_cert != null && ssl_trust != null) {
        opt.setSsl(true).setClientAuth(ClientAuth.REQUIRED)
            .setPemKeyCertOptions(new PemKeyCertOptions()
                .setKeyPath(ssl_cert_key)
                .setCertPath(ssl_cert)
            )
            .setPemTrustOptions(new PemTrustOptions()
                .addCertPath(ssl_trust)
            )
        ;
    }

    netServer = vertx.createNetServer(opt);
    netServer.connectHandler(sock -> {
        final EventBusNetBridge ebnb = new EventBusNetBridge(sock, vertx.eventBus(), address);
        sock.closeHandler(aVoid -> {
            logger.info("Bridge Server - closed connection from client ip: " + sock.remoteAddress());
            ebnb.stop();
        });
        sock.exceptionHandler(throwable -> {
            logger.error("Bridge Server - Exception: " + throwable.getMessage(), throwable);
            ebnb.stop();
        });

        logger.info("Bridge Server - new connection from client ip: " + sock.remoteAddress());

        RecordParser parser = ebnb.initialHandhakeProtocolParser();
        sock.handler(parser::handle);

    }).listen();
}
 
Example #29
Source File: VxApiApplication.java    From VX-API-Gateway with MIT License 4 votes vote down vote up
/**
 * 创建https服务器
 * 
 * @param createHttp
 */
public void createHttpsServer(Handler<AsyncResult<Void>> createHttps) {
	this.httpsRouter = Router.router(vertx);
	httpsRouter.route().handler(this::filterBlackIP);
	httpsRouter.route().handler(CookieHandler.create());
	SessionStore sessionStore = null;
	if (vertx.isClustered()) {
		sessionStore = ClusteredSessionStore.create(vertx);
	} else {
		sessionStore = LocalSessionStore.create(vertx);
	}
	SessionHandler sessionHandler = SessionHandler.create(sessionStore);
	sessionHandler.setSessionCookieName(appOption.getSessionCookieName());
	sessionHandler.setSessionTimeout(appOption.getSessionTimeOut());
	httpsRouter.route().handler(sessionHandler);
	// 跨域处理
	if (corsOptions != null) {
		CorsHandler corsHandler = CorsHandler.create(corsOptions.getAllowedOrigin());
		if (corsOptions.getAllowedHeaders() != null) {
			corsHandler.allowedHeaders(corsOptions.getAllowedHeaders());
		}
		corsHandler.allowCredentials(corsOptions.isAllowCredentials());
		if (corsOptions.getExposedHeaders() != null) {
			corsHandler.exposedHeaders(corsOptions.getExposedHeaders());
		}
		if (corsOptions.getAllowedMethods() != null) {
			corsHandler.allowedMethods(corsOptions.getAllowedMethods());
		}
		corsHandler.maxAgeSeconds(corsOptions.getMaxAgeSeconds());
		httpsRouter.route().handler(corsHandler);
	}
	// 创建https服务器
	serverOptions.setSsl(true);
	VxApiCertOptions certOptions = serverOptions.getCertOptions();
	if (certOptions.getCertType().equalsIgnoreCase("pem")) {
		serverOptions
				.setPemKeyCertOptions(new PemKeyCertOptions().setCertPath(certOptions.getCertPath()).setKeyPath(certOptions.getCertKey()));
	} else if (certOptions.getCertType().equalsIgnoreCase("pfx")) {
		serverOptions.setPfxKeyCertOptions(new PfxOptions().setPath(certOptions.getCertPath()).setPassword(certOptions.getCertKey()));
	} else {
		LOG.error("创建https服务器-->失败:无效的证书类型,只支持pem/pfx格式的证书");
		createHttps.handle(Future.failedFuture("创建https服务器-->失败:无效的证书类型,只支持pem/pfx格式的证书"));
		return;
	}
	Future<Boolean> createFuture = Future.future();
	vertx.fileSystem().exists(certOptions.getCertPath(), createFuture);
	createFuture.setHandler(check -> {
		if (check.succeeded()) {
			if (check.result()) {
				// 404页面
				httpsRouter.route().order(999999).handler(rct -> {
					if (LOG.isDebugEnabled()) {
						LOG.debug(
								"用户: " + rct.request().remoteAddress().host() + "请求的了不存的路径: " + rct.request().method() + ":" + rct.request().path());
					}
					HttpServerResponse response = rct.response();
					if (appOption.getNotFoundContentType() != null) {
						response.putHeader("Content-Type", appOption.getNotFoundContentType());
					}
					response.end(appOption.getNotFoundResult());
				});
				// 如果在linux系统开启epoll
				if (vertx.isNativeTransportEnabled()) {
					serverOptions.setTcpFastOpen(true).setTcpCork(true).setTcpQuickAck(true).setReusePort(true);
				}
				vertx.createHttpServer(serverOptions).requestHandler(httpsRouter::accept).listen(serverOptions.getHttpsPort(), res -> {
					if (res.succeeded()) {
						System.out.println(appOption.getAppName() + " Running on port " + serverOptions.getHttpsPort() + " by HTTPS");
						createHttps.handle(Future.succeededFuture());
					} else {
						System.out.println("create HTTPS Server failed : " + res.cause());
						createHttps.handle(Future.failedFuture(res.cause()));
					}
				});
			} else {
				LOG.error("执行创建https服务器-->失败:无效的证书或者错误的路径:如果证书存放在conf/cert中,路径可以从cert/开始,示例:cert/XXX.XXX");
				createHttps.handle(Future.failedFuture("无效的证书或者错误的路径"));
			}
		} else {
			LOG.error("执行创建https服务器-->失败:无效的证书或者错误的路径:如果证书存放在conf/cert中,路径可以从cert/开始,示例:cert/XXX.XXX", check.cause());
			createHttps.handle(Future.failedFuture(check.cause()));
		}
	});
}
 
Example #30
Source File: ProtonClientOptions.java    From vertx-proton with Apache License 2.0 4 votes vote down vote up
@Override
public ProtonClientOptions setPemKeyCertOptions(PemKeyCertOptions options) {
  super.setPemKeyCertOptions(options);
  return this;
}