Java 类io.vertx.core.net.PemKeyCertOptions 实例源码

项目:vertx-zero    文件:PemCert.java   
@Override
public Handler<TCPSSLOptions> parse(final JsonObject options) {
    return Fn.get(() -> {
        final PemKeyCertOptions pem = Fn.getSemi(
                null == options ||
                        !options.containsKey(PATH_KEY) ||
                        !options.containsKey(PATH_CERT), LOGGER,
                Cert.SERVER_PEM,
                () -> new PemKeyCertOptions().setKeyPath(PATH_KEY).setCertPath(PATH_CERT)
        );
        return option -> option
                .setSsl(true)
                .setUseAlpn(true)
                .setPemKeyCertOptions(pem)
                .setOpenSslEngineOptions(new OpenSSLEngineOptions());
    }, options);
}
项目:DAVe    文件:GrpcPersistenceService.java   
private void setGrpcSslOptions(TCPSSLOptions sslOptions) {
    PemTrustOptions pemTrustOptions = new PemTrustOptions();
    this.config.getSslTrustCerts()
            .forEach(trustKey -> pemTrustOptions.addCertValue(Buffer.buffer(trustKey)));
    sslOptions
            .setSsl(true)
            .setUseAlpn(true)
            .setPemTrustOptions(pemTrustOptions);
    final String sslCert = this.config.getSslCert();
    final String sslKey = this.config.getSslKey();
    if (sslKey != null && sslCert != null) {
        PemKeyCertOptions pemKeyCertOptions = new PemKeyCertOptions()
                .setKeyValue(Buffer.buffer(sslKey))
                .setCertValue(Buffer.buffer(sslCert));
        sslOptions.setPemKeyCertOptions(pemKeyCertOptions);
    }
}
项目:DAVe    文件:ApiVerticle.java   
private void setSsl(HttpServerOptions httpServerOptions) {
    ApiConfig.SslConfig sslConfig = config.getSsl();
    if (!sslConfig.isEnable()) {
        return;
    }
    httpServerOptions.setSsl(true);
    PemKeyCertOptions pemKeyCertOptions = new PemKeyCertOptions()
            .setKeyValue(Buffer.buffer(sslConfig.getSslKey()))
            .setCertValue(Buffer.buffer(sslConfig.getSslCert()));
    httpServerOptions.setPemKeyCertOptions(pemKeyCertOptions);

    PemTrustOptions pemTrustOptions = new PemTrustOptions();
    Arrays.stream(sslConfig.getSslTrustCerts())
            .map(Object::toString)
            .forEach(trustKey -> pemTrustOptions.addCertValue(Buffer.buffer(trustKey)));
    if (!pemTrustOptions.getCertValues().isEmpty()) {
        httpServerOptions.setPemTrustOptions(pemTrustOptions);
        ClientAuth clientAuth = sslConfig.isSslRequireClientAuth() ?
                ClientAuth.REQUIRED : ClientAuth.REQUEST;
        httpServerOptions.setClientAuth(clientAuth);
    }
}
项目:vertx-mqtt    文件:MqttServerSslTest.java   
@Before
public void before(TestContext context) {

  PemKeyCertOptions pemKeyCertOptions = new PemKeyCertOptions()
    .setKeyPath("tls/server-key.pem")
    .setCertPath("tls/server-cert.pem");

  MqttServerOptions options = new MqttServerOptions()
    .setPort(MQTT_SERVER_TLS_PORT)
    .setKeyCertOptions(pemKeyCertOptions)
    .setSsl(true);

  // just useful for enabling decryption using Wireshark (which doesn't support default Diffie-Hellmann for key exchange)
  // options.addEnabledCipherSuite("TLS_RSA_WITH_AES_256_CBC_SHA256");

  this.setUp(context, options);
}
项目:vertx-config    文件:VaultClientWithCertTest.java   
/**
 * 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);
}
项目:vertx-config    文件:VaultConfigStoreWithCertsTest.java   
@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;
}
项目:enmasse    文件:HTTPServer.java   
private void createSecureServer(VertxRequestHandler requestHandler, Future<Void> startPromise) {
    if (new File(certDir).exists()) {
        HttpServerOptions options = new HttpServerOptions();
        File keyFile = new File(certDir, "tls.key");
        File certFile = new File(certDir, "tls.crt");
        log.info("Loading key from " + keyFile.getAbsolutePath() + ", cert from " + certFile.getAbsolutePath());
        options.setKeyCertOptions(new PemKeyCertOptions()
                .setKeyPath(keyFile.getAbsolutePath())
                .setCertPath(certFile.getAbsolutePath()));
        options.setSsl(true);

        httpsServer = vertx.createHttpServer(options)
                .requestHandler(requestHandler)
                .listen(SECURE_PORT, ar -> {
                    if (ar.succeeded()) {
                        log.info("Started HTTPS server. Listening on port " + SECURE_PORT);
                        startPromise.complete();
                    } else {
                        log.info("Error starting HTTPS server");
                        startPromise.fail(ar.cause());
                    }
                });
    } else {
        startPromise.complete();
    }
}
项目:enmasse    文件:MqttLwt.java   
/**
 * Create an options instance for the ProtonClient
 *
 * @return  ProtonClient options instance
 */
private ProtonClientOptions createClientOptions() {

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

    if (certDir != null) {
        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;
}
项目:amqp-kafka-bridge    文件:AmqpBridge.java   
/**
 * 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.bridgeConfigProperties.getEndpointConfigProperties().getCertDir() != null && this.bridgeConfigProperties.getEndpointConfigProperties().getCertDir().length() > 0) {
        String certDir = this.bridgeConfigProperties.getEndpointConfigProperties().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;
}
项目:vertx-mqtt-broker    文件:MQTTBroker.java   
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();
}
项目:DAVe    文件:ApiVerticleTest.java   
@Test
public void testSslClientAuthentication(TestContext context) {
    JsonObject config = TestConfig.getApiConfig();
    deployApiVerticle(context, config);

    final Async asyncSslClient = context.async();

    HttpClientOptions sslOpts = new HttpClientOptions().setSsl(true)
            .setPemTrustOptions(TestConfig.HTTP_API_CERTIFICATE.trustOptions());

    vertx.createHttpClient(sslOpts).get(port, "localhost", "/api/v1.0/pr/latest", res -> {
        context.assertEquals(200, res.statusCode());
        asyncSslClient.complete();
    }).end();

    final Async asyncSslClientAuth = context.async();
    HttpClientOptions sslClientAuthOpts = new HttpClientOptions().setSsl(true)
            .setPemTrustOptions(TestConfig.HTTP_API_CERTIFICATE.trustOptions())
            .setPemKeyCertOptions(new PemKeyCertOptions()
                    .setKeyPath(TestConfig.HTTP_CLIENT_CERTIFICATE.privateKeyPath())
                    .setCertPath(TestConfig.HTTP_CLIENT_CERTIFICATE.certificatePath()));

    vertx.createHttpClient(sslClientAuthOpts).get(port, "localhost", "/api/v1.0/pr/latest", res -> {
        context.assertEquals(200, res.statusCode());
        asyncSslClientAuth.complete();
    }).end();

    final Async asyncClient = context.async();

    vertx.createHttpClient().get(port, "localhost", "/api/v1.0/pr/latest", res ->
        context.fail("Connected to HTTPS connection with HTTP!")
    ).exceptionHandler(res ->
        asyncClient.complete()
    ).end();
}
项目:DAVe    文件:ApiVerticleTest.java   
@Test
public void testSslRequiredClientAuthentication(TestContext context) {
    JsonObject config = TestConfig.getApiConfig();
    config.getJsonObject("ssl").put("sslRequireClientAuth", true);
    deployApiVerticle(context, config);

    final Async asyncSslClient = context.async();

    HttpClientOptions sslOpts = new HttpClientOptions().setSsl(true)
            .setPemTrustOptions(TestConfig.HTTP_API_CERTIFICATE.trustOptions());

    vertx.createHttpClient(sslOpts).get(port, "localhost", "/api/v1.0/pr/latest", res ->
        context.fail("Connected without client authentication!")
    ).exceptionHandler(res ->
        asyncSslClient.complete()
    ).end();

    final Async asyncSslClientAuth = context.async();
    HttpClientOptions sslClientAuthOpts = new HttpClientOptions().setSsl(true)
            .setPemTrustOptions(TestConfig.HTTP_API_CERTIFICATE.trustOptions())
            .setPemKeyCertOptions(new PemKeyCertOptions()
                    .setKeyPath(TestConfig.HTTP_CLIENT_CERTIFICATE.privateKeyPath())
                    .setCertPath(TestConfig.HTTP_CLIENT_CERTIFICATE.certificatePath()));

    vertx.createHttpClient(sslClientAuthOpts).get(port, "localhost", "/api/v1.0/pr/latest", res -> {
        context.assertEquals(200, res.statusCode());
        asyncSslClientAuth.complete();
    }).end();

    final Async asyncClient = context.async();

    vertx.createHttpClient().get(port, "localhost", "/api/v1.0/pr/latest", res ->
        context.fail("Connected to HTTPS connection with HTTP!")
    ).exceptionHandler(res ->
        asyncClient.complete()
    ).end();
}
项目:hono    文件:AbstractConfigTest.java   
/**
 * Test a valid PEM configuration.
 */
@Test
public void testPemConfig() {
    final TestConfig cfg = new TestConfig();
    cfg.setKeyPath(PREFIX_KEY_PATH + "hono-messaging-key.pem");
    cfg.setCertPath(PREFIX_KEY_PATH + "hono-messaging-cert.pem");

    final KeyCertOptions options = cfg.getKeyCertOptions();

    Assert.assertNotNull(options);
    Assert.assertThat(options, instanceOf(PemKeyCertOptions.class));
}
项目:vertx-mqtt    文件:MqttClientSslTest.java   
@Before
public void before() {
  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.endpointHandler(e -> {
    log.info("Client connected");
    e.disconnectHandler(d -> log.info("Client disconnected"));
    e.accept(false);
  }).listen(ar -> {
    if (ar.succeeded()) {
      log.info("MQTT server listening on port " + ar.result().actualPort());
    } else {
      log.error("Error starting MQTT server", ar.cause());
      System.exit(1);
    }
  });

  server.exceptionHandler(t -> context.assertTrue(false));
}
项目:vertx-config    文件:Examples.java   
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));
}
项目:vertx-config    文件:Examples.java   
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));
}
项目:vertx-config    文件:VaultProcess.java   
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;
}
项目:enmasse    文件:Main.java   
private static ProtonClientOptions createClientOptions(String certDir)
{
    ProtonClientOptions options = new ProtonClientOptions();

    if (certDir != null) {
        options.setSsl(true)
                .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 options;
}
项目:enmasse    文件:Forwarder.java   
private ProtonClientOptions getOptions() {
    ProtonClientOptions options = new ProtonClientOptions();
    if (certDir != null) {
        options.setHostnameVerificationAlgorithm("")
                .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 options;
}
项目:enmasse    文件:Main.java   
private static ProtonServerOptions createOptionsForTls(final String certDir) {
    ProtonServerOptions options = new ProtonServerOptions();
    PemKeyCertOptions pemKeyCertOptions = new PemKeyCertOptions();
    pemKeyCertOptions.setCertPath(certDir + File.separator + "tls.crt");
    pemKeyCertOptions.setKeyPath(certDir + File.separator + "tls.key");
    options.setPemKeyCertOptions(pemKeyCertOptions);
    options.setClientAuth(ClientAuth.REQUIRED);
    options.setSsl(true);
    PemTrustOptions pemTrustOptions = new PemTrustOptions();
    pemTrustOptions.addCertPath(certDir + File.separator + "ca.crt");
    options.setPemTrustOptions(pemTrustOptions);
    return options;
}
项目:enmasse    文件:MqttGateway.java   
/**
 * Start the MQTT server component
 *
 * @param startFuture
 */
private void bindMqttServer(Future<Void> startFuture) {

    MqttServerOptions options = new MqttServerOptions();
    options.setHost(this.bindAddress).setPort(this.listenPort);

    if (this.ssl) {

        PemKeyCertOptions pemKeyCertOptions = new PemKeyCertOptions()
                .setKeyPath(this.keyFile)
                .setCertPath(this.certFile);

        options.setKeyCertOptions(pemKeyCertOptions)
                .setSsl(this.ssl);

        LOG.info("SSL/TLS support enabled key {} cert {}", this.keyFile, this.certFile);
    }

    this.server = MqttServer.create(this.vertx, options);

    this.server
            .endpointHandler(this::handleMqttEndpointConnection)
            .listen(done -> {

                if (done.succeeded()) {

                    this.bridges = new HashMap<>();

                    LOG.info("MQTT gateway running on {}:{}", this.bindAddress, this.server.actualPort());
                    LOG.info("AMQP messaging service on {}:{}", this.messagingServiceHost, this.messagingServicePort);
                    startFuture.complete();
                } else {
                    LOG.error("Error while starting up MQTT gateway", done.cause());
                    startFuture.fail(done.cause());
                }

            });
}
项目:enmasse    文件:AmqpServer.java   
@Override
public void start() {
    ProtonServerOptions options = new ProtonServerOptions();
    if(useTls) {
        options.setSsl(true);
        String path;
        if((path = config.get("jksKeyStorePath")) != null) {
            final JksOptions jksOptions = new JksOptions();
            jksOptions.setPath(path);
            jksOptions.setPassword(config.get("keyStorePassword"));
            options.setKeyStoreOptions(jksOptions);
        } else if((path = config.get("pfxKeyStorePath")) != null) {
            final PfxOptions pfxOptions = new PfxOptions();
            pfxOptions.setPath(path);
            pfxOptions.setPassword(config.get("keyStorePassword"));
            options.setPfxKeyCertOptions(pfxOptions);
        } else if((path = config.get("pemCertificatePath")) != null) {
            final PemKeyCertOptions pemKeyCertOptions = new PemKeyCertOptions();
            pemKeyCertOptions.setCertPath(path);
            pemKeyCertOptions.setKeyPath(config.get("pemKeyPath"));
            options.setPemKeyCertOptions(pemKeyCertOptions);
        } else {
            // use JDK settings?
        }

    }
    server = ProtonServer.create(vertx, options);

    server.saslAuthenticatorFactory(() -> new SaslAuthenticator(keycloakSessionFactory, config, useTls));
    server.connectHandler(this::connectHandler);
    LOG.info("Starting server on "+hostname+":"+ port);
    server.listen(port, hostname, event -> {
        if(event.failed())
        {
            LOG.error("Unable to listen for AMQP on "+hostname+":" + port, event.cause());
        }

    });
}
项目:vertx-web    文件:StaticHandlerTest.java   
@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::accept).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);
  HttpClientRequest request = client.get(8443, "localhost", "/testLinkPreload.html", resp -> {
    assertEquals(200, resp.statusCode());
    assertEquals(HttpVersion.HTTP_2, resp.version());
    resp.bodyHandler(this::assertNotNull);
    testComplete();
  });
  request.pushHandler(pushedReq -> pushedReq.handler(pushedResp -> {
    fail();
  }));
  request.end();
  await();
}
项目:vertx-web    文件:StaticHandlerTest.java   
@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::accept).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);
  HttpClientRequest request = client.get(8443, "localhost", "/testLinkPreload.html", resp -> {
    assertEquals(200, resp.statusCode());
    assertEquals(HttpVersion.HTTP_2, resp.version());
    resp.bodyHandler(this::assertNotNull);
  });
  CountDownLatch latch = new CountDownLatch(2);
  request.pushHandler(pushedReq -> pushedReq.handler(pushedResp -> {
    assertNotNull(pushedResp);
    pushedResp.bodyHandler(this::assertNotNull);
    latch.countDown();
  }));
  request.end();
  latch.await();
}
项目:vertx-mqtt-broker    文件:MQTTBroker.java   
private void startWebsocketServer(ConfigParser c) {
    int port = c.getPort();
    String wsSubProtocols = c.getWsSubProtocols();
    String keyPath = c.getTlsKeyPath();
    String certPath = c.getTlsCertPath();
    boolean tlsEnabled = c.isTlsEnabled();
    int idleTimeout = c.getSocketIdleTimeout();

    HttpServerOptions httpOpt = new HttpServerOptions()
            .setTcpKeepAlive(true)
            .setIdleTimeout(idleTimeout) // in seconds; 0 means "don't timeout".
            .setWebsocketSubProtocols(wsSubProtocols)
            .setPort(port);
    if(tlsEnabled) {
        httpOpt.setSsl(true);
        httpOpt.setPemKeyCertOptions(new PemKeyCertOptions()
            .setKeyPath(keyPath)
            .setCertPath(certPath)
        );
    }
    HttpServer http = vertx.createHttpServer(httpOpt);
    Map<String, MQTTSession> sessions = new MonitoredMap<>();
    http.websocketHandler(serverWebSocket -> {
        MQTTWebSocket mqttWebSocket = new MQTTWebSocket(vertx, c, serverWebSocket, sessions);
        mqttWebSocket.start();
    }).listen();
}
项目:reactive-pg-client    文件:PgConnectOptions.java   
@Override
public PgConnectOptions setPemKeyCertOptions(PemKeyCertOptions options) {
  return (PgConnectOptions)super.setPemKeyCertOptions(options);
}
项目:vertx-mqtt    文件:VertxMqttServerExamples.java   
/**
 * Example for handling client connection using SSL/TLS
 * @param vertx
 */
public void example3(Vertx vertx) {

  MqttServerOptions options = new MqttServerOptions()
    .setPort(8883)
    .setKeyCertOptions(new PemKeyCertOptions()
      .setKeyPath("./src/test/resources/tls/server-key.pem")
      .setCertPath("./src/test/resources/tls/server-cert.pem"))
    .setSsl(true);

  MqttServer mqttServer = MqttServer.create(vertx, options);
  mqttServer.endpointHandler(endpoint -> {

    // shows main connect info
    System.out.println("MQTT client [" + endpoint.clientIdentifier() + "] request to connect, clean session = " + endpoint.isCleanSession());

    if (endpoint.auth() != null) {
      System.out.println("[username = " + endpoint.auth().userName() + ", password = " + endpoint.auth().password() + "]");
    }
    if (endpoint.will() != null) {
      System.out.println("[will topic = " + endpoint.will().willTopic() + " msg = " + endpoint.will().willMessage() +
        " QoS = " + endpoint.will().willQos() + " isRetain = " + endpoint.will().isWillRetain() + "]");
    }

    System.out.println("[keep alive timeout = " + endpoint.keepAliveTimeSeconds() + "]");

    // accept connection from the remote client
    endpoint.accept(false);

  })
    .listen(ar -> {

      if (ar.succeeded()) {

        System.out.println("MQTT server is listening on port " + ar.result().actualPort());
      } else {

        System.out.println("Error on starting the server");
        ar.cause().printStackTrace();
      }
    });
}
项目:vertx-mqtt    文件:MqttServerOptions.java   
@Override
public MqttServerOptions setPemKeyCertOptions(PemKeyCertOptions options) {
  super.setPemKeyCertOptions(options);
  return this;
}
项目:vertx-mqtt    文件:MqttClientOptions.java   
@Override
public MqttClientOptions setPemKeyCertOptions(PemKeyCertOptions options) {
   super.setPemKeyCertOptions(options);
   return this;
}
项目:enmasse    文件:QueueScheduler.java   
@Override
public void start() {
    ProtonServerOptions options = new ProtonServerOptions();
    if (certDir != null) {
        options.setSsl(true)
            .setClientAuth(ClientAuth.REQUIRED)
            .setPemKeyCertOptions(new PemKeyCertOptions()
                    .setKeyPath(new File(certDir, "tls.key").getAbsolutePath())
                    .setCertPath(new File(certDir, "tls.crt").getAbsolutePath()))
            .setPemTrustOptions(new PemTrustOptions()
                    .addCertPath(new File(certDir, "ca.crt").getAbsolutePath()));
    }

    server = ProtonServer.create(vertx, options);
    server.saslAuthenticatorFactory(saslAuthenticatorFactory);
    server.connectHandler(connection -> {
        connection.setContainer("queue-scheduler");
        connection.openHandler(result -> {
            connection.open();
            connectionOpened(connection);
        }).closeHandler(conn -> {
            log.info("Broker connection " + connection.getRemoteContainer() + " closed");
            executeBlocking(() -> schedulerState.brokerRemoved(getGroupId(connection), connection.getRemoteContainer()),
                    "Error removing broker");
            connection.close();
            connection.disconnect();
        }).disconnectHandler(protonConnection -> {
            log.info("Broker connection " + connection.getRemoteContainer() + " disconnected");
            executeBlocking(() -> schedulerState.brokerRemoved(getGroupId(connection), connection.getRemoteContainer()),
                    "Error removing broker");
            connection.disconnect();
        });
    });

    server.listen(port, event -> {
        if (event.succeeded()) {
            log.info("QueueScheduler is up and running");
        } else {
            log.error("Error starting queue scheduler", event.cause());
        }
    });
}
项目:enmasse    文件:DispatchRouterJ.java   
private ProtonServer startServer(Future<Void> startPromise, String certDir, boolean isRouteContainer) {
    ProtonServerOptions serverOptions = new ProtonServerOptions();
    if (certDir != null) {
        serverOptions
                .setPemKeyCertOptions(new PemKeyCertOptions()
                        .addKeyPath(certDir + "/tls.key")
                        .addCertPath(certDir + "/tls.crt"))
                .setPemTrustOptions(new PemTrustOptions()
                        .addCertPath(certDir + "/ca.crt"))
                .setSsl(true);

    }
    ProtonServer server = ProtonServer.create(vertx, serverOptions);
    if (certDir != null) {
        server.saslAuthenticatorFactory(ExternalSaslAuthenticator::new);
    }
    server.connectHandler(connection -> {
        connection.sessionOpenHandler(ProtonSession::open);
        connection.receiverOpenHandler(this::receiverOpen);
        connection.senderOpenHandler(this::senderOpen);
        connection.openHandler(ar -> connectionOpen(ar, isRouteContainer));
        connection.disconnectHandler(conn -> {
            log.info("Connection disconnected!");
            connection.disconnect();
        });
        connection.closeHandler(handle -> {
            log.info("Connection closing!");
            connection.close();
            connection.disconnect();
        });
        connection.setContainer("dispatch-router-j");
    }).listen(0, "localhost", result -> {
        if (result.succeeded()) {
            log.info("Started server on port {}", server.actualPort());
            startPromise.complete();
        } else {
            startPromise.fail(result.cause());
        }
    });
    return server;
}
项目:vertx-rest-client    文件:RestClientOptions.java   
@Override
public RestClientOptions setPemKeyCertOptions(PemKeyCertOptions options) {
    super.setPemKeyCertOptions(options);
    return this;
}
项目:vertx-shell    文件:TelnetTermOptions.java   
@Override
public TelnetTermOptions setPemKeyCertOptions(PemKeyCertOptions options) {
  return (TelnetTermOptions) super.setPemKeyCertOptions(options);
}
项目:vertx-shell    文件:HttpTermOptions.java   
@Override
public HttpTermOptions setPemKeyCertOptions(PemKeyCertOptions options) {
  return (HttpTermOptions) super.setPemKeyCertOptions(options);
}
项目:vertx-amqp-bridge    文件:AmqpBridgeOptions.java   
@Override
public AmqpBridgeOptions setPemKeyCertOptions(PemKeyCertOptions options) {
  super.setPemKeyCertOptions(options);
  return this;
}
项目:vertx-proton    文件:ProtonServerOptions.java   
@Override
public ProtonServerOptions setPemKeyCertOptions(PemKeyCertOptions options) {
  super.setPemKeyCertOptions(options);
  return this;
}
项目:vertx-proton    文件:ProtonClientOptions.java   
@Override
public ProtonClientOptions setPemKeyCertOptions(PemKeyCertOptions options) {
  super.setPemKeyCertOptions(options);
  return this;
}
项目:vertx-web    文件:WebClientOptions.java   
@Override
public WebClientOptions setPemKeyCertOptions(PemKeyCertOptions options) {
  return (WebClientOptions) super.setPemKeyCertOptions(options);
}
项目:vertx-mqtt-broker    文件:EventBusBridgeServerVerticle.java   
@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();
}
项目:vertx-mqtt-broker    文件:EventBusBridgeWebsocketServerVerticle.java   
@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.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();
}