Example usage for io.vertx.core.http HttpServerOptions setSsl

List of usage examples for io.vertx.core.http HttpServerOptions setSsl

Introduction

In this page you can find the example usage for io.vertx.core.http HttpServerOptions setSsl.

Prototype

@Override
    public HttpServerOptions setSsl(boolean ssl) 

Source Link

Usage

From source file:com.englishtown.vertx.jersey.impl.DefaultJerseyServer.java

License:Open Source License

@Override
public void init(final JerseyOptions options, final Handler<AsyncResult<HttpServer>> doneHandler) {

    // Setup the http server options
    HttpServerOptions serverOptions = new HttpServerOptions().setHost(options.getHost())
            .setPort(options.getPort()).setAcceptBacklog(options.getAcceptBacklog()); // Performance tweak

    // Enable https
    if (options.getSSL()) {
        serverOptions.setSsl(true);
    }//from   w ww .  ja v  a2s .c o  m
    if (options.getKeyStoreOptions() != null) {
        serverOptions.setKeyStoreOptions(options.getKeyStoreOptions());
    }

    Integer receiveBufferSize = options.getReceiveBufferSize();
    if (receiveBufferSize != null && receiveBufferSize > 0) {
        // TODO: This doesn't seem to actually affect buffer size for dataHandler.  Is this being used correctly or is it a Vertx bug?
        serverOptions.setReceiveBufferSize(receiveBufferSize);
    }

    // Create the http server
    server = options.getVertx().createHttpServer(serverOptions);

    // Init jersey handler
    jerseyHandler.init(options);

    // Set request handler for the baseUri
    server.requestHandler(jerseyHandler::handle);

    // Perform any additional server setup (add routes etc.)
    if (setupHandler != null) {
        setupHandler.handle(server);
    }

    // Start listening and log success/failure
    server.listen(ar -> {
        final String listenPath = (options.getSSL() ? "https" : "http") + "://" + serverOptions.getHost() + ":"
                + serverOptions.getPort();
        if (ar.succeeded()) {
            logger.info("Http server listening for " + listenPath);
        } else {
            logger.error("Failed to start http server listening for " + listenPath, ar.cause());
        }
        if (doneHandler != null) {
            doneHandler.handle(ar);
        }
    });

}

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

License:Open Source License

private void initHttpsServer(Router router, Handler<AsyncResult<Void>> handler) {
    if (settings.getSslPort() > 0) {
        LOGGER.info("launching ssl server listening on port " + settings.getSslPort());
        HttpServerOptions options = new HttpServerOptions().setPort(settings.getSslPort());
        options.setSsl(true);
        try {//from  w  w w . j a  va  2s  .  c om
            handleSslCertificate(options, handler);
            HttpServer server = vertx.createHttpServer(options);
            server.requestHandler(router::accept).listen(result -> {
                if (result.failed()) {
                    handler.handle(Future.failedFuture(result.cause()));
                } else {
                    handler.handle(Future.succeededFuture());
                }
            });
        } catch (Exception e) {
            handler.handle(Future.failedFuture(e));
        }
    } else {
        LOGGER.info("no ssl server is launched, cause ssl port is not set: " + settings.getSslPort());
        handler.handle(Future.succeededFuture());
    }
}

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");
        }/*from  w  w  w  . j av  a2 s  . c  om*/
        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:io.apiman.gateway.platforms.vertx3.verticles.ApiVerticle.java

License:Apache License

@Override
public void start(Future<Void> startFuture) {
    super.start(startFuture);
    IRouteBuilder clientResource = new ClientResourceImpl(apimanConfig, engine);
    IRouteBuilder apiResource = new ApiResourceImpl(apimanConfig, engine);
    IRouteBuilder systemResource = new SystemResourceImpl(apimanConfig, engine);

    Router router = Router.router(vertx).exceptionHandler(log::error);

    AuthHandler handler = AuthFactory.getAuth(vertx, router, apimanConfig, apimanConfig.getAuth());

    router.route("/*").handler(handler);

    clientResource.buildRoutes(router);//from w  w w  .ja  va 2 s.  c  om
    apiResource.buildRoutes(router);
    systemResource.buildRoutes(router);

    HttpServerOptions httpOptions = new HttpServerOptions().setHost(apimanConfig.getHostname());

    if (apimanConfig.isSSL()) {
        httpOptions.setSsl(true)
                .setKeyStoreOptions(new JksOptions().setPath(apimanConfig.getKeyStore())
                        .setPassword(apimanConfig.getKeyStorePassword()))
                .setTrustStoreOptions(new JksOptions().setPath(apimanConfig.getTrustStore())
                        .setPassword(apimanConfig.getTrustStorePassword()));
    } else {
        log.warn("API is running in plaintext mode. Enable SSL in config for production deployments.");
    }

    vertx.createHttpServer(httpOptions).requestHandler(router::accept)
            .listen(apimanConfig.getPort(VERTICLE_TYPE));
}

From source file:io.gravitee.am.gateway.vertx.VertxHttpServerFactory.java

License:Apache License

@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);/*from w ww .j  av  a 2  s.c  o  m*/

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

        if (httpServerConfiguration.isClientAuth()) {
            options.setClientAuth(ClientAuth.REQUIRED);
        }

        if (httpServerConfiguration.getTrustStorePath() != null) {
            options.setTrustStoreOptions(new JksOptions().setPath(httpServerConfiguration.getTrustStorePath())
                    .setPassword(httpServerConfiguration.getTrustStorePassword()));
        }

        if (httpServerConfiguration.getKeyStorePath() != null) {
            options.setKeyStoreOptions(new JksOptions().setPath(httpServerConfiguration.getKeyStorePath())
                    .setPassword(httpServerConfiguration.getKeyStorePassword()));
        }
    }

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

    return vertx.createHttpServer(options);
}

From source file:io.gravitee.gateway.standalone.vertx.VertxHttpServerFactory.java

License:Apache License

@Override
public HttpServer getObject() throws Exception {
    HttpServerOptions options = new HttpServerOptions();

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

    // Netty pool buffers must be enabled by default
    options.setUsePooledBuffers(true);//from ww w . j  ava 2  s. co m

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

        if (httpServerConfiguration.isClientAuth()) {
            options.setClientAuth(ClientAuth.REQUIRED);
        }

        options.setTrustStoreOptions(new JksOptions().setPath(httpServerConfiguration.getKeyStorePath())
                .setPassword(httpServerConfiguration.getKeyStorePassword()));
        options.setKeyStoreOptions(new JksOptions().setPath(httpServerConfiguration.getTrustStorePath())
                .setPassword(httpServerConfiguration.getKeyStorePassword()));
    }

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

    return vertx.createHttpServer(options);
}

From source file:io.nitor.api.backend.tls.SetupHttpServerOptions.java

License:Apache License

public static HttpServerOptions createHttpServerOptions(JsonObject config) {
    JsonObject tls = config.getJsonObject("tls");
    HttpServerOptions httpOptions = new HttpServerOptions()
            // basic TCP/HTTP options
            .setReuseAddress(true).setCompressionSupported(false) // otherwise it automatically compresses based on response headers even if pre-compressed with e.g. proxy
            .setUsePooledBuffers(true).setCompressionLevel(2)
            .setIdleTimeout(config.getInteger("idleTimeout", (int) MINUTES.toSeconds(10)));

    if (!config.getBoolean("http2", true)) {
        httpOptions.setAlpnVersions(asList(HTTP_1_1));
    }//from  ww  w . j  av a  2 s . c om

    if (tls != null) {
        httpOptions.setSsl(true)
                // server side certificate
                .setPemKeyCertOptions(new PemKeyCertOptions().setKeyPath(tls.getString("serverKey"))
                        .setCertPath(tls.getString("serverCert")))
                // TLS tuning
                .addEnabledSecureTransportProtocol("TLSv1.2").addEnabledSecureTransportProtocol("TLSv1.3");

        JsonObject clientAuth = config.getJsonObject("clientAuth");
        if (httpOptions.isSsl() && clientAuth != null && clientAuth.getString("clientChain") != null) {
            // client side certificate
            httpOptions.setClientAuth(REQUEST)
                    .setTrustOptions(new PemTrustOptions().addCertPath(clientAuth.getString("clientChain")));
        }
        if (TRUE.equals(config.getBoolean("useNativeOpenSsl"))) {
            httpOptions.setUseAlpn(true).setSslEngineOptions(new OpenSSLEngineOptions());
            cipherSuites.stream().map(SetupHttpServerOptions::javaCipherNameToOpenSSLName)
                    .forEach(httpOptions::addEnabledCipherSuite);
        } else {
            httpOptions.setUseAlpn(DynamicAgent.enableJettyAlpn())
                    .setJdkSslEngineOptions(new JdkSSLEngineOptions());
            cipherSuites.forEach(httpOptions::addEnabledCipherSuite);
        }
    }

    return httpOptions;
}

From source file:org.wisdom.framework.vertx.Server.java

License:Apache License

private void bind(int p, Handler<AsyncResult<Void>> completion) {
    // Get port number.
    final int thePort = pickAPort(port);
    HttpServerOptions options = new HttpServerOptions();
    if (ssl) {/*  w  w w .j  a va  2s  .  c  om*/
        options.setSsl(true);
        options.setTrustStoreOptions(SSLServerContext.getTrustStoreOption(accessor));
        options.setKeyStoreOptions(SSLServerContext.getKeyStoreOption(accessor));
        if (authentication) {
            options.setClientAuth(ClientAuth.REQUIRED);
        }
    }

    if (hasCompressionEnabled()) {
        options.setCompressionSupported(true);
    }

    if (configuration.getIntegerWithDefault("vertx.acceptBacklog", -1) != -1) {
        options.setAcceptBacklog(configuration.getInteger("vertx.acceptBacklog"));
    }
    if (configuration.getIntegerWithDefault("vertx.maxWebSocketFrameSize", -1) != -1) {
        options.setMaxWebsocketFrameSize(configuration.getInteger("vertx.maxWebSocketFrameSize"));
    }
    if (configuration.getStringArray("wisdom.websocket.subprotocols").length > 0) {
        options.setWebsocketSubProtocols(configuration.get("wisdom.websocket.subprotocols"));
    }
    if (configuration.getStringArray("vertx.websocket-subprotocols").length > 0) {
        options.setWebsocketSubProtocols(configuration.get("vertx.websocket-subprotocols"));
    }
    if (configuration.getIntegerWithDefault("vertx.receiveBufferSize", -1) != -1) {
        options.setReceiveBufferSize(configuration.getInteger("vertx.receiveBufferSize"));
    }
    if (configuration.getIntegerWithDefault("vertx.sendBufferSize", -1) != -1) {
        options.setSendBufferSize(configuration.getInteger("vertx.sendBufferSize"));
    }

    http = vertx.createHttpServer(options).requestHandler(new HttpHandler(vertx, accessor, this))
            .websocketHandler(new WebSocketHandler(accessor, this));

    http.listen(thePort, host, event -> {
        if (event.succeeded()) {
            logger.info("Wisdom is going to serve HTTP requests on port {}.", thePort);
            port = thePort;
            completion.handle(Future.succeededFuture());
        } else if (port == 0) {
            logger.debug("Cannot bind on port {} (port already used probably)", thePort, event.cause());
            bind(0, completion);
        } else {
            logger.error("Cannot bind on port {} (port already used probably)", thePort, event.cause());
            completion.handle(Future.failedFuture("Cannot bind on port " + thePort));
        }
    });
}

From source file:spring.vertxtest.verticle.MyTestVerticle.java

@Override
public void start(Future<Void> fut) throws Exception {
    log.info("start() -- starting Vertx Verticle with eventbus, API handler, and static file handler");

    // grab the router
    router = getRouter();// ww  w.  j  av a  2  s  . c om

    // enable CORS for the router 
    CorsHandler corsHandler = CorsHandler.create("*"); //Wildcard(*) not allowed if allowCredentials is true
    corsHandler.allowedMethod(HttpMethod.OPTIONS);
    corsHandler.allowedMethod(HttpMethod.GET);
    corsHandler.allowedMethod(HttpMethod.POST);
    corsHandler.allowedMethod(HttpMethod.PUT);
    corsHandler.allowedMethod(HttpMethod.DELETE);
    corsHandler.allowCredentials(false);
    corsHandler.allowedHeader("Access-Control-Request-Method");
    corsHandler.allowedHeader("Access-Control-Allow-Method");
    corsHandler.allowedHeader("Access-Control-Allow-Credentials");
    corsHandler.allowedHeader("Access-Control-Allow-Origin");
    corsHandler.allowedHeader("Access-Control-Allow-Headers");
    corsHandler.allowedHeader("Content-Type");

    // enable handling of body
    router.route().handler(BodyHandler.create());
    router.route().handler(corsHandler);
    router.route().handler(this::handleAccessLogging);

    // publish a payload to provided eventbus destination
    router.post("/api/eventbus/publish/:destination").handler(this::publish);

    // open up all for outbound and inbound traffic
    bridgeOptions = new BridgeOptions();
    bridgeOptions.addOutboundPermitted(new PermittedOptions().setAddressRegex(".*"));
    bridgeOptions.addInboundPermitted(new PermittedOptions().setAddressRegex(".*"));
    //        sockJsHandler = SockJSHandler.create(vertx).bridge(bridgeOptions);   
    sockJsHandler = SockJSHandler.create(vertx);
    sockJsHandler.bridge(bridgeOptions, be -> {
        try {
            if (be.type() == BridgeEventType.SOCKET_CREATED) {
                handleSocketOpenEvent(be);
            } else if (be.type() == BridgeEventType.REGISTER) {
                handleRegisterEvent(be);
            } else if (be.type() == BridgeEventType.UNREGISTER) {
                handleUnregisterEvent(be);
            } else if (be.type() == BridgeEventType.SOCKET_CLOSED) {
                handleSocketCloseEvent(be);
            }
        } catch (Exception e) {

        } finally {
            be.complete(true);
        }
    });
    router.route("/eventbus/*").handler(sockJsHandler);

    if (testPathEnabled) {
        router.route("/" + testUrlPath + "/*")
                .handler(StaticHandler.create(testFilePath).setCachingEnabled(cachingEnabled));
    }

    // create periodic task, pushing all current EventBusRegistrations
    vertx.setPeriodic(1000, handler -> {
        JsonObject obj = new JsonObject();
        obj.put("testMessage", "Periodic test message from server...");
        vertx.eventBus().publish("heartbeat-test", Json.encodePrettily(obj));
    });

    EventBus eb = vertx.eventBus();
    eb.consumer("client-test", message -> {
        log.info("Received message from client: " + Json.encodePrettily(message.body()) + " at "
                + System.currentTimeMillis());
    });

    HttpServerOptions httpOptions = new HttpServerOptions();
    if (sslEnabled) {
        httpOptions.setSsl(true);
        httpOptions.setKeyStoreOptions(sslKeyStoreOptions);
    }

    log.info("starting web server on port: " + port);
    vertx.createHttpServer(httpOptions).requestHandler(router::accept).listen(port, result -> {
        if (result.succeeded()) {
            setStarted(true);
            log.info("Server started and ready to accept requests");
            fut.complete();
        } else {
            setStarted(false);
            fut.fail(result.cause());
        }
    });
}