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:com.company.vertxstarter.MainVerticle.java

@Override
public void start(Future<Void> fut) {
    // Create a router object.
    Router router = Router.router(vertx);
    //CORS handler
    router.route().handler(CorsHandler.create("*").allowedMethod(HttpMethod.GET).allowedMethod(HttpMethod.POST)
            .allowedMethod(HttpMethod.OPTIONS).allowedHeader("Content-Type").allowedHeader("Accept"));

    //default headers
    router.route().handler(ctx -> {/*from w w  w .  j  a  va  2s.  co m*/
        ctx.response().putHeader("Cache-Control", "no-store, no-cache").putHeader("Content-Type",
                "application/json");

        if (StringUtils.isEmpty(ctx.request().getHeader("Accept"))) {
            ctx.fail(Failure.NO_MEDIA_TYPE);
            return;
        } else if (!"application/json".equalsIgnoreCase(ctx.request().getHeader("Accept"))) {
            ctx.fail(Failure.UNSUPPORTED_MEDIA_TYPE);
            return;
        }
        ctx.next();
    });

    //error handling
    router.route().failureHandler(ctx -> {
        HttpServerResponse response = ctx.response();
        final JsonObject error = new JsonObject();
        Failure ex;

        if (ctx.failure() instanceof Failure) { //specific error
            ex = (Failure) ctx.failure();
        } else { //general error
            ctx.failure().printStackTrace();
            ex = Failure.INTERNAL_ERROR;
        }
        error.put("message", ex.getMessage());
        response.setStatusCode(ex.getCode()).end(error.encode());
    });
    //default 404 handling
    router.route().last().handler(ctx -> {
        HttpServerResponse response = ctx.response();
        final JsonObject error = new JsonObject();
        error.put("message", Failure.NOT_FOUND.getMessage());
        response.setStatusCode(404).end(error.encode());
    });

    //routes
    Injector injector = Guice.createInjector(new AppInjector());
    router.route(HttpMethod.GET, "/people").handler(injector.getInstance(PersonResource.class)::get);

    // Create the HTTP server and pass the "accept" method to the request handler.
    HttpServerOptions serverOptions = new HttpServerOptions();
    serverOptions.setCompressionSupported(true);
    vertx.createHttpServer(serverOptions).requestHandler(router::accept)
            .listen(config().getInteger("http.port", 8080), result -> {
                if (result.succeeded()) {
                    fut.complete();
                } else {
                    fut.fail(result.cause());
                }
            });
}

From source file:com.dinstone.vertx.verticle.HttpManageVerticle.java

License:Apache License

private HttpServerOptions getRestHttpServerOptions() {
    HttpServerOptions serverOptions = null;
    try {//from  w  w w .ja v a 2s.co  m
        serverOptions = applicationContext.getBean("restHttpServerOptions", HttpServerOptions.class);
    } catch (Exception e) {
        // ignore
    }
    if (serverOptions == null) {
        serverOptions = new HttpServerOptions();
    }

    serverOptions.setIdleTimeout(manageProperties.getIdleTimeout());
    serverOptions.setPort(manageProperties.getPort());

    if (manageProperties.getHost() != null) {
        serverOptions.setHost(manageProperties.getHost());
    }
    return serverOptions;
}

From source file:com.dinstone.vertx.verticle.HttpRestVerticle.java

License:Apache License

private HttpServerOptions getRestHttpServerOptions() {
    HttpServerOptions serverOptions = null;
    try {/*  w  w w. j  a v a  2  s  .  c  o m*/
        serverOptions = applicationContext.getBean("restHttpServerOptions", HttpServerOptions.class);
    } catch (Exception e) {
        // ignore
    }
    if (serverOptions == null) {
        serverOptions = new HttpServerOptions();
    }

    serverOptions.setIdleTimeout(restProperties.getIdleTimeout());
    serverOptions.setPort(restProperties.getPort());

    if (restProperties.getHost() != null) {
        serverOptions.setHost(restProperties.getHost());
    }
    return serverOptions;
}

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);// w  ww.  ja  v a 2s  .  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:com.github.mcollovati.vertx.vaadin.VaadinVerticle.java

License:Open Source License

@Override
public void start(Future<Void> startFuture) throws Exception {
    log.info("Starting vaadin verticle " + getClass().getName());

    VaadinVerticleConfiguration vaadinVerticleConfiguration = getClass()
            .getAnnotation(VaadinVerticleConfiguration.class);

    JsonObject vaadinConfig = new JsonObject();
    vaadinConfig.put("serviceName", this.deploymentID());
    vaadinConfig.put("mountPoint", Optional.ofNullable(vaadinVerticleConfiguration)
            .map(VaadinVerticleConfiguration::mountPoint).orElse("/"));
    readUiFromEnclosingClass(vaadinConfig);
    readConfigurationAnnotation(vaadinConfig);
    vaadinConfig.mergeIn(config().getJsonObject("vaadin", new JsonObject()));

    String mountPoint = vaadinConfig.getString("mountPoint");
    VertxVaadin vertxVaadin = createVertxVaadin(vaadinConfig);
    vaadinService = vertxVaadin.vaadinService();

    HttpServerOptions serverOptions = new HttpServerOptions().setCompressionSupported(true);
    httpServer = vertx.createHttpServer(serverOptions);

    Router router = Router.router(vertx);
    router.mountSubRouter(mountPoint, vertxVaadin.router());

    httpServer.websocketHandler(vertxVaadin.webSocketHandler());
    httpServer.requestHandler(router::accept).listen(config().getInteger("httpPort", 8080));

    serviceInitialized(vaadinService, router);

    log.info("Started vaadin verticle " + getClass().getName());
    startFuture.complete();//from  www  . j a  v  a 2s .c o  m
}

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

License:Open Source License

private void initHttpServer(Router router, Handler<AsyncResult<Void>> handler) {
    HttpServerOptions options = new HttpServerOptions().setPort(settings.getServerPort());
    HttpServer server = vertx.createHttpServer(options);
    server.requestHandler(router::accept).listen(result -> {
        if (result.failed()) {
            handler.handle(Future.failedFuture(result.cause()));
        } else {/*from  w w w  . j av a 2  s . c om*/
            handler.handle(Future.succeededFuture());
        }
    });
}

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);/*from ww w.j  ava  2s. c  o m*/
        try {
            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:eu.rethink.mn.MsgNode.java

License:Apache License

@Override
public void start() throws Exception {
    final PipeRegistry register = new PipeRegistry(vertx, mgr, config.getDomain());
    register.installComponent(new SubscriptionManager(register));
    register.installComponent(new SessionManager(register));
    register.installComponent(new HypertyAllocationManager(register));
    register.installComponent(new ObjectAllocationManager(register));
    register.installComponent(new AllocationManager(register));

    final RegistryConnector rc = new RegistryConnector(register);
    register.installComponent(rc);/*from w  w w  .j a  v a2s  . c  om*/

    final GlobalRegistryConnector grc = new GlobalRegistryConnector(register);
    register.installComponent(grc);

    final Pipeline pipeline = new Pipeline(register).addHandler(new ValidatorPipeHandler()) //validation of mandatory fields
            .addHandler(new TransitionPipeHandler()) //inter-domain allocator and routing
            .addHandler(new PoliciesPipeHandler()).failHandler(error -> {
                out.println("PIPELINE-FAIL: " + error);
            });

    //HTTPS security configurations
    final JksOptions jksOptions = new JksOptions().setPath("server-keystore.jks").setPassword("rethink2015");

    final HttpServerOptions httpOptions = new HttpServerOptions().setTcpKeepAlive(true).setSsl(true)
            .setKeyStoreOptions(jksOptions).setMaxWebsocketFrameSize(6553600);

    final HttpServer server = vertx.createHttpServer(httpOptions);
    server.requestHandler(req -> {
        //just a land page to test connection
        System.out.println("HTTP-PING");
        req.response().putHeader("content-type", "text/html").end("<html><body><h1>Hello</h1></body></html>");
    });

    WebSocketServer.init(server, pipeline);
    server.listen(config.getPort());
    System.out.println("[Message-Node] Running with config: " + config);
}

From source file:examples.HTTP2Examples.java

License:Open Source License

public void example0(Vertx vertx) {
    HttpServerOptions options = new HttpServerOptions().setUseAlpn(true).setSsl(true)
            .setKeyStoreOptions(new JksOptions().setPath("/path/to/my/keystore"));

    HttpServer server = vertx.createHttpServer(options);
}

From source file:examples.HTTPExamples.java

License:Open Source License

public void example2(Vertx vertx) {

    HttpServerOptions options = new HttpServerOptions().setMaxWebsocketFrameSize(1000000);

    HttpServer server = vertx.createHttpServer(options);
}