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:net.udidb.server.driver.UdidbServer.java

License:Open Source License

public UdidbServer(String[] args) {
    // TODO process args to configure the server

    initializeLogging();/*from w  w w .j ava  2s  . c  o m*/

    String uiPath = System.getProperty("udidb.ui.path", "");
    boolean cors = Boolean.getBoolean("udidb.cors");

    Injector injector = Guice.createInjector(new ServerModule());

    Vertx vertx = injector.getInstance(Vertx.class);

    this.httpServer = vertx.createHttpServer(new HttpServerOptions().setWebsocketSubProtocols("wamp.2.json"));

    // WebSocket events
    this.httpServer.websocketHandler(websocket -> {
        if (!websocket.path().equals("/events")) {
            websocket.reject();
        }

        injector.getInstance(EventsSocket.class).setServerWebSocket(websocket);
    });

    Router router = Router.router(vertx);

    // static content for the UI
    StaticHandler staticHandler = StaticHandler.create();
    if (uiPath != null) {
        staticHandler.setAllowRootFileSystemAccess(true);
        staticHandler.setWebRoot(uiPath);
    } else {
        staticHandler.setWebRoot("webui");
    }
    router.route("/webui/*").handler(staticHandler);

    // API resources
    if (cors) {
        router.route().handler(CorsHandler.create("*").allowedHeader("Content-Type"));
    }

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

    DebuggeeContexts debuggeeContexts = injector.getInstance(DebuggeeContexts.class);

    router.get("/debuggeeContexts").blockingHandler(noParamHandler(debuggeeContexts::getAll));
    router.post("/debuggeeContexts").blockingHandler(bodyHandler(debuggeeContexts::create));
    router.options("/debuggeeContexts").blockingHandler(ok());
    router.get("/debuggeeContexts/operations")
            .blockingHandler(noParamHandler(debuggeeContexts::getOperationDescriptions));
    router.post("/debuggeeContexts/globalOperation")
            .blockingHandler(bodyHandler(debuggeeContexts::createGlobalOperation));
    router.options("/debuggeeContexts/globalOperation").blockingHandler(ok());
    router.get("/debuggeeContexts/:id").blockingHandler(pathParamHandler("id", debuggeeContexts::get));
    router.get("/debuggeeContexts/:id/process")
            .blockingHandler(pathParamHandler("id", debuggeeContexts::getProcess));
    router.get("/debuggeeContexts/:id/process/threads")
            .blockingHandler(pathParamHandler("id", debuggeeContexts::getThreads));
    router.get("/debuggeeContexts/:id/process/threads/:threadId")
            .blockingHandler(varPathParamHandler(debuggeeContexts::getThread, "id", "threadId"));
    router.post("/debuggeeContexts/:id/process/operation")
            .blockingHandler(bodyHandler("id", debuggeeContexts::createOperation));
    router.options("/debuggeeContexts/:id/process/operation").blockingHandler(ok());
    router.get("/debuggeeContexts/:id/process/operation")
            .blockingHandler(pathParamHandler("id", debuggeeContexts::getOperation));
    router.get("/debuggeeContexts/:id/process/operations")
            .blockingHandler(pathParamHandler("id", debuggeeContexts::getOperationDescriptions));

    httpServer.requestHandler(router::accept);
}

From source file:org.apache.servicecomb.transport.rest.vertx.RestServerVerticle.java

License:Apache License

private HttpServerOptions createDefaultHttpServerOptions() {
    HttpServerOptions serverOptions = new HttpServerOptions();
    serverOptions.setUsePooledBuffers(true);
    serverOptions.setIdleTimeout(TransportConfig.getConnectionIdleTimeoutInSeconds());
    serverOptions.setCompressionSupported(TransportConfig.getCompressed());
    serverOptions.setMaxHeaderSize(TransportConfig.getMaxHeaderSize());
    serverOptions.setMaxInitialLineLength(TransportConfig.getMaxInitialLineLength());
    if (endpointObject.isHttp2Enabled()) {
        serverOptions.setUseAlpn(TransportConfig.getUseAlpn()).setInitialSettings(
                new Http2Settings().setMaxConcurrentStreams(TransportConfig.getMaxConcurrentStreams()));
    }//w  w  w . j  a va 2  s  .co m
    if (endpointObject.isSslEnabled()) {
        SSLOptionFactory factory = SSLOptionFactory.createSSLOptionFactory(SSL_KEY, null);
        SSLOption sslOption;
        if (factory == null) {
            sslOption = SSLOption.buildFromYaml(SSL_KEY);
        } else {
            sslOption = factory.createSSLOption();
        }
        SSLCustom sslCustom = SSLCustom.createSSLCustom(sslOption.getSslCustomClass());
        VertxTLSBuilder.buildNetServerOptions(sslOption, sslCustom, serverOptions);
    }

    return serverOptions;
}

From source file:org.azrul.langmera.DecisionService.java

@Override
public void start(Future<Void> fut) {

    // Create a router object.
    Router router = Router.router(vertx);

    //enable CORS
    if (config.getProperty("enableCors", Boolean.class)) {
        String allowedAddress = config.getProperty("cors.allowedAddress", String.class);

        CorsHandler c = CorsHandler.create(allowedAddress);

        String allowedHeaders = config.getProperty("cors.allowedHeaders", String.class);
        if (allowedHeaders != null) {
            String[] allowedHeadersArray = allowedHeaders.split(",");
            c.allowedHeaders(new HashSet<String>(Arrays.asList(allowedHeadersArray)));
        }// w  ww.j a va2  s .c om
        String allowedMethods = config.getProperty("cors.allowedMethods", String.class);
        if (allowedMethods != null) {
            String[] allowedMethodsArray = allowedMethods.split(",");
            for (String m : allowedMethodsArray) {
                if ("POST".equals(m)) {
                    c.allowedMethod(HttpMethod.POST);
                } else if ("PUT".equals(m)) {
                    c.allowedMethod(HttpMethod.PUT);
                } else if ("GET".equals(m)) {
                    c.allowedMethod(HttpMethod.GET);
                } else if ("DELETE".equals(m)) {
                    c.allowedMethod(HttpMethod.DELETE);
                }
            }
        }

        router.route().handler(c);
    }
    //Handle body
    router.route().handler(BodyHandler.create());

    //router.route("/langmera/assets/*").handler(StaticHandler.create("assets"));
    router.post("/langmera/api/makeDecision").handler(this::makeDecision);
    router.post("/langmera/api/acceptFeedback").handler(this::acceptFeedback);
    //router.post("/langmera/api/getHistory").handler(this::getHistory);
    //router.post("/langmera/api/getRequestTemplate").handler(this::getRequestTemplate);
    //router.post("/langmera/api/getResponseTemplate").handler(this::getFeedbackTemplate);

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

    // Create the HTTP server and pass the "accept" method to the request handler.
    vertx.createHttpServer(options).requestHandler(router::accept).listen(
            // Retrieve the port from the configuration,
            // default to 8080.
            config().getInteger("http.port", config.getProperty("http.port", Integer.class)), result -> {
                if (result.succeeded()) {
                    fut.complete();
                } else {
                    fut.fail(result.cause());
                }
            });
}

From source file:org.azrul.langmera.SaveToDB.java

@Override
public void start(Future<Void> fut) {

    HttpServerOptions options = new HttpServerOptions();
    options.setReuseAddress(true);//w  w  w  .  j ava 2  s .  co  m

    JDBCClient client = JDBCClient.createShared(vertx,
            new JsonObject().put("url", "jdbc:postgresql://localhost:5432/langmeradb")
                    .put("driver_class", "org.postgresql.Driver").put("max_pool_size", 20)
                    .put("user", "Langmera").put("password", "1qazZAQ!"));

    vertx.eventBus().<byte[]>consumer("SAVE_TRACE_TO_TRACE", message -> {

        Trace trace = (Trace) SerializationUtils.deserialize(message.body());
        client.getConnection(res -> {
            if (!res.succeeded()) {
                logger.log(Level.SEVERE,
                        "Problem encountered getting DB connection. Please check DB credentials", res.cause());
            } else {
                SQLConnection connection = res.result();
                //                    String sql = "insert into Trace(context,qvalue,decisionid, decisiontime,decision,score) values(?,?,?,?,?,?)";
                //                    JsonArray input = new JsonArray().
                //                            add(trace.getContext()).
                //                            add(trace.getQvalue()).
                //                            add(trace.getDecisionId()).
                //                            add(trace.getTimeStamp()).
                //                            add(trace.getOption()).
                //                            add(trace.getScore());

                String sql = "insert into Trace(context,qvalue,decisionid, decisiontime,decision,score,maxQ) values('"
                        + trace.getContext() + "'," + trace.getQvalue() + ",'" + trace.getDecisionId() + "','"
                        + trace.getTimeStamp() + "','" + trace.getOption() + "'," + trace.getScore() + ","
                        + trace.getMaxQ() + ")";

                //System.out.println("SQL:"+sql);

                connection.execute(sql, res2 -> {
                    if (res2.failed()) {
                        logger.log(Level.SEVERE, "Problem encountered when saving to DB", res2.cause());
                    }
                    connection.close();
                });

                //                    connection.setAutoCommit(false, 
                //                            res3->connection.updateWithParams(sql, input, res2 -> {
                //                                if (res2.failed()){
                //                                    connection.rollback(res5->{ 
                //                                        logger.log(Level.SEVERE, "Problem encountered when saving to DB", res2.cause());
                //                                    });
                //                                  
                //                                }else{
                //                                    connection.commit(res4->{
                //                                        connection.close();
                //                                    });
                //                                }
                //                                
                //                    }));

            }
        });
    });

}

From source file:org.eclipse.hono.adapter.http.AbstractVertxBasedHttpProtocolAdapter.java

License:Open Source License

/**
 * Gets the options to use for creating the TLS secured http server.
 * <p>//from  w  w w .j  ava  2  s  .c o  m
 * Subclasses may override this method in order to customize the server.
 * <p>
 * This method returns default options with the host and port being set to the corresponding values
 * from the <em>config</em> properties and using a maximum chunk size of 4096 bytes.
 * 
 * @return The http server options.
 */
protected HttpServerOptions getHttpServerOptions() {

    HttpServerOptions options = new HttpServerOptions();
    options.setHost(getConfig().getBindAddress()).setPort(getConfig().getPort(getPortDefaultValue()))
            .setMaxChunkSize(4096);
    addTlsKeyCertOptions(options);
    addTlsTrustOptions(options);
    return options;
}

From source file:org.eclipse.hono.adapter.http.AbstractVertxBasedHttpProtocolAdapter.java

License:Open Source License

/**
 * Gets the options to use for creating the insecure http server.
 * <p>/*  w  ww.  j ava 2  s  .co m*/
 * Subclasses may override this method in order to customize the server.
 * <p>
 * This method returns default options with the host and port being set to the corresponding values
 * from the <em>config</em> properties and using a maximum chunk size of 4096 bytes.
 * 
 * @return The http server options.
 */
protected HttpServerOptions getInsecureHttpServerOptions() {

    HttpServerOptions options = new HttpServerOptions();
    options.setHost(getConfig().getInsecurePortBindAddress())
            .setPort(getConfig().getInsecurePort(getInsecurePortDefaultValue())).setMaxChunkSize(4096);
    return options;
}

From source file:org.eclipse.hono.service.HealthCheckServer.java

License:Open Source License

/**
 * Starts the health check server if health check is configured, otherwise does nothing.
 *
 * @return a future indicating the output of the operation.
 *//* www . j av  a2 s  .  c  om*/
public Future<Void> start() {

    Future<Void> result = Future.future();
    if (router != null) {
        HttpServerOptions options = new HttpServerOptions().setPort(config.getHealthCheckPort())
                .setHost(config.getHealthCheckBindAddress());
        server = vertx.createHttpServer(options);

        router.get(URI_READINESS_PROBE).handler(readinessHandler);
        router.get(URI_LIVENESS_PROBE).handler(livenessHandler);

        server.requestHandler(router::accept).listen(startAttempt -> {
            if (startAttempt.succeeded()) {
                LOG.info("readiness probe available at http://{}:{}{}", options.getHost(), options.getPort(),
                        URI_READINESS_PROBE);
                LOG.info("liveness probe available at http://{}:{}{}", options.getHost(), options.getPort(),
                        URI_LIVENESS_PROBE);
                result.complete();
            } else {
                LOG.warn("failed to start health checks HTTP server:", startAttempt.cause().getMessage());
                result.fail(startAttempt.cause());
            }
        });

    } else { // health check port not configured
        result.complete();
    }
    return result;
}

From source file:org.entcore.workspace.Workspace.java

License:Open Source License

@Override
public void start() throws Exception {
    setResourceProvider(new WorkspaceResourcesProvider());
    super.start();

    Storage storage = new StorageFactory(vertx, config,
            new MongoDBApplicationStorage("documents", Workspace.class.getSimpleName())).getStorage();
    WorkspaceService service = new WorkspaceService();

    final boolean neo4jPlugin = config.getBoolean("neo4jPlugin", false);
    final QuotaService quotaService = new DefaultQuotaService(neo4jPlugin);

    setRepositoryEvents(new WorkspaceRepositoryEvents(vertx, storage,
            config.getBoolean("share-old-groups-to-users", false)));

    if (config.getBoolean("searching-event", true)) {
        setSearchingEvents(new WorkspaceSearchingEvents(DocumentDao.DOCUMENTS_COLLECTION));
    }// w  w  w .j av  a2  s .  co m

    service.setQuotaService(quotaService);
    service.setStorage(storage);
    addController(service);

    QuotaController quotaController = new QuotaController();
    quotaController.setQuotaService(quotaService);
    addController(quotaController);

    if (config.getInteger("wsPort") != null) {
        vertx.deployVerticle(AudioRecorderWorker.class,
                new DeploymentOptions().setConfig(config).setWorker(true));
        HttpServerOptions options = new HttpServerOptions().setMaxWebsocketFrameSize(1024 * 1024);
        vertx.createHttpServer(options).websocketHandler(new AudioRecorderHandler(vertx))
                .listen(config.getInteger("wsPort"));
    }

}

From source file:org.jspare.forvertx.web.transporter.Transporter.java

License:Apache License

/**
 * Builder.// w  w  w.  j a  v a 2  s . c  o m
 *
 * @return the transporter builder
 */
@SneakyThrows(IOException.class)
public static TransporterBuilder builder() {

    // Prepare httpServerOptions default
    HttpServerOptions httpServerOptions = new HttpServerOptions().setTcpKeepAlive(true).setReuseAddress(true);
    if (my(ResourceLoader.class).exist(DEFAULT_HTTP_OPTIONS_JSON_PATH)) {

        String content = my(ResourceLoader.class).readFileToString(DEFAULT_HTTP_OPTIONS_JSON_PATH);
        if (StringUtils.isNotEmpty(content)) {

            HttpServerOptionsConverter.fromJson(Json.decodeValue(content, JsonObject.class), httpServerOptions);
        }
    }

    return new TransporterBuilder().httpServerOptions(httpServerOptions);
}

From source file:org.sfs.SfsSingletonServer.java

License:Apache License

protected Observable<HttpServer> createHttpServer(VertxContext<Server> vertxContext, HostAndPort hostAndPort,
        int verticleMaxHeaderSize, Router router) {
    ObservableFuture<HttpServer> handler = RxHelper.observableFuture();
    HttpServerOptions httpServerOptions = new HttpServerOptions().setMaxHeaderSize(verticleMaxHeaderSize)
            .setCompressionSupported(false).setUsePooledBuffers(true).setAcceptBacklog(10000)
            .setReuseAddress(true).setHandle100ContinueAutomatically(true);
    vertxContext.vertx().createHttpServer(httpServerOptions).requestHandler(router::accept)
            .listen(hostAndPort.getPort(), hostAndPort.getHostText(), handler.toHandler());
    return handler;
}