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

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

Introduction

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

Prototype

public HttpServerOptions() 

Source Link

Document

Default constructor

Usage

From source file:org.springframework.integration.vertx.WebSocketServer.java

License:Apache License

@Override
public synchronized void start() {
    if (this.running) {
        return;//  w w w  .  ja  v  a  2  s.c  om
    }

    HttpServerOptions httpServerOptions = new HttpServerOptions();
    httpServerOptions.setPort(this.getPort());

    this.server = Vertx.factory.vertx().createHttpServer(httpServerOptions).websocketHandler(ws -> {
        final String correlationId = UUID.randomUUID().toString();
        final TcpListener listener = WebSocketServer.this.getListener();
        WebSocketConnection connection = new WebSocketConnection(correlationId, ws, listener);
        WebSocketServer.this.getSender().addNewConnection(connection);
        if (ws.path().equals("/myapp")) {
            ws.handler(data -> {

                listener.onMessage(MessageBuilder.withPayload(data.toString()).setCorrelationId(correlationId)
                        .setHeader(IpHeaders.CONNECTION_ID, correlationId).build());
            });

        } else {
            ws.reject();
        }
    }).requestHandler(req -> {
        if (req.path().equals("/")) {
            req.response().sendFile("ws.html");
        }
    }).listen();
    this.running = true;
}

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) {/*from w  ww . j  a va 2  s . 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:org.workspace7.k8s.auth.proxy.K8sWebProxyVerticle.java

License:Apache License

/**
 * @param keyCloakOAuth2//from  ww  w.  j  a  v  a 2 s  .c  om
 * @param next
 */
protected void startWebApp(AsyncResult<OAuth2Auth> keyCloakOAuth2, Handler<AsyncResult<HttpServer>> next) {

    Router router = Router.router(vertx);

    final String proxyUri = "https://" + config().getString("k8s_proxy_host") + ":"
            + config().getInteger("k8s_proxy_port");

    if (keyCloakOAuth2.succeeded()) {

        OAuth2AuthHandler keycloakOAuthHandler = OAuth2AuthHandler.create(keyCloakOAuth2.result(), proxyUri);
        keycloakOAuthHandler.setupCallback(router.get("/callback"));

        //router.route().handler(BodyHandler.create());

        router.route("/api/*").handler(keycloakOAuthHandler);
        router.route("/ui/*").handler(keycloakOAuthHandler);

        //Handle UI Requests
        router.route("/ui/").handler(this::handleUIPath);

        //Handle API Requests
        router.route("/api/*").handler(this::handleApiPath);

        router.get("/").handler(ctx -> ctx.reroute("/ui/"));

        //These options are for setting up the server (k8s-proxy)
        HttpServerOptions httpServerOptions = new HttpServerOptions().setSsl(true);

        //Server HTTPS
        httpServerOptions.setPemKeyCertOptions(proxyPemOptions());
        httpServerOptions.setTrustStoreOptions(proxyTrustOptions());

        vertx.createHttpServer(httpServerOptions).requestHandler(router::accept)
                .listen(config().getInteger("k8s_proxy_port"), config().getString("k8s_proxy_host"), next);
    } else {
        _logger.error("Unable to start proxy : {}", keyCloakOAuth2.cause());
        next.handle(Future.failedFuture(keyCloakOAuth2.cause()));
    }
}

From source file:otocloud.webserver.verticle.WebTestBase.java

License:Open Source License

@Override
public void setUp() throws Exception {
    super.setUp();
    router = Router.router(vertx);//from  w  w  w. j ava  2  s.  com
    server = vertx.createHttpServer(new HttpServerOptions().setPort(8080).setHost("localhost"));
    client = vertx.createHttpClient(new HttpClientOptions().setDefaultPort(8080));
    CountDownLatch latch = new CountDownLatch(1);
    server.requestHandler(router::accept).listen(onSuccess(res -> {
        latch.countDown();
    }));
    awaitLatch(latch);
}

From source file:pt.davidafsilva.slacker.server.HttpServerConfiguration.java

License:Open Source License

/**
 * Sets up the http server configuration based on the available environment variables (SLACK_*)
 * and current configuration via the json configuration file.
 *
 * @param config the current configuration
 * @return the configured server options
 *///  ww w  .jav a  2  s.c o  m
static HttpServerOptions setup(final JsonObject config) {
    // evaluate the environment variables
    evaluateEnvironmentVariables(config);

    // create the http server options
    final HttpServerOptions options = new HttpServerOptions().setIdleTimeout(IDLE_TIMEOUT)
            .setPort(config.getInteger(ConfigurationVariable.HTTP_PORT.name(), DEFAULT_HTTP_PORT))
            .setSsl(config.getBoolean(ConfigurationVariable.USE_SSL.name(), DEFAULT_USE_SSL));

    // setup the required SSL parameters
    if (options.isSsl()) {
        // validate the configuration
        validateOptions(config, ConfigurationVariable.KEY_STORE_FILE, ConfigurationVariable.KEY_STORE_PASS);

        // add the enabled cipher suites
        CIPHER_SUITES.stream().forEach(options::addEnabledCipherSuite);

        // set the both keystore location and keystore password
        options.setKeyStoreOptions(
                new JksOptions().setPath(config.getString(ConfigurationVariable.KEY_STORE_FILE.name()))
                        .setPassword(config.getString(ConfigurationVariable.KEY_STORE_PASS.name())));
    }

    return options;
}

From source file:se.liquidbytes.jel.web.WebserverVerticle.java

License:Apache License

/**
 * Method should be called when verticle should start up
 *
 * @param future Future for reporting back success or failure of execution
 *///from   w w  w  .  java 2s .c om
@Override
public void start(Future<Void> future) {

    // If no API should be exposed, and thus the client won't work either, then don't start the webserver.
    if (Settings.get("skipapi").equals("true")) {
        logger.info("No API will be exposed according to the settings provided during application startup.");
        future.complete();
        return;
    }

    systemApi = new SystemApi(vertx);
    pluginApi = new PluginApi(vertx);
    adapterApi = new AdapterApi(vertx);
    siteApi = new SiteApi(vertx);
    userApi = new UserApi(vertx);
    deviceApi = new DeviceApi(vertx);

    HttpServerOptions options = new HttpServerOptions();
    options.setHost(SystemInfo.getIP());
    options.setPort(Integer.parseInt(config.getString("port")));

    server = vertx.createHttpServer(options);
    server.requestHandler(createRouter()::accept);
    server.listen(result -> {
        if (result.succeeded()) {
            logger.info(String.format("Jel REST-API now listening on %s port %d.", options.getHost(),
                    options.getPort()));
            future.complete();
        } else {
            future.fail(result.cause());
        }
    });
}

From source file:space.xkr47.vertx.acme4j.util.SetupHttpServerOptions.java

License:Apache License

public static HttpServerOptions createHttpServerOptions(DynamicCertOptions dynamicCertOptions,
        boolean jettyAgentAlreadyLoaded) {
    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).setSsl(true).setKeyCertOptions(dynamicCertOptions)
            // TLS tuning
            .addEnabledSecureTransportProtocol("TLSv1.2").addEnabledSecureTransportProtocol("TLSv1.3");

    // enable HTTP/2 support if we can..
    if (USE_OPENSSL) {
        // TODO this has not really been tested with SNI yet
        httpOptions.setUseAlpn(true).setSslEngineOptions(new OpenSSLEngineOptions());
        cipherSuites.stream().map(SetupHttpServerOptions::javaCipherNameToOpenSSLName)
                .forEach(httpOptions::addEnabledCipherSuite);
    } else {//from  w w w . j  av a2  s.  co m
        httpOptions.setUseAlpn(jettyAgentAlreadyLoaded || DynamicAgent.enableJettyAlpn())
                .setJdkSslEngineOptions(new JdkSSLEngineOptions());
        cipherSuites.forEach(httpOptions::addEnabledCipherSuite);
    }

    return httpOptions;
}

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();/*from ww w.j  ava2 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());
        }
    });
}

From source file:suonos.httpserver.VertxHttpServer.java

License:Apache License

@Override
public void run() {
    HttpServerOptions opts = new HttpServerOptions();
    opts.setHost(host);//from w  ww.j  ava2s  .c  o m
    opts.setPort(port);
    opts.setCompressionSupported(true);

    staticFileHandler.setContextPath("/res");
    server = vertx.createHttpServer(opts);

    webApp.routes().addRouteHandler("/res/:path*", staticFileHandler);
    server.requestHandler(new VertxRequestHandler(vertx, webApp));
    server.listen();
}

From source file:webservice.WebServiceExample.java

License:Open Source License

@Override
public void start(Future<Void> startFuture) {
    // deploy the web server
    HttpServerOptions options = new HttpServerOptions().setCompressionSupported(true);
    HttpServer server = vertx.createHttpServer(options);
    server.requestHandler(this::onRequest);
    server.listenObservable(8080) // listen on port 8080
            .subscribe(v -> startFuture.complete(), startFuture::fail);
}