Search in sources :

Example 56 with HttpServer

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

the class MainVerticle method start.

@Override
public void start(Future<Void> startFuture) throws Exception {
    // PORT env check
    try {
        PORT = Integer.parseInt(System.getenv("PORT"));
    } catch (Exception e) {
        logger.warn("Environment variable PORT not found or not valid. Defautling to: " + PORT);
    }
    // Create HTTP server
    HttpServer httpServer = getVertx().createHttpServer();
    // Set Router
    Router mainRouter = Router.router(getVertx());
    mainRouter.route("/*").handler(StaticHandler.create());
    httpServer.requestHandler(mainRouter::accept);
    // Start listening
    httpServer.listen(PORT, asyncResult -> {
        if (asyncResult.succeeded()) {
            logger.info("Listening on port: " + PORT);
            startFuture.complete();
        } else {
            logger.error("Failed to bind on port " + PORT + ". Is it being used?");
            startFuture.fail(asyncResult.cause());
        }
    });
}
Also used : HttpServer(io.vertx.core.http.HttpServer) Router(io.vertx.ext.web.Router)

Example 57 with HttpServer

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

the class OpenAPI3Examples method mainExample.

public void mainExample(Vertx vertx) {
    // Load the api spec. This operation is asynchronous
    OpenAPI3RouterFactory.create(vertx, "src/main/resources/petstore.yaml", openAPI3RouterFactoryAsyncResult -> {
        if (openAPI3RouterFactoryAsyncResult.succeeded()) {
            // Spec loaded with success, retrieve the router
            OpenAPI3RouterFactory routerFactory = openAPI3RouterFactoryAsyncResult.result();
            // You can enable or disable different features of router factory through mounting RouterFactoryOptions
            // For example you can enable or disable the default failure handler for ValidationException
            RouterFactoryOptions options = new RouterFactoryOptions().setMountValidationFailureHandler(false);
            // Mount the options
            routerFactory.setOptions(options);
            // Add an handler with operationId
            routerFactory.addHandlerByOperationId("listPets", routingContext -> {
                // Handle listPets operation
                routingContext.response().setStatusMessage("Called listPets").end();
            });
            // Add a failure handler to the same operationId
            routerFactory.addFailureHandlerByOperationId("listPets", routingContext -> {
                // This is the failure handler
                Throwable failure = routingContext.failure();
                if (failure instanceof ValidationException)
                    // Handle Validation Exception
                    routingContext.response().setStatusCode(400).setStatusMessage("ValidationException thrown! " + ((ValidationException) failure).type().name()).end();
            });
            // Add an handler with a combination of HttpMethod and path
            routerFactory.addHandler(HttpMethod.POST, "/pets", routingContext -> {
                // Extract request body and use it
                RequestParameters params = routingContext.get("parsedParameters");
                JsonObject pet = params.body().getJsonObject();
                routingContext.response().putHeader("content-type", "application/json; charset=utf-8").end(pet.encodePrettily());
            });
            // Add a security handler
            routerFactory.addSecurityHandler("api_key", routingContext -> {
                // Handle security here
                routingContext.next();
            });
            // Now you have to generate the router
            Router router = routerFactory.getRouter();
            // Now you can use your Router instance
            HttpServer server = vertx.createHttpServer(new HttpServerOptions().setPort(8080).setHost("localhost"));
            server.requestHandler(router::accept).listen();
        } else {
            // Something went wrong during router factory initialization
            Throwable exception = openAPI3RouterFactoryAsyncResult.cause();
        }
    });
}
Also used : ValidationException(io.vertx.ext.web.api.validation.ValidationException) RouterFactoryOptions(io.vertx.ext.web.api.contract.RouterFactoryOptions) HttpServer(io.vertx.core.http.HttpServer) HttpServerOptions(io.vertx.core.http.HttpServerOptions) JsonObject(io.vertx.core.json.JsonObject) Router(io.vertx.ext.web.Router) OpenAPI3RouterFactory(io.vertx.ext.web.api.contract.openapi3.OpenAPI3RouterFactory) RequestParameters(io.vertx.ext.web.api.RequestParameters)

Example 58 with HttpServer

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

the class OpenAPI3Examples method generateRouter.

public void generateRouter(Vertx vertx, OpenAPI3RouterFactory routerFactory) {
    Router router = routerFactory.getRouter();
    HttpServer server = vertx.createHttpServer(new HttpServerOptions().setPort(8080).setHost("localhost"));
    server.requestHandler(router::accept).listen();
}
Also used : HttpServer(io.vertx.core.http.HttpServer) HttpServerOptions(io.vertx.core.http.HttpServerOptions) Router(io.vertx.ext.web.Router)

Example 59 with HttpServer

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

the class WebClientTest method testStreamHttpServerRequest.

@Test
public void testStreamHttpServerRequest() throws Exception {
    Buffer expected = TestUtils.randomBuffer(10000);
    HttpServer server2 = vertx.createHttpServer(new HttpServerOptions().setPort(8081)).requestHandler(req -> req.bodyHandler(body -> {
        assertEquals(body, expected);
        req.response().end();
    }));
    startServer(server2);
    WebClient webClient = WebClient.create(vertx);
    try {
        server.requestHandler(req -> webClient.postAbs("http://localhost:8081/").sendStream(req, onSuccess(resp -> req.response().end("ok"))));
        startServer();
        webClient.post(8080, "localhost", "/").sendBuffer(expected, onSuccess(resp -> {
            assertEquals("ok", resp.bodyAsString());
            complete();
        }));
        await();
    } finally {
        server2.close();
    }
}
Also used : Buffer(io.vertx.core.buffer.Buffer) VertxException(io.vertx.core.VertxException) AsyncFile(io.vertx.core.file.AsyncFile) HttpServerRequest(io.vertx.core.http.HttpServerRequest) Arrays(java.util.Arrays) DecodeException(io.vertx.core.json.DecodeException) HttpServer(io.vertx.core.http.HttpServer) MultiMap(io.vertx.core.MultiMap) BodyCodec(io.vertx.ext.web.codec.BodyCodec) TimeoutException(java.util.concurrent.TimeoutException) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) CompletableFuture(java.util.concurrent.CompletableFuture) Cert(io.vertx.test.core.tls.Cert) AddressResolverOptions(io.vertx.core.dns.AddressResolverOptions) AtomicReference(java.util.concurrent.atomic.AtomicReference) Function(java.util.function.Function) HttpTestBase(io.vertx.test.core.HttpTestBase) TestUtils(io.vertx.test.core.TestUtils) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) WriteStream(io.vertx.core.streams.WriteStream) ReadStream(io.vertx.core.streams.ReadStream) BiConsumer(java.util.function.BiConsumer) JsonObject(io.vertx.core.json.JsonObject) ConnectException(java.net.ConnectException) HttpClientOptions(io.vertx.core.http.HttpClientOptions) HttpConnection(io.vertx.core.http.HttpConnection) ProxyOptions(io.vertx.core.net.ProxyOptions) OpenOptions(io.vertx.core.file.OpenOptions) Files(java.nio.file.Files) VertxOptions(io.vertx.core.VertxOptions) HttpHeaders(io.vertx.core.http.HttpHeaders) Test(org.junit.Test) File(java.io.File) Consumer(java.util.function.Consumer) JsonArray(io.vertx.core.json.JsonArray) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) Buffer(io.vertx.core.buffer.Buffer) ProxyType(io.vertx.core.net.ProxyType) HttpMethod(io.vertx.core.http.HttpMethod) HttpServerResponse(io.vertx.core.http.HttpServerResponse) WineAndCheese(io.vertx.ext.web.client.jackson.WineAndCheese) HttpServerOptions(io.vertx.core.http.HttpServerOptions) Handler(io.vertx.core.Handler) Collections(java.util.Collections) HttpServer(io.vertx.core.http.HttpServer) HttpServerOptions(io.vertx.core.http.HttpServerOptions) Test(org.junit.Test)

Example 60 with HttpServer

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

the class WebExamples method example1.

public void example1(Vertx vertx) {
    HttpServer server = vertx.createHttpServer();
    server.requestHandler(request -> {
        // This handler gets called for each request that arrives on the server
        HttpServerResponse response = request.response();
        response.putHeader("content-type", "text/plain");
        // Write to the response and end it
        response.end("Hello World!");
    });
    server.listen(8080);
}
Also used : HttpServerResponse(io.vertx.core.http.HttpServerResponse) HttpServer(io.vertx.core.http.HttpServer)

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