Search in sources :

Example 1 with HTTPRequestValidationHandler

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

Aggregations

AbstractVerticle (io.vertx.core.AbstractVerticle)1 HttpServerOptions (io.vertx.core.http.HttpServerOptions)1 JsonObject (io.vertx.core.json.JsonObject)1 Runner (io.vertx.example.util.Runner)1 Router (io.vertx.ext.web.Router)1 RequestParameter (io.vertx.ext.web.api.RequestParameter)1 RequestParameters (io.vertx.ext.web.api.RequestParameters)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 ValidationException (io.vertx.ext.web.api.validation.ValidationException)1 BodyHandler (io.vertx.ext.web.handler.BodyHandler)1