Search in sources :

Example 71 with HttpServer

use of io.vertx.core.http.HttpServer in project georocket by georocket.

the class StoreEndpointTest method setupMockEndpoint.

private static Observable<HttpServer> setupMockEndpoint() {
    JsonObject config = vertx.getOrCreateContext().config();
    String host = config.getString(ConfigConstants.HOST, ConfigConstants.DEFAULT_HOST);
    int port = config.getInteger(ConfigConstants.PORT, ConfigConstants.DEFAULT_PORT);
    HttpServerOptions serverOptions = new HttpServerOptions().setCompressionSupported(true);
    HttpServer server = vertxCore.createHttpServer(serverOptions);
    ObservableFuture<HttpServer> observable = RxHelper.observableFuture();
    server.requestHandler(getStoreEndpointRouter()::accept).listen(port, host, observable.toHandler());
    return observable;
}
Also used : HttpServerOptions(io.vertx.core.http.HttpServerOptions) HttpServer(io.vertx.core.http.HttpServer) JsonObject(io.vertx.core.json.JsonObject)

Example 72 with HttpServer

use of io.vertx.core.http.HttpServer in project incubator-servicecomb-java-chassis by apache.

the class RestServerVerticle method start.

@Override
public void start(Future<Void> startFuture) throws Exception {
    try {
        super.start();
        // 如果本地未配置地址,则表示不必监听,只需要作为客户端使用即可
        if (endpointObject == null) {
            LOGGER.warn("rest listen address is not configured, will not start.");
            startFuture.complete();
            return;
        }
        Router mainRouter = Router.router(vertx);
        mountAccessLogHandler(mainRouter);
        initDispatcher(mainRouter);
        HttpServer httpServer = createHttpServer();
        httpServer.requestHandler(mainRouter::accept);
        startListen(httpServer, startFuture);
    } catch (Throwable e) {
        // vert.x got some states that not print error and execute call back in VertexUtils.blockDeploy, we add a log our self.
        LOGGER.error("", e);
        throw e;
    }
}
Also used : HttpServer(io.vertx.core.http.HttpServer) Router(io.vertx.ext.web.Router)

Example 73 with HttpServer

use of io.vertx.core.http.HttpServer in project microservices by pwillhan.

the class MainVerticle method startHttpServer.

private Future<Void> startHttpServer() {
    System.out.println("#startHttpServer");
    Future<Void> future = Future.future();
    // <1>
    HttpServer server = vertx.createHttpServer();
    // <2>
    Router router = Router.router(vertx);
    // Bind "/" to our hello message - so are still compatible.
    router.route("/").handler(routingContext -> {
        HttpServerResponse response = routingContext.response();
        response.putHeader("content-type", "text/html").end("<h1>Hello from Vert.x 3</h1>");
    });
    // Enables the reading of the request body for all routes under "/api/customers".
    router.route("/api/customers*").handler(BodyHandler.create());
    // GET all
    // curl http://localhost:8080/api/customers
    router.get("/api/customers").handler(this::getAll);
    // POST
    // curl -X POST http://localhost:8080/api/customers -H 'content-type: application/json' -d '{"name": "Tom", "age": "18"}'
    router.post("/api/customers").handler(this::addOne);
    server.requestHandler(// <5>
    router::accept).listen(8080, ar -> {
        // <6>
        if (ar.succeeded()) {
            LOGGER.info("HTTP server running on port 8080");
            future.complete();
        } else {
            LOGGER.error("Could not start a HTTP server", ar.cause());
            future.fail(ar.cause());
        }
    });
    return future;
}
Also used : HttpServerResponse(io.vertx.core.http.HttpServerResponse) HttpServer(io.vertx.core.http.HttpServer) Router(io.vertx.ext.web.Router)

Example 74 with HttpServer

use of io.vertx.core.http.HttpServer in project raml-module-builder by folio-org.

the class RestVerticle method start.

@Override
public void start(Future<Void> startFuture) throws Exception {
    readInGitProps();
    // process cmd line arguments
    cmdProcessing();
    deploymentId = UUID.randomUUID().toString();
    LogUtil.formatLogMessage(className, "start", "metrics enabled: " + vertx.isMetricsEnabled());
    serverMetrics = MetricsService.create(vertx);
    // maps paths found in raml to the generated functions to route to when the paths are requested
    MappedClasses mappedURLs = populateConfig();
    // set of exposed urls as declared in the raml
    Set<String> urlPaths = mappedURLs.getAvailURLs();
    // create a map of regular expression to url path
    Map<String, Pattern> regex2Pattern = mappedURLs.buildURLRegex();
    // Create a router object.
    Router router = Router.router(vertx);
    eventBus = vertx.eventBus();
    log.info(context.getInstanceCount() + " verticles deployed ");
    try {
        // register codec to be able to pass pojos on the event bus
        eventBus.registerCodec(new PojoEventBusCodec());
    } catch (Exception e3) {
        if (e3.getMessage().startsWith("Already a codec registered with name")) {
            // needed in case we run multiple verticle instances
            // in this vertx instace - re-registering the same codec twice throws an
            // exception
            log.info("Attempt to register PojoEventBusCodec again... this is acceptable ");
        } else {
            throw e3;
        }
    }
    // needed so that we get the body content of the request - note that this
    // will read the entire body into memory
    final BodyHandler handler = BodyHandler.create();
    // IMPORTANT!!!
    // the body of the request will be read into memory for ALL PUT requests
    // and for POST requests with the content-types below ONLY!!!
    // multipart, for example will not be read by the body handler as vertx saves
    // multiparts and www-encoded to disk - hence multiparts will be handled differently
    // see uploadHandler further down
    router.put().handler(handler);
    router.post().consumes(SUPPORTED_CONTENT_TYPE_JSON_DEF).handler(handler);
    router.post().consumes(SUPPORTED_CONTENT_TYPE_TEXT_DEF).handler(handler);
    router.post().consumes(SUPPORTED_CONTENT_TYPE_XML_DEF).handler(handler);
    router.post().consumes(SUPPORTED_CONTENT_TYPE_FORM).handler(handler);
    // run pluggable startup code in a class implementing the InitAPI interface
    // in the "org.folio.rest.impl" package
    runHook(vv -> {
        if (((Future<?>) vv).failed()) {
            String reason = ((Future<?>) vv).cause().getMessage();
            log.error(messages.getMessage("en", MessageConsts.InitializeVerticleFail, reason));
            startFuture.fail(reason);
            vertx.close();
            System.exit(-1);
        } else {
            log.info("init succeeded.......");
            try {
                // startup periodic impl if exists
                runPeriodicHook();
            } catch (Exception e2) {
                log.error(e2);
            }
            // single handler for all url calls other then documentation
            // which is handled separately
            router.routeWithRegex("^(?!.*apidocs).*$").handler(rc -> route(mappedURLs, urlPaths, regex2Pattern, rc));
            // routes requests on “/assets/*” to resources stored in the “assets”
            // directory.
            router.route("/assets/*").handler(StaticHandler.create("assets"));
            // In the following example all requests to paths starting with
            // /apidocs/ will get served from the directory resources/apidocs:
            // example:
            // http://localhost:8181/apidocs/index.html?raml=raml/_patrons.raml
            router.route("/apidocs/*").handler(StaticHandler.create("apidocs"));
            // startup http server on port 8181 to serve documentation
            if (port == -1) {
                // we are here if port was not passed via cmd line
                port = config().getInteger("http.port", 8081);
            }
            // check if mock mode requested and set sys param so that http client factory
            // can config itself accordingly
            String mockMode = config().getString(HttpClientMock2.MOCK_MODE);
            if (mockMode != null) {
                System.setProperty(HttpClientMock2.MOCK_MODE, mockMode);
            }
            // in anycase set the port so it is available to others via the config()
            config().put("http.port", port);
            Integer p = port;
            // if client includes an Accept-Encoding header which includes
            // the supported compressions - deflate or gzip.
            HttpServerOptions serverOptions = new HttpServerOptions();
            serverOptions.setCompressionSupported(false);
            HttpServer server = vertx.createHttpServer(serverOptions);
            server.requestHandler(router::accept).listen(p, // default to 8181.
            result -> {
                if (result.failed()) {
                    startFuture.fail(result.cause());
                } else {
                    try {
                        runPostDeployHook(res2 -> {
                            if (!res2.succeeded()) {
                                log.error(res2.cause().getMessage(), res2.cause());
                            }
                        });
                    } catch (Exception e) {
                        log.error(e.getMessage(), e);
                    }
                    LogUtil.formatLogMessage(className, "start", "http server for apis and docs started on port " + p + ".");
                    LogUtil.formatLogMessage(className, "start", "Documentation available at: " + "http://localhost:" + Integer.toString(p) + "/apidocs/");
                    startFuture.complete();
                }
            });
        }
    });
}
Also used : Pattern(java.util.regex.Pattern) HttpServerOptions(io.vertx.core.http.HttpServerOptions) Router(io.vertx.ext.web.Router) UnrecognizedPropertyException(com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException) MessagingException(javax.mail.MessagingException) IOException(java.io.IOException) PojoEventBusCodec(org.folio.rest.tools.codecs.PojoEventBusCodec) BodyHandler(io.vertx.ext.web.handler.BodyHandler) HttpServer(io.vertx.core.http.HttpServer) Future(io.vertx.core.Future)

Example 75 with HttpServer

use of io.vertx.core.http.HttpServer in project vertx-micrometer-metrics by vert-x3.

the class VertxHttpClientServerMetricsTest method setUp.

@Before
public void setUp(TestContext ctx) {
    vertx = Vertx.vertx(new VertxOptions().setMetricsOptions(new MicrometerMetricsOptions().setPrometheusOptions(new VertxPrometheusOptions().setEnabled(true)).setRegistryName(registryName).setEnabled(true))).exceptionHandler(ctx.exceptionHandler());
    // Setup server
    Async serverReady = ctx.async();
    vertx.deployVerticle(new AbstractVerticle() {

        @Override
        public void start(Future<Void> future) throws Exception {
            httpServer = vertx.createHttpServer();
            httpServer.websocketHandler(ws -> ws.handler(event -> {
                vertx.setTimer(REQ_DELAY, timer -> ws.writeTextMessage(SERVER_RESPONSE).end());
            })).requestHandler(req -> {
                // Timer as artificial processing time
                vertx.setTimer(REQ_DELAY, handler -> req.response().setChunked(true).putHeader("Content-Type", "text/plain").write(SERVER_RESPONSE).end());
            }).listen(9195, "127.0.0.1", r -> {
                if (r.failed()) {
                    ctx.fail(r.cause());
                } else {
                    serverReady.complete();
                }
            });
        }
    });
    serverReady.awaitSuccess();
}
Also used : TestContext(io.vertx.ext.unit.TestContext) Async(io.vertx.ext.unit.Async) HttpServer(io.vertx.core.http.HttpServer) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) Vertx(io.vertx.core.Vertx) RunWith(org.junit.runner.RunWith) VertxOptions(io.vertx.core.VertxOptions) Test(org.junit.Test) VertxUnitRunner(io.vertx.ext.unit.junit.VertxUnitRunner) UUID(java.util.UUID) Future(io.vertx.core.Future) Collectors(java.util.stream.Collectors) RegistryInspector.dp(io.vertx.micrometer.RegistryInspector.dp) List(java.util.List) ForkJoinPool(java.util.concurrent.ForkJoinPool) AbstractVerticle(io.vertx.core.AbstractVerticle) After(org.junit.After) HttpClient(io.vertx.core.http.HttpClient) Before(org.junit.Before) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) Async(io.vertx.ext.unit.Async) VertxOptions(io.vertx.core.VertxOptions) AbstractVerticle(io.vertx.core.AbstractVerticle) Before(org.junit.Before)

Aggregations

HttpServer (io.vertx.core.http.HttpServer)82 Router (io.vertx.ext.web.Router)37 HttpServerOptions (io.vertx.core.http.HttpServerOptions)32 Test (org.junit.Test)24 JsonObject (io.vertx.core.json.JsonObject)17 Buffer (io.vertx.core.buffer.Buffer)14 HttpServerResponse (io.vertx.core.http.HttpServerResponse)14 Future (io.vertx.core.Future)12 HttpClient (io.vertx.core.http.HttpClient)12 Vertx (io.vertx.core.Vertx)11 CountDownLatch (java.util.concurrent.CountDownLatch)10 Handler (io.vertx.core.Handler)9 HttpMethod (io.vertx.core.http.HttpMethod)9 VertxOptions (io.vertx.core.VertxOptions)8 HttpClientOptions (io.vertx.core.http.HttpClientOptions)8 List (java.util.List)8 AbstractVerticle (io.vertx.core.AbstractVerticle)7 PemKeyCertOptions (io.vertx.core.net.PemKeyCertOptions)7 AtomicReference (java.util.concurrent.atomic.AtomicReference)7 AsyncResult (io.vertx.core.AsyncResult)6