Search in sources :

Example 11 with RouterFactoryOptions

use of io.vertx.ext.web.api.contract.RouterFactoryOptions in project vertx-examples by vert-x3.

the class OpenAPI3Server method start.

public void start(Future future) {
    // Load the api spec. This operation is asynchronous
    OpenAPI3RouterFactory.create(this.vertx, "petstore.yaml", openAPI3RouterFactoryAsyncResult -> {
        if (openAPI3RouterFactoryAsyncResult.failed()) {
            // Something went wrong during router factory initialization
            Throwable exception = openAPI3RouterFactoryAsyncResult.cause();
            logger.error("oops, something went wrong during factory initialization", exception);
            future.fail(exception);
        }
        // Spec loaded with success
        OpenAPI3RouterFactory routerFactory = openAPI3RouterFactoryAsyncResult.result();
        // Add an handler with operationId
        routerFactory.addHandlerByOperationId("listPets", routingContext -> {
            // Load the parsed parameters
            RequestParameters params = routingContext.get("parsedParameters");
            // Handle listPets operation
            RequestParameter limitParameter = params.queryParameter(/* Parameter name */
            "limit");
            if (limitParameter != null) {
                // limit parameter exists, use it!
                Integer limit = limitParameter.getInteger();
            } else {
            // limit parameter doesn't exist (it's not required).
            // If it's required you don't have to check if it's null!
            }
            routingContext.response().setStatusMessage("OK").end();
        });
        // Add a failure handler
        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 a security handler
        routerFactory.addSecurityHandler("api_key", routingContext -> {
            // Handle security here
            routingContext.next();
        });
        // Before router creation you can enable/disable various router factory behaviours
        RouterFactoryOptions factoryOptions = new RouterFactoryOptions().setMountValidationFailureHandler(// Disable mounting of dedicated validation failure handler
        false).setMountResponseContentTypeHandler(// Mount ResponseContentTypeHandler automatically
        true);
        // Now you have to generate the router
        Router router = routerFactory.setOptions(factoryOptions).getRouter();
        // Now you can use your Router instance
        server = vertx.createHttpServer(new HttpServerOptions().setPort(8080).setHost("localhost"));
        server.requestHandler(router::accept).listen((ar) -> {
            if (ar.succeeded()) {
                logger.info("Server started on port " + ar.result().actualPort());
                future.complete();
            } else {
                logger.error("oops, something went wrong during server initialization", ar.cause());
                future.fail(ar.cause());
            }
        });
    });
}
Also used : ValidationException(io.vertx.ext.web.api.validation.ValidationException) RequestParameter(io.vertx.ext.web.api.RequestParameter) RouterFactoryOptions(io.vertx.ext.web.api.contract.RouterFactoryOptions) HttpServerOptions(io.vertx.core.http.HttpServerOptions) Router(io.vertx.ext.web.Router) OpenAPI3RouterFactory(io.vertx.ext.web.api.contract.openapi3.OpenAPI3RouterFactory) RequestParameters(io.vertx.ext.web.api.RequestParameters)

Example 12 with RouterFactoryOptions

use of io.vertx.ext.web.api.contract.RouterFactoryOptions in project vertx-web by vert-x3.

the class OpenAPI3RouterFactoryTest method notRequireSecurityHandler.

@Test
public void notRequireSecurityHandler() throws Exception {
    CountDownLatch latch = new CountDownLatch(1);
    OpenAPI3RouterFactory.create(this.vertx, "src/test/resources/swaggers/router_factory_test.yaml", openAPI3RouterFactoryAsyncResult -> {
        routerFactory = openAPI3RouterFactoryAsyncResult.result();
        routerFactory.setOptions(new RouterFactoryOptions().setRequireSecurityHandlers(false));
        routerFactory.addHandlerByOperationId("listPets", routingContext -> {
            routingContext.response().setStatusCode(200).setStatusMessage(routingContext.get("message") + "OK").end();
        });
        latch.countDown();
    });
    awaitLatch(latch);
    assertNotThrow(() -> routerFactory.getRouter(), RouterFactoryException.class);
}
Also used : RouterFactoryOptions(io.vertx.ext.web.api.contract.RouterFactoryOptions) CountDownLatch(java.util.concurrent.CountDownLatch) Test(org.junit.Test)

Example 13 with RouterFactoryOptions

use of io.vertx.ext.web.api.contract.RouterFactoryOptions in project vertx-web by vert-x3.

the class OpenAPI3RouterFactoryTest method mountCustomNotImplementedHandler.

@Test
public void mountCustomNotImplementedHandler() throws Exception {
    CountDownLatch latch = new CountDownLatch(1);
    OpenAPI3RouterFactory.create(this.vertx, "src/test/resources/swaggers/router_factory_test.yaml", openAPI3RouterFactoryAsyncResult -> {
        routerFactory = openAPI3RouterFactoryAsyncResult.result();
        routerFactory.setOptions(new RouterFactoryOptions().setMountNotImplementedHandler(true).setRequireSecurityHandlers(false).setNotImplementedFailureHandler(routingContext -> routingContext.response().setStatusCode(501).setStatusMessage("We are too lazy to implement this operation").end()));
        latch.countDown();
    });
    awaitLatch(latch);
    startServer();
    testRequest(HttpMethod.GET, "/pets", 501, "We are too lazy to implement this operation");
}
Also used : ValidationException(io.vertx.ext.web.api.validation.ValidationException) MultiMap(io.vertx.core.MultiMap) Router(io.vertx.ext.web.Router) RouterFactoryException(io.vertx.ext.web.api.contract.RouterFactoryException) Test(org.junit.Test) RoutingContext(io.vertx.ext.web.RoutingContext) BodyHandler(io.vertx.ext.web.handler.BodyHandler) Collectors(java.util.stream.Collectors) RouterFactoryOptions(io.vertx.ext.web.api.contract.RouterFactoryOptions) CountDownLatch(java.util.concurrent.CountDownLatch) URLEncoder(java.net.URLEncoder) List(java.util.List) Stream(java.util.stream.Stream) Paths(java.nio.file.Paths) HttpMethod(io.vertx.core.http.HttpMethod) RequestParameters(io.vertx.ext.web.api.RequestParameters) HttpServerOptions(io.vertx.core.http.HttpServerOptions) JsonObject(io.vertx.core.json.JsonObject) HttpClientOptions(io.vertx.core.http.HttpClientOptions) Handler(io.vertx.core.Handler) WebTestWithWebClientBase(io.vertx.ext.web.WebTestWithWebClientBase) RouterFactoryOptions(io.vertx.ext.web.api.contract.RouterFactoryOptions) CountDownLatch(java.util.concurrent.CountDownLatch) Test(org.junit.Test)

Example 14 with RouterFactoryOptions

use of io.vertx.ext.web.api.contract.RouterFactoryOptions in project vertx-web by vert-x3.

the class OpenAPI3RouterFactoryTest method notMountNotImplementedHandler.

@Test
public void notMountNotImplementedHandler() throws Exception {
    CountDownLatch latch = new CountDownLatch(1);
    OpenAPI3RouterFactory.create(this.vertx, "src/test/resources/swaggers/router_factory_test.yaml", openAPI3RouterFactoryAsyncResult -> {
        routerFactory = openAPI3RouterFactoryAsyncResult.result();
        routerFactory.setOptions(new RouterFactoryOptions().setMountNotImplementedHandler(false));
        latch.countDown();
    });
    awaitLatch(latch);
    startServer();
    testRequest(HttpMethod.GET, "/pets", 404, "Not Found");
}
Also used : RouterFactoryOptions(io.vertx.ext.web.api.contract.RouterFactoryOptions) CountDownLatch(java.util.concurrent.CountDownLatch) Test(org.junit.Test)

Example 15 with RouterFactoryOptions

use of io.vertx.ext.web.api.contract.RouterFactoryOptions in project vertx-web by vert-x3.

the class OpenAPI3RouterFactoryTest method producesTest.

@Test
public void producesTest() throws Exception {
    CountDownLatch latch = new CountDownLatch(1);
    OpenAPI3RouterFactory.create(this.vertx, "src/test/resources/swaggers/produces_consumes_test.yaml", openAPI3RouterFactoryAsyncResult -> {
        routerFactory = openAPI3RouterFactoryAsyncResult.result();
        routerFactory.setOptions(new RouterFactoryOptions().setMountNotImplementedHandler(false));
        routerFactory.addHandlerByOperationId("producesTest", routingContext -> {
            if (((RequestParameters) routingContext.get("parsedParameters")).queryParameter("fail").getBoolean())
                routingContext.response().putHeader("content-type", "text/plain").setStatusCode(500).end("Hate it");
            else
                // ResponseContentTypeHandler does the job for me
                routingContext.response().setStatusCode(200).end("{}");
        });
        latch.countDown();
    });
    awaitLatch(latch);
    startServer();
    List<String> acceptableContentTypes = Stream.of("application/json", "text/plain").collect(Collectors.toList());
    testRequestWithResponseContentTypeCheck(HttpMethod.GET, "/producesTest", 200, "application/json", acceptableContentTypes);
    testRequestWithResponseContentTypeCheck(HttpMethod.GET, "/producesTest?fail=true", 500, "text/plain", acceptableContentTypes);
}
Also used : RouterFactoryOptions(io.vertx.ext.web.api.contract.RouterFactoryOptions) CountDownLatch(java.util.concurrent.CountDownLatch) Test(org.junit.Test)

Aggregations

RouterFactoryOptions (io.vertx.ext.web.api.contract.RouterFactoryOptions)17 CountDownLatch (java.util.concurrent.CountDownLatch)13 Test (org.junit.Test)12 RequestParameters (io.vertx.ext.web.api.RequestParameters)5 ValidationException (io.vertx.ext.web.api.validation.ValidationException)4 MultiMap (io.vertx.core.MultiMap)3 HttpServerOptions (io.vertx.core.http.HttpServerOptions)3 JsonObject (io.vertx.core.json.JsonObject)3 Router (io.vertx.ext.web.Router)3 OpenAPI3RouterFactory (io.vertx.ext.web.api.contract.openapi3.OpenAPI3RouterFactory)3 HttpClientOptions (io.vertx.core.http.HttpClientOptions)2 RoutingContext (io.vertx.ext.web.RoutingContext)2 Handler (io.vertx.core.Handler)1 HttpMethod (io.vertx.core.http.HttpMethod)1 HttpServer (io.vertx.core.http.HttpServer)1 WebTestWithWebClientBase (io.vertx.ext.web.WebTestWithWebClientBase)1 RequestParameter (io.vertx.ext.web.api.RequestParameter)1 RouterFactoryException (io.vertx.ext.web.api.contract.RouterFactoryException)1 OpenAPI3RouterFactoryImpl (io.vertx.ext.web.api.contract.openapi3.impl.OpenAPI3RouterFactoryImpl)1 BodyHandler (io.vertx.ext.web.handler.BodyHandler)1