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:examples.HTTPExamples.java

License:Open Source License

public void exampleServerLogging(Vertx vertx) {

    HttpServerOptions options = new HttpServerOptions().setLogActivity(true);

    HttpServer server = vertx.createHttpServer(options);
}

From source file:examples.NetExamples.java

License:Open Source License

public void example50(Vertx vertx) throws CertificateException {
    SelfSignedCertificate certificate = SelfSignedCertificate.create();

    vertx.createHttpServer(new HttpServerOptions().setSsl(true).setKeyCertOptions(certificate.keyCertOptions())
            .setTrustOptions(certificate.trustOptions())).requestHandler(req -> req.response().end("Hello!"))
            .listen(8080);//from  ww w .j ava 2  s.  c o m
}

From source file:examples.StompServerExamples.java

License:Open Source License

public void example16(Vertx vertx) {
    StompServer server = StompServer.create(vertx, new StompServerOptions().setPort(-1) // Disable the TCP port, optional
            .setWebsocketBridge(true) // Enable the web socket support
            .setWebsocketPath("/stomp")) // Configure the web socket path, /stomp by default
            .handler(StompServerHandler.create(vertx));

    HttpServer http = vertx//from   w w w.j  a v a2 s.com
            .createHttpServer(new HttpServerOptions().setWebsocketSubProtocols("v10.stomp, v11.stomp"))
            .websocketHandler(server.webSocketHandler()).listen(8080);
}

From source file:gribbit.server.GribbitServer.java

License:Open Source License

/**
 * Start the HTTP server./*  w w w .  j ava  2 s. c  om*/
 * 
 * @throws IllegalArgumentException
 *             if port is already in use, or the server cannot be started for some other reason.
 */
public GribbitServer start() {
    if (port == null) {
        port = useTLS ? 8443 : 8080;
    }
    if (!portAvailable(port)) {
        throw new IllegalArgumentException("Port " + port + " is not available -- is server already running?");
    }

    String domainAndPort = domain + ((!useTLS && port == 80) || (useTLS && port == 443) ? "" : ":" + port);
    try {
        uri = new URI((useTLS ? "https" : "http") + "://" + domainAndPort);
        wsUri = new URI((useTLS ? "wss" : "ws") + "://" + domainAndPort);
    } catch (URISyntaxException e) {
        throw new RuntimeException(e);
    }

    HttpServerOptions serverOptions = new HttpServerOptions() //
            .setIdleTimeout(IDLE_TIMEOUT_SECONDS) //
            .setHandle100ContinueAutomatically(true) //
            .setSsl(useTLS);
    server = vertx.createHttpServer(serverOptions);
    router = Router.router(vertx);

    // Automatically serve files in "webroot/static/*" (relative to current directory, or in classpath).
    // Handles range requests automatically, and if files are in a jar in the classpath, they are
    // transparently extracted to a temporary cache directory on disk. Also handles Content-Range requests.
    StaticHandler staticHandler = StaticHandler.create() //
            .setWebRoot("webroot") //
            .setIncludeHidden(false) //
            .setDirectoryListing(false);
    router.route("/static/*").handler(staticHandler);

    // TODO: switch to clustered session store in clustered environment
    SessionStore store = LocalSessionStore.create(vertx, basePackageName, SESSION_REAPER_TIMEOUT_MILLIS);
    router.route().handler(CookieHandler.create()); // SessionHandler requires CookieHandler
    router.route().handler(SessionHandler.create(store));

    router.route().handler(routingContext -> {
        // Execute all requests on worker threads, so that they can block
        vertx.executeBlocking(future -> {
            Response response = null;
            HttpServerRequest request = routingContext.request();
            ParsedURL reqURL = new ParsedURL(request.uri());
            try {
                // RequestURL reqURL = new RequestURL(request.absoluteURI());  // TODO
                boolean isWSUpgrade = false;
                //                    if (webSocketHandlers != null) {
                //                        for (WebSocketHandler handler : webSocketHandlers) {
                //                            if (handler.isWebSocketUpgradeURL(request.absoluteURI())) {
                //                                isWSUpgrade = true;
                //                                ServerWebSocket websocket = request.upgrade();
                //                                throw new RuntimeException("TODO"); // TODO
                //                            }
                //                        }
                //                    }
                if (!isWSUpgrade) {
                    // Try each route in turn
                    for (Route route : siteResources.getAllRoutes()) {
                        if (route.matches(reqURL)) {
                            response = route.callHandler(routingContext, reqURL);
                            if (response != null) {
                                // Stop calling handlers after the first response
                                break;
                            }
                        }
                    }
                    if (response == null) {
                        // No route matched => 404
                        response = new NotFoundException().generateErrorResponse(routingContext, siteResources);
                    }
                }
            } catch (Exception e) {
                // Convert Exception to InternalServerErrorException if it's not already a ResponseException 
                ResponseException responseException;
                if (e instanceof ResponseException) {
                    responseException = (ResponseException) e;
                } else {
                    responseException = new InternalServerErrorException(e);
                }
                try {
                    // Otherwise, use the default response for this error type
                    response = responseException.generateErrorResponse(routingContext, siteResources);
                } catch (Exception e2) {
                    // Generate a generic InternalServerErrorException response if an exception was thrown
                    // while generating a response
                    response = new InternalServerErrorException(
                            "Exception in error handler while handling exception " + e.getMessage(), e2)
                                    .generateErrorResponse(routingContext, siteResources);
                }
            }
            try {
                // Send response
                response.send(routingContext);

            } catch (Exception e) {
                // Failure while sending response, connection was probably closed
            }
            future.complete();
        },
                // From the docs:
                // "By default, if executeBlocking is called several times from the same context (e.g. the
                // same verticle instance) then the different executeBlocking are executed serially (i.e.
                // one after another). If you dont care about ordering you can call executeBlocking
                // specifying false as the argument to ordered. In this case any executeBlocking may be
                // executed in parallel on the worker pool."
                /* ordered = */ false,

                //
                // Async result handler
                res -> {
                    if (res.failed()) {
                        // An uncaught exception was thrown from the blocking handler
                        routingContext.fail(res.cause());
                    }
                });
    });

    server.requestHandler(router::accept);

    Log.info("Starting " + SERVER_IDENTIFIER + " on port " + port);
    server.listen(port);
    Log.info(SERVER_IDENTIFIER + " started at " + uri + "/");
    return this;
}

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  . j  a  v  a 2  s.com
    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.apiman.gateway.platforms.vertx3.verticles.HttpGatewayVerticle.java

License:Apache License

@Override
public void start(Future<Void> startFuture) {
    super.start(startFuture);

    HttpApiFactory.init(engine.getApiRequestPathParser());

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

    vertx.createHttpServer(standardOptions).requestHandler(this::requestHandler)
            .listen(apimanConfig.getPort(VERTICLE_TYPE));
}

From source file:io.apiman.gateway.platforms.vertx3.verticles.HttpsGatewayVerticle.java

License:Apache License

@Override
public void start(Future<Void> startFuture) {
    super.start(startFuture);

    HttpApiFactory.init(engine.getApiRequestPathParser());

    HttpServerOptions sslOptions = new HttpServerOptions().setHost(apimanConfig.getHostname()).setSsl(true)
            .setKeyStoreOptions(new JksOptions().setPath(apimanConfig.getKeyStore())
                    .setPassword(apimanConfig.getKeyStorePassword()))
            .setTrustStoreOptions(new JksOptions().setPath(apimanConfig.getTrustStore())
                    .setPassword(apimanConfig.getTrustStorePassword()));

    vertx.createHttpServer(sslOptions).requestHandler(this::requestHandler)
            .listen(apimanConfig.getPort(VERTICLE_TYPE));
}

From source file:io.apiman.test.common.echo.EchoServerVertx.java

License:Apache License

private HttpServerOptions getHttpServerOptions(String name) {
    HttpServerOptions options = new HttpServerOptions();
    HttpServerOptionsConverter.fromJson(config().getJsonObject(name, new JsonObject()), options);
    if (JdkSSLEngineOptions.isAlpnAvailable()) {
        options.setUseAlpn(true);//www  .jav a  2 s . c o  m
    }
    return options;
}

From source file:io.github.bckfnn.actioner.Main.java

License:Apache License

/**
 * Initialize.//from w  w w.  j  a v a  2s.c  o m
 * @param future the future to signal when done
 * @throws Exception if an action class can not be loaded
 */
@Override
public void start(Future<Void> future) throws Exception {
    log.info("Starting");
    config = loadConfig();

    if (config.hasPath("translations")) {
        translations = ConfigFactory.load(config.getString("translations"));
    }

    log.debug("config loaded");

    initialize();

    boolean develop = config.getBoolean("develop");
    String contextRoot = config.getString("webserver.contextRoot");

    //Schema schema = makeSchema();
    //Persistor persistor = makePersistor(config, schema);

    if (config.hasPath("groups")) {
        authProvider = new DbAuthProvider(this, ConfigFactory.load(config.getString("groups")));
    }

    Router router = Router.router(vertx);
    System.out.println(router);

    router.route().handler(ctx -> {

        ctx.put(Vertx.class.getName(), vertx);
        ctx.put(Router.class.getName(), router);
        ctx.put(ActionRouter.class.getName(), actionRouter);
        ctx.put(Config.class.getName(), config);

        ctx.put("ctx", ctx);
        ctx.put("startTime", System.currentTimeMillis());
        ctx.put("translations", translations);
        ctx.put("contextRoot", contextRoot);
        ctx.put(AuthProvider.class.getName(), authProvider);

        ctx.response().putHeader("X-Frame-Options", "deny");
        configContext(ctx);
        log.debug("request: {}", ctx.request().path());
        ctx.next();
    });

    if (authProvider != null) {
        sessionStore = new PersistentLocalSessionStore(vertx, LocalSessionStore.DEFAULT_SESSION_MAP_NAME,
                LocalSessionStore.DEFAULT_REAPER_INTERVAL, config.getString("sessionStorage")); //LocalSessionStore.create(vertx);
    }

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

    if (config.hasPath("metrics")) {
        MetricRegistry registry = SharedMetricRegistries.getOrCreate(config.getString("metrics.registryName"));

        if (config.hasPath("metrics.logback")) {
            final LoggerContext factory = (LoggerContext) LoggerFactory.getILoggerFactory();
            final ch.qos.logback.classic.Logger root = factory.getLogger(Logger.ROOT_LOGGER_NAME);

            final InstrumentedAppender metrics = new InstrumentedAppender(registry);
            metrics.setContext(root.getLoggerContext());
            metrics.start();
            root.addAppender(metrics);
        }

        if (config.hasPath("metrics.prometheus.uri")) {
            router.get(config.getString("metrics.prometheus.uri"))
                    .handler(new PrometheusMetricsHandler(registry));
        }

    }

    if (config.hasPath("webserver.webjars")) {
        router.route().path(contextRoot + config.getString("webserver.webjars.uri"))
                .handler(new WebjarsHandler());
    }
    if (config.hasPath("webserver.assets")) {
        router.route().path(contextRoot + config.getString("webserver.assets.uri"))
                .handler(new AssetsHandler());
    }

    if (config.hasPath("webserver.public")) {
        router.route().path(contextRoot + config.getString("webserver.public.uri"))
                .handler(StaticHandler.create(config.getString("app.publicFolder")).setCachingEnabled(!develop)
                        .setFilesReadOnly(!develop));
    }

    if (authProvider != null) {
        router.route().handler(SessionHandler.create(sessionStore).setNagHttps(!develop));
        router.route().handler(UserSessionHandler.create(authProvider));
    }
    router.route().handler(new AcceptLanguageHandler(true));
    router.route().handler(LoggerHandler.create(false, LoggerFormat.SHORT));

    configRouter(router);

    for (String cls : config.getStringList("app.actionClasses")) {
        actionRouter.addAction(contextRoot, router, getClass().getClassLoader().loadClass(cls));
    }

    router.route().handler(new LayoutTemplateHandler());
    router.route().failureHandler(ctx -> {
        if (ctx.failed() && ctx.failure() != null) {
            log.error("Error handler", ctx.failure());
        }
        ErrorHandler.create(develop).handle(ctx);
    });

    BridgeOptions opts = new BridgeOptions()
            .addInboundPermitted(new PermittedOptions().setAddress("importList"))
            .addOutboundPermitted(new PermittedOptions().setAddress("importList"));
    SockJSHandler ebHandler = SockJSHandler.create(vertx).bridge(opts);
    router.route("/eventbus/*").handler(ebHandler);

    HttpServerOptions options = new HttpServerOptions();
    options.setPort(config.getInt("port"));

    server = vertx.createHttpServer(options);
    server.requestHandler(router::accept).listen(res -> {
        if (res.failed()) {
            log.error("http server failed to start", res.cause());
            future.fail(res.cause());
        } else {
            log.info("http started");
        }
        future.complete();
    });
}

From source file:io.github.cdelmas.spike.vertx.Main.java

License:Apache License

public static void main(String[] args) {
    long time = System.currentTimeMillis();
    Json.mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);

    Vertx vertx = Vertx.vertx();/*from w  ww  .j a  v a  2  s. c  o m*/

    Router router = Router.router(vertx);

    HelloResource helloResource = new HelloResource();
    router.get("/vertx/hello").produces("application/json").handler(helloResource::hello);
    router.route("/vertx/hello").method(HttpMethod.POST).handler(BodyHandler.create());
    router.post("/vertx/hello").consumes("application/json").handler(helloResource::createMessage);

    HttpServerOptions serverOptions = new HttpServerOptions().setPort(8085);
    HttpServer server = vertx.createHttpServer(serverOptions);
    server.requestHandler(router::accept).listen();
    System.out.println("started in " + (System.currentTimeMillis() - time) + " ms");
}