Search in sources :

Example 81 with RequestParameters

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

the class HTTPRequestValidationTest method testQueryParamsArrayAndPathParamsFailureWithIncludedTypes.

@Test
public void testQueryParamsArrayAndPathParamsFailureWithIncludedTypes() throws Exception {
    HTTPRequestValidationHandler validationHandler = HTTPRequestValidationHandler.create().addPathParam("pathParam1", ParameterType.INT).addQueryParamsArray("awesomeArray", ParameterType.EMAIL, true).addQueryParam("anotherParam", ParameterType.DOUBLE, true);
    router.get("/testQueryParams/:pathParam1").handler(validationHandler);
    router.get("/testQueryParams/:pathParam1").handler(routingContext -> {
        RequestParameters params = routingContext.get("parsedParameters");
        routingContext.response().setStatusMessage(params.pathParameter("pathParam1").getInteger().toString() + params.queryParameter("awesomeArray").getArray().size() + params.queryParameter("anotherParam").getDouble().toString()).end();
    }).failureHandler(generateFailureHandler(true));
    String pathParam = getSuccessSample(ParameterType.INT).getInteger().toString();
    String arrayValue1 = getFailureSample(ParameterType.EMAIL);
    String arrayValue2 = getSuccessSample(ParameterType.EMAIL).getString();
    String anotherParam = getSuccessSample(ParameterType.DOUBLE).getDouble().toString();
    QueryStringEncoder encoder = new QueryStringEncoder("/testQueryParams/" + URLEncoder.encode(pathParam, "UTF-8"));
    encoder.addParam("awesomeArray", arrayValue1);
    encoder.addParam("awesomeArray", arrayValue2);
    encoder.addParam("anotherParam", anotherParam);
    testRequest(HttpMethod.GET, encoder.toString(), 400, "failure:NO_MATCH");
}
Also used : QueryStringEncoder(io.netty.handler.codec.http.QueryStringEncoder) URLEncoder(java.net.URLEncoder) HttpMethod(io.vertx.core.http.HttpMethod) MultiMap(io.vertx.core.MultiMap) RequestParameters(io.vertx.ext.web.api.RequestParameters) Test(org.junit.Test) BodyHandler(io.vertx.ext.web.handler.BodyHandler) QueryStringEncoder(io.netty.handler.codec.http.QueryStringEncoder) RequestParameters(io.vertx.ext.web.api.RequestParameters) Test(org.junit.Test)

Example 82 with RequestParameters

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

the class HTTPRequestValidationTest method testFormURLEncodedParamWithIncludedTypes.

@Test
public void testFormURLEncodedParamWithIncludedTypes() throws Exception {
    HTTPRequestValidationHandler validationHandler = HTTPRequestValidationHandler.create().addFormParam("parameter", ParameterType.INT, true);
    router.route().handler(BodyHandler.create());
    router.post("/testFormParam").handler(validationHandler);
    router.post("/testFormParam").handler(routingContext -> {
        RequestParameters params = routingContext.get("parsedParameters");
        routingContext.response().setStatusMessage(params.formParameter("parameter").getInteger().toString()).end();
    }).failureHandler(generateFailureHandler(false));
    String formParam = getSuccessSample(ParameterType.INT).getInteger().toString();
    MultiMap form = MultiMap.caseInsensitiveMultiMap();
    form.add("parameter", formParam);
    testRequestWithForm(HttpMethod.POST, "/testFormParam", FormType.FORM_URLENCODED, form, 200, formParam);
}
Also used : QueryStringEncoder(io.netty.handler.codec.http.QueryStringEncoder) URLEncoder(java.net.URLEncoder) HttpMethod(io.vertx.core.http.HttpMethod) MultiMap(io.vertx.core.MultiMap) RequestParameters(io.vertx.ext.web.api.RequestParameters) Test(org.junit.Test) BodyHandler(io.vertx.ext.web.handler.BodyHandler) MultiMap(io.vertx.core.MultiMap) RequestParameters(io.vertx.ext.web.api.RequestParameters) Test(org.junit.Test)

Example 83 with RequestParameters

use of io.vertx.ext.web.api.RequestParameters 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).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 84 with RequestParameters

use of io.vertx.ext.web.api.RequestParameters 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/:pathParam").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).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

RequestParameters (io.vertx.ext.web.api.RequestParameters)84 Test (org.junit.Test)79 JsonObject (io.vertx.core.json.JsonObject)59 RequestParameter (io.vertx.ext.web.api.RequestParameter)58 CountDownLatch (java.util.concurrent.CountDownLatch)52 AsyncResult (io.vertx.core.AsyncResult)48 HashMap (java.util.HashMap)32 ArrayList (java.util.ArrayList)24 RouterFactoryOptions (io.vertx.ext.web.api.contract.RouterFactoryOptions)22 HttpServerOptions (io.vertx.core.http.HttpServerOptions)21 Operation (io.swagger.v3.oas.models.Operation)20 OpenAPI3RequestValidationHandlerImpl (io.vertx.ext.web.api.contract.openapi3.impl.OpenAPI3RequestValidationHandlerImpl)20 Handler (io.vertx.core.Handler)18 RoutingContext (io.vertx.ext.web.RoutingContext)18 Paths (java.nio.file.Paths)18 List (java.util.List)18 Collectors (java.util.stream.Collectors)18 OpenAPI (io.swagger.v3.oas.models.OpenAPI)17 OpenAPIV3Parser (io.swagger.v3.parser.OpenAPIV3Parser)17 ParseOptions (io.swagger.v3.parser.core.models.ParseOptions)17