Search in sources :

Example 1 with ValidationException

use of io.vertx.ext.web.api.validation.ValidationException in project vertx-web by vert-x3.

the class OpenAPI3RouterFactoryTest method notMountValidationFailureHandler.

@Test
public void notMountValidationFailureHandler() 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).setMountValidationFailureHandler(false));
        routerFactory.addHandlerByOperationId("listPets", routingContext -> {
            routingContext.response().setStatusCode(200).setStatusMessage(((RequestParameters) routingContext.get("parsedParameters")).queryParameter("limit").toString()).end();
        });
        routerFactory.addFailureHandlerByOperationId("listPets", routingContext -> {
            routingContext.response().setStatusCode((routingContext.failure() instanceof ValidationException) ? 400 : 500).setStatusMessage((routingContext.failure() instanceof ValidationException) ? "Very very Bad Request" : "Error").end();
        });
        latch.countDown();
    });
    awaitLatch(latch);
    startServer();
    testRequest(HttpMethod.GET, "/pets?limit=hello", 400, "Very very Bad Request");
    testRequest(HttpMethod.GET, "/pets?limit=10", 200, "10");
}
Also used : ValidationException(io.vertx.ext.web.api.validation.ValidationException) RouterFactoryOptions(io.vertx.ext.web.api.contract.RouterFactoryOptions) CountDownLatch(java.util.concurrent.CountDownLatch) Test(org.junit.Test)

Example 2 with ValidationException

use of io.vertx.ext.web.api.validation.ValidationException 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 3 with ValidationException

use of io.vertx.ext.web.api.validation.ValidationException in project vertx-examples by vert-x3.

the class ValidationExampleServer method start.

@Override
public void start() throws Exception {
    Router router = Router.router(vertx);
    // If you want to validate bodies, don't miss that handler!
    router.route().handler(BodyHandler.create());
    // Create Validation Handler with some stuff
    HTTPRequestValidationHandler validationHandler = HTTPRequestValidationHandler.create().addQueryParam("parameterName", ParameterType.INT, true).addFormParamWithPattern("formParameterName", "a{4}", true).addPathParam("pathParam", ParameterType.FLOAT);
    router.post("/hello").handler(validationHandler).handler((routingContext) -> {
        // To consume parameters you can get it in the "classic way" of Vert.x Web
        // or you can use the RequestParameters that contains parameters already parsed (and maybe transformed)
        // Get RequestParameters container
        RequestParameters params = routingContext.get("parsedParameters");
        // Get parameters
        Integer parameterName = params.queryParameter("parameterName").getInteger();
        String formParameterName = params.formParameter("formParameterName").getString();
        Float pathParam = params.pathParameter("pathParam").getFloat();
    // Do awesome things with your parameters!
    }).failureHandler((routingContext) -> {
        Throwable failure = routingContext.failure();
        if (failure instanceof ValidationException) {
            // Something went wrong during validation!
            String validationErrorMessage = failure.getMessage();
            routingContext.response().setStatusCode(400).end();
        }
    });
    // A very basic example of JSON body validation
    router.post("/jsonUploader").handler(HTTPRequestValidationHandler.create().addJsonBodySchema("{type: string}")).handler((routingContext -> {
        RequestParameters params = routingContext.get("parsedParameters");
        JsonObject body = params.body().getJsonObject();
    }));
    // Write your own parameter type validator
    ParameterTypeValidator primeCustomTypeValidator = value -> {
        try {
            int number = Integer.parseInt(value);
            // Yeah I know this is a lazy way to check if number is prime :)
            for (int i = 2; i < number; i++) {
                if (// Number is not prime
                number % i == 0)
                    throw ValidationException.ValidationExceptionFactory.generateNotMatchValidationException("Number is not prime!");
            }
            // We pass directly the parsed parameter
            return RequestParameter.create(number);
        } catch (NumberFormatException e) {
            throw ValidationException.ValidationExceptionFactory.generateNotMatchValidationException("Wrong integer format");
        }
    };
    // Now we create the route and mount the HTTPRequestValidationHandler
    router.get("/superAwesomeParameter").handler(HTTPRequestValidationHandler.create().addQueryParamWithCustomTypeValidator("primeNumber", primeCustomTypeValidator, true, false)).handler((routingContext -> {
        RequestParameters params = routingContext.get("parsedParameters");
        Integer primeNumber = params.queryParameter("primeNumber").getInteger();
    }));
    vertx.createHttpServer().requestHandler(router::accept).listen();
}
Also used : ParameterTypeValidator(io.vertx.ext.web.api.validation.ParameterTypeValidator) ValidationException(io.vertx.ext.web.api.validation.ValidationException) RequestParameter(io.vertx.ext.web.api.RequestParameter) AbstractVerticle(io.vertx.core.AbstractVerticle) RequestParameters(io.vertx.ext.web.api.RequestParameters) HttpServerOptions(io.vertx.core.http.HttpServerOptions) Router(io.vertx.ext.web.Router) JsonObject(io.vertx.core.json.JsonObject) HTTPRequestValidationHandler(io.vertx.ext.web.api.validation.HTTPRequestValidationHandler) BodyHandler(io.vertx.ext.web.handler.BodyHandler) Runner(io.vertx.example.util.Runner) ParameterType(io.vertx.ext.web.api.validation.ParameterType) ValidationException(io.vertx.ext.web.api.validation.ValidationException) ParameterTypeValidator(io.vertx.ext.web.api.validation.ParameterTypeValidator) Router(io.vertx.ext.web.Router) JsonObject(io.vertx.core.json.JsonObject) HTTPRequestValidationHandler(io.vertx.ext.web.api.validation.HTTPRequestValidationHandler) RequestParameters(io.vertx.ext.web.api.RequestParameters)

Example 4 with ValidationException

use of io.vertx.ext.web.api.validation.ValidationException in project vertx-web by vert-x3.

the class XMLTypeValidator method isValid.

@Override
public RequestParameter isValid(String value) throws ValidationException {
    try {
        DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        Document document = parser.parse(value);
        this.schemaValidator.validate(new DOMSource(document));
        return RequestParameter.create(document);
    } catch (Exception e) {
        throw ValidationException.ValidationExceptionFactory.generateInvalidXMLBodyException(e.getMessage());
    }
}
Also used : DOMSource(javax.xml.transform.dom.DOMSource) DocumentBuilder(javax.xml.parsers.DocumentBuilder) Document(org.w3c.dom.Document) ValidationException(io.vertx.ext.web.api.validation.ValidationException) SAXException(org.xml.sax.SAXException)

Example 5 with ValidationException

use of io.vertx.ext.web.api.validation.ValidationException 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)

Aggregations

ValidationException (io.vertx.ext.web.api.validation.ValidationException)5 HttpServerOptions (io.vertx.core.http.HttpServerOptions)3 Router (io.vertx.ext.web.Router)3 RequestParameters (io.vertx.ext.web.api.RequestParameters)3 RouterFactoryOptions (io.vertx.ext.web.api.contract.RouterFactoryOptions)3 JsonObject (io.vertx.core.json.JsonObject)2 RequestParameter (io.vertx.ext.web.api.RequestParameter)2 OpenAPI3RouterFactory (io.vertx.ext.web.api.contract.openapi3.OpenAPI3RouterFactory)2 AbstractVerticle (io.vertx.core.AbstractVerticle)1 HttpServer (io.vertx.core.http.HttpServer)1 Runner (io.vertx.example.util.Runner)1 HTTPRequestValidationHandler (io.vertx.ext.web.api.validation.HTTPRequestValidationHandler)1 ParameterType (io.vertx.ext.web.api.validation.ParameterType)1 ParameterTypeValidator (io.vertx.ext.web.api.validation.ParameterTypeValidator)1 BodyHandler (io.vertx.ext.web.handler.BodyHandler)1 CountDownLatch (java.util.concurrent.CountDownLatch)1 DocumentBuilder (javax.xml.parsers.DocumentBuilder)1 DOMSource (javax.xml.transform.dom.DOMSource)1 Test (org.junit.Test)1 Document (org.w3c.dom.Document)1