Example usage for io.vertx.core.net PemKeyCertOptions PemKeyCertOptions

List of usage examples for io.vertx.core.net PemKeyCertOptions PemKeyCertOptions

Introduction

In this page you can find the example usage for io.vertx.core.net PemKeyCertOptions PemKeyCertOptions.

Prototype

public PemKeyCertOptions() 

Source Link

Document

Default constructor

Usage

From source file:com.hurence.logisland.engine.vanilla.stream.amqp.AmqpClientPipelineStream.java

License:Apache License

private CompletableFuture<ProtonConnection> setupConnection() {
    CompletableFuture<ProtonConnection> completableFuture = new CompletableFuture<>();
    String hostname = streamContext.getPropertyValue(StreamOptions.CONNECTION_HOST).asString();
    int port = streamContext.getPropertyValue(StreamOptions.CONNECTION_PORT).asInteger();
    int credits = streamContext.getPropertyValue(StreamOptions.LINK_CREDITS).asInteger();

    String user = streamContext.getPropertyValue(StreamOptions.CONNECTION_AUTH_USERNAME).asString();
    String password = streamContext.getPropertyValue(StreamOptions.CONNECTION_AUTH_PASSWORD).asString();
    if (user != null && password != null) {
        options.addEnabledSaslMechanism("PLAIN");
    } else if (streamContext.getPropertyValue(StreamOptions.CONNECTION_AUTH_TLS_CERT).isSet()) {
        String tlsCert = streamContext.getPropertyValue(StreamOptions.CONNECTION_AUTH_TLS_CERT).asString();
        String tlsKey = streamContext.getPropertyValue(StreamOptions.CONNECTION_AUTH_TLS_KEY).asString();
        String caCert = streamContext.getPropertyValue(StreamOptions.CONNECTION_AUTH_CA_CERT).asString();
        options.addEnabledSaslMechanism("EXTERNAL").setHostnameVerificationAlgorithm("")
                .setPemKeyCertOptions(new PemKeyCertOptions().addCertPath(new File(tlsCert).getAbsolutePath())
                        .addKeyPath(new File(tlsKey).getAbsolutePath()));
        if (caCert != null) {
            options.setPemTrustOptions(new PemTrustOptions().addCertPath(new File(caCert).getAbsolutePath()));
        }//ww w .  j a  v  a2  s  .  co m

    }
    protonClient.connect(options, hostname, port, user, password, event -> {
        if (event.failed()) {
            handleConnectionFailure(false);
            completableFuture.completeExceptionally(event.cause());
            return;
        }
        connectionControl.connected();
        completableFuture.complete(event.result());
        protonConnection = event.result();
        String containerId = streamContext.getPropertyValue(StreamOptions.CONTAINER_ID).asString();
        if (containerId != null) {
            protonConnection.setContainer(containerId);
        }
        protonConnection.closeHandler(x -> {
            handleConnectionFailure(true);
        }).disconnectHandler(x -> {
            handleConnectionFailure(false);
        }).openHandler(onOpen -> {

            //setup the output path
            sender = protonConnection
                    .createSender(streamContext.getPropertyValue(StreamOptions.WRITE_TOPIC).asString());
            sender.setAutoDrained(true);
            sender.setAutoSettle(true);
            sender.open();

            //setup the input path
            receiver = protonConnection
                    .createReceiver(streamContext.getPropertyValue(StreamOptions.READ_TOPIC).asString());
            receiver.setPrefetch(credits);
            receiver.handler((delivery, message) -> {
                try {
                    Record record;
                    if (deserializer == null) {
                        record = RecordUtils.getKeyValueRecord(
                                StringUtils.defaultIfEmpty(message.getSubject(), ""),
                                new String(extractBodyContent(message.getBody())));
                    } else {
                        record = deserializer
                                .deserialize(new ByteArrayInputStream(extractBodyContent(message.getBody())));
                        if (!record.hasField(FieldDictionary.RECORD_KEY)) {
                            record.setField(FieldDictionary.RECORD_KEY, FieldType.STRING, message.getSubject());
                        }
                    }

                    Collection<Record> r = Collections.singleton(record);
                    for (ProcessContext processContext : streamContext.getProcessContexts()) {
                        r = processContext.getProcessor().process(processContext, r);
                    }
                    List<Message> toAdd = new ArrayList<>();
                    for (Record out : r) {
                        ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream();
                        serializer.serialize(byteOutputStream, out);
                        Message mo = ProtonHelper.message();
                        if (out.hasField(FieldDictionary.RECORD_KEY)) {
                            mo.setSubject(out.getField(FieldDictionary.RECORD_KEY).asString());
                        }
                        if (StringUtils.isNotBlank(contentType)) {
                            mo.setContentType(contentType);
                        }
                        mo.setMessageId(out.getId());
                        mo.setBody(new Data(Binary.create(ByteBuffer.wrap(byteOutputStream.toByteArray()))));
                        toAdd.add(mo);
                    }
                    toAdd.forEach(sender::send);
                    delivery.disposition(Accepted.getInstance(), true);
                } catch (Exception e) {
                    Rejected rejected = new Rejected();
                    delivery.disposition(rejected, true);
                    getLogger().warn("Unable to process message : " + e.getMessage());
                }
            }).open();

        }).open();

    });
    return completableFuture;
}

From source file:de.braintags.netrelay.NetRelay.java

License:Open Source License

private void importCertificate(HttpServerOptions httpOpts) {
    String certPath = settings.getCertificatePath();
    String password = settings.getCertificatePassword();

    if (certPath.matches("^.*\\.(pem|PEM)$")) {
        // Use a PEM key/cert pair
        if (settings.getCertificateKeyPath() == null) {
            throw new IllegalArgumentException("The certificateKeyPath is not set for pem certificate");
        }/*  w w w .  jav  a2 s  .co  m*/
        httpOpts.setPemKeyCertOptions(
                new PemKeyCertOptions().setCertPath(certPath).setKeyPath(settings.getCertificateKeyPath()));
        httpOpts.setSsl(true);
    } else {
        throw new IllegalArgumentException("Please specify the certificate as PEM file in the format pkcs8");
    }

}

From source file:examples.ConfigVaultExamples.java

License:Apache License

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));
}

From source file:examples.ConfigVaultExamples.java

License:Apache License

public void exampleWithCerts(Vertx vertx) {
    JsonObject vault_config = new JsonObject();

    // .../*ww  w  .j av a 2  s.c  o  m*/

    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));
}

From source file:examples.NetExamples.java

License:Open Source License

public void example21(Vertx vertx) {
    NetServerOptions options = new NetServerOptions().setSsl(true).setPemKeyCertOptions(new PemKeyCertOptions()
            .setKeyPath("/path/to/your/server-key.pem").setCertPath("/path/to/your/server-cert.pem"));
    NetServer server = vertx.createNetServer(options);
}

From source file:examples.NetExamples.java

License:Open Source License

public void example22(Vertx vertx) {
    Buffer myKeyAsABuffer = vertx.fileSystem().readFileBlocking("/path/to/your/server-key.pem");
    Buffer myCertAsABuffer = vertx.fileSystem().readFileBlocking("/path/to/your/server-cert.pem");
    PemKeyCertOptions pemOptions = new PemKeyCertOptions().setKeyValue(myKeyAsABuffer)
            .setCertValue(myCertAsABuffer);
    NetServerOptions options = new NetServerOptions().setSsl(true).setPemKeyCertOptions(pemOptions);
    NetServer server = vertx.createNetServer(options);
}

From source file:examples.NetExamples.java

License:Open Source License

public void example40(Vertx vertx) {
    NetClientOptions options = new NetClientOptions().setSsl(true).setPemKeyCertOptions(new PemKeyCertOptions()
            .setKeyPath("/path/to/your/client-key.pem").setCertPath("/path/to/your/client-cert.pem"));
    NetClient client = vertx.createNetClient(options);
}

From source file:examples.NetExamples.java

License:Open Source License

public void example41(Vertx vertx) {
    Buffer myKeyAsABuffer = vertx.fileSystem().readFileBlocking("/path/to/your/client-key.pem");
    Buffer myCertAsABuffer = vertx.fileSystem().readFileBlocking("/path/to/your/client-cert.pem");
    PemKeyCertOptions pemOptions = new PemKeyCertOptions().setKeyValue(myKeyAsABuffer)
            .setCertValue(myCertAsABuffer);
    NetClientOptions options = new NetClientOptions().setSsl(true).setPemKeyCertOptions(pemOptions);
    NetClient client = vertx.createNetClient(options);
}

From source file:examples.VertxMqttServerExamples.java

License:Apache License

/**
 * Example for handling client connection using SSL/TLS
 * @param vertx//  w  w  w .j  a  v  a  2  s  . c om
 */
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();
        }
    });
}

From source file:io.gravitee.gateway.http.connector.VertxHttpClient.java

License:Apache License

@Override
protected void doStart() throws Exception {
    httpClientOptions = new HttpClientOptions();

    httpClientOptions.setPipelining(endpoint.getHttpClientOptions().isPipelining());
    httpClientOptions.setKeepAlive(endpoint.getHttpClientOptions().isKeepAlive());
    httpClientOptions.setIdleTimeout((int) (endpoint.getHttpClientOptions().getIdleTimeout() / 1000));
    httpClientOptions.setConnectTimeout((int) endpoint.getHttpClientOptions().getConnectTimeout());
    httpClientOptions.setUsePooledBuffers(true);
    httpClientOptions.setMaxPoolSize(endpoint.getHttpClientOptions().getMaxConcurrentConnections());
    httpClientOptions.setTryUseCompression(endpoint.getHttpClientOptions().isUseCompression());
    httpClientOptions.setLogActivity(true);

    // Configure proxy
    HttpProxy proxy = endpoint.getHttpProxy();
    if (proxy != null && proxy.isEnabled()) {
        ProxyOptions proxyOptions = new ProxyOptions();
        proxyOptions.setHost(proxy.getHost());
        proxyOptions.setPort(proxy.getPort());
        proxyOptions.setUsername(proxy.getUsername());
        proxyOptions.setPassword(proxy.getPassword());
        proxyOptions.setType(ProxyType.valueOf(proxy.getType().name()));

        httpClientOptions.setProxyOptions(proxyOptions);
    }//w ww  .j a va  2  s  .c om

    URI target = URI.create(endpoint.getTarget());
    HttpClientSslOptions sslOptions = endpoint.getHttpClientSslOptions();

    if (HTTPS_SCHEME.equalsIgnoreCase(target.getScheme())) {
        // Configure SSL
        httpClientOptions.setSsl(true);

        if (sslOptions != null) {
            httpClientOptions.setVerifyHost(sslOptions.isHostnameVerifier())
                    .setTrustAll(sslOptions.isTrustAll());

            // Client trust configuration
            if (!sslOptions.isTrustAll() && sslOptions.getTrustStore() != null) {
                switch (sslOptions.getTrustStore().getType()) {
                case PEM:
                    PEMTrustStore pemTrustStore = (PEMTrustStore) sslOptions.getTrustStore();
                    PemTrustOptions pemTrustOptions = new PemTrustOptions();
                    if (pemTrustStore.getPath() != null && !pemTrustStore.getPath().isEmpty()) {
                        pemTrustOptions.addCertPath(pemTrustStore.getPath());
                    } else if (pemTrustStore.getContent() != null && !pemTrustStore.getContent().isEmpty()) {
                        pemTrustOptions
                                .addCertValue(io.vertx.core.buffer.Buffer.buffer(pemTrustStore.getContent()));
                    } else {
                        throw new EndpointException(
                                "Missing PEM certificate value for endpoint " + endpoint.getName());
                    }
                    this.httpClientOptions.setPemTrustOptions(pemTrustOptions);
                    break;
                case PKCS12:
                    PKCS12TrustStore pkcs12TrustStore = (PKCS12TrustStore) sslOptions.getTrustStore();
                    PfxOptions pfxOptions = new PfxOptions();
                    pfxOptions.setPassword(pkcs12TrustStore.getPassword());
                    if (pkcs12TrustStore.getPath() != null && !pkcs12TrustStore.getPath().isEmpty()) {
                        pfxOptions.setPath(pkcs12TrustStore.getPath());
                    } else if (pkcs12TrustStore.getContent() != null
                            && !pkcs12TrustStore.getContent().isEmpty()) {
                        pfxOptions.setValue(io.vertx.core.buffer.Buffer.buffer(pkcs12TrustStore.getContent()));
                    } else {
                        throw new EndpointException("Missing PKCS12 value for endpoint " + endpoint.getName());
                    }
                    this.httpClientOptions.setPfxTrustOptions(pfxOptions);
                    break;
                case JKS:
                    JKSTrustStore jksTrustStore = (JKSTrustStore) sslOptions.getTrustStore();
                    JksOptions jksOptions = new JksOptions();
                    jksOptions.setPassword(jksTrustStore.getPassword());
                    if (jksTrustStore.getPath() != null && !jksTrustStore.getPath().isEmpty()) {
                        jksOptions.setPath(jksTrustStore.getPath());
                    } else if (jksTrustStore.getContent() != null && !jksTrustStore.getContent().isEmpty()) {
                        jksOptions.setValue(io.vertx.core.buffer.Buffer.buffer(jksTrustStore.getContent()));
                    } else {
                        throw new EndpointException("Missing JKS value for endpoint " + endpoint.getName());
                    }
                    this.httpClientOptions.setTrustStoreOptions(jksOptions);
                    break;
                }
            }

            // Client authentication configuration
            if (sslOptions.getKeyStore() != null) {
                switch (sslOptions.getKeyStore().getType()) {
                case PEM:
                    PEMKeyStore pemKeyStore = (PEMKeyStore) sslOptions.getKeyStore();
                    PemKeyCertOptions pemKeyCertOptions = new PemKeyCertOptions();
                    if (pemKeyStore.getCertPath() != null && !pemKeyStore.getCertPath().isEmpty()) {
                        pemKeyCertOptions.setCertPath(pemKeyStore.getCertPath());
                    } else if (pemKeyStore.getCertContent() != null
                            && !pemKeyStore.getCertContent().isEmpty()) {
                        pemKeyCertOptions
                                .setCertValue(io.vertx.core.buffer.Buffer.buffer(pemKeyStore.getCertContent()));
                    }
                    if (pemKeyStore.getKeyPath() != null && !pemKeyStore.getKeyPath().isEmpty()) {
                        pemKeyCertOptions.setKeyPath(pemKeyStore.getKeyPath());
                    } else if (pemKeyStore.getKeyContent() != null && !pemKeyStore.getKeyContent().isEmpty()) {
                        pemKeyCertOptions
                                .setKeyValue(io.vertx.core.buffer.Buffer.buffer(pemKeyStore.getKeyContent()));
                    }
                    this.httpClientOptions.setPemKeyCertOptions(pemKeyCertOptions);
                    break;
                case PKCS12:
                    PKCS12KeyStore pkcs12KeyStore = (PKCS12KeyStore) sslOptions.getKeyStore();
                    PfxOptions pfxOptions = new PfxOptions();
                    pfxOptions.setPassword(pkcs12KeyStore.getPassword());
                    if (pkcs12KeyStore.getPath() != null && !pkcs12KeyStore.getPath().isEmpty()) {
                        pfxOptions.setPath(pkcs12KeyStore.getPath());
                    } else if (pkcs12KeyStore.getContent() != null && !pkcs12KeyStore.getContent().isEmpty()) {
                        pfxOptions.setValue(io.vertx.core.buffer.Buffer.buffer(pkcs12KeyStore.getContent()));
                    }
                    this.httpClientOptions.setPfxKeyCertOptions(pfxOptions);
                    break;
                case JKS:
                    JKSKeyStore jksKeyStore = (JKSKeyStore) sslOptions.getKeyStore();
                    JksOptions jksOptions = new JksOptions();
                    jksOptions.setPassword(jksKeyStore.getPassword());
                    if (jksKeyStore.getPath() != null && !jksKeyStore.getPath().isEmpty()) {
                        jksOptions.setPath(jksKeyStore.getPath());
                    } else if (jksKeyStore.getContent() != null && !jksKeyStore.getContent().isEmpty()) {
                        jksOptions.setValue(io.vertx.core.buffer.Buffer.buffer(jksKeyStore.getContent()));
                    }
                    this.httpClientOptions.setKeyStoreOptions(jksOptions);
                    break;
                }
            }
        }
    }

    printHttpClientConfiguration(httpClientOptions);
}