Search in sources :

Example 36 with RequestParameter

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

the class ArrayTypeValidator method validate.

@Override
protected RequestParameter validate(List<String> values) {
    if (values == null || !checkMaxItems(values.size()) || !checkMinItems(values.size()))
        throw ValidationException.ValidationExceptionFactory.generateUnexpectedArraySizeValidationException(this.getMaxItems(), this.getMinItems(), values.size());
    List<RequestParameter> parsedParams = new ArrayList<>();
    for (String s : values) {
        RequestParameter parsed = validator.isValid(s);
        parsedParams.add(parsed);
    }
    return RequestParameter.create(parsedParams);
}
Also used : RequestParameter(io.vertx.ext.web.api.RequestParameter) ArrayList(java.util.ArrayList)

Example 37 with RequestParameter

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

the class BaseValidationHandler method validateCookieParams.

private Map<String, RequestParameter> validateCookieParams(RoutingContext routingContext) throws ValidationException {
    // Validation process validate only params that are registered in the validation -> extra params are allowed
    if (!routingContext.request().headers().contains("Cookie"))
        return null;
    // Some hack to reuse this object
    QueryStringDecoder decoder = new QueryStringDecoder("/?" + routingContext.request().getHeader("Cookie"));
    Map<String, List<String>> cookies = new HashMap<>();
    for (Map.Entry<String, List<String>> e : decoder.parameters().entrySet()) {
        String key = e.getKey().trim();
        if (cookies.containsKey(key))
            cookies.get(key).addAll(e.getValue());
        else
            cookies.put(key, e.getValue());
    }
    Map<String, RequestParameter> parsedParams = new HashMap<>();
    for (ParameterValidationRule rule : cookieParamsRules.values()) {
        String name = rule.getName().trim();
        if (cookies.containsKey(name)) {
            List<String> p = cookies.get(name);
            if (p.size() != 0) {
                RequestParameter parsedParam = rule.validateArrayParam(p);
                if (parsedParams.containsKey(parsedParam.getName()))
                    parsedParam = parsedParam.merge(parsedParams.get(parsedParam.getName()));
                parsedParams.put(parsedParam.getName(), parsedParam);
            } else {
                throw ValidationException.ValidationExceptionFactory.generateNotMatchValidationException(name + " can't be empty");
            }
        } else {
            if (rule.parameterTypeValidator().getDefault() != null) {
                RequestParameter parsedParam = new RequestParameterImpl(name, rule.parameterTypeValidator().getDefault());
                if (parsedParams.containsKey(parsedParam.getName()))
                    parsedParam = parsedParam.merge(parsedParams.get(parsedParam.getName()));
                parsedParams.put(parsedParam.getName(), parsedParam);
            } else if (!rule.isOptional())
                throw ValidationException.ValidationExceptionFactory.generateNotFoundValidationException(name, ParameterLocation.COOKIE);
        }
    }
    return parsedParams;
}
Also used : QueryStringDecoder(io.netty.handler.codec.http.QueryStringDecoder) RequestParameterImpl(io.vertx.ext.web.api.impl.RequestParameterImpl) RequestParameter(io.vertx.ext.web.api.RequestParameter) MultiMap(io.vertx.core.MultiMap)

Example 38 with RequestParameter

use of io.vertx.ext.web.api.RequestParameter 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 39 with RequestParameter

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

the class OpenAPI3ParametersUnitTest method testPathLabelExplodeArray.

/**
 * Test: path_label_explode_array
 * Expected parameters sent:
 * color: .blue.black.brown
 * Expected response: {"color":["blue","black","brown"]}
 * @throws Exception
 */
@Test
public void testPathLabelExplodeArray() throws Exception {
    routerFactory.addHandlerByOperationId("path_label_explode_array", routingContext -> {
        RequestParameters params = routingContext.get("parsedParameters");
        JsonObject res = new JsonObject();
        RequestParameter color_path = params.pathParameter("color");
        assertNotNull(color_path);
        assertTrue(color_path.isArray());
        res.put("color", new JsonArray(color_path.getArray().stream().map(param -> param.getString()).collect(Collectors.toList())));
        routingContext.response().setStatusCode(200).setStatusMessage("OK").putHeader("content-type", "application/json; charset=utf-8").end(res.encode());
    });
    CountDownLatch latch = new CountDownLatch(1);
    List<Object> color_path;
    color_path = new ArrayList<>();
    color_path.add("blue");
    color_path.add("black");
    color_path.add("brown");
    startServer();
    apiClient.pathLabelExplodeArray(color_path, (AsyncResult<HttpResponse> ar) -> {
        if (ar.succeeded()) {
            assertEquals(200, ar.result().statusCode());
            assertTrue("Expected: " + new JsonObject("{\"color\":[\"blue\",\"black\",\"brown\"]}").encode() + " Actual: " + ar.result().bodyAsJsonObject().encode(), new JsonObject("{\"color\":[\"blue\",\"black\",\"brown\"]}").equals(ar.result().bodyAsJsonObject()));
        } else {
            assertTrue(ar.cause().getMessage(), false);
        }
        latch.countDown();
    });
    awaitLatch(latch);
}
Also used : JsonArray(io.vertx.core.json.JsonArray) HttpResponse(io.vertx.ext.web.client.HttpResponse) HashMap(java.util.HashMap) RoutingContext(io.vertx.ext.web.RoutingContext) OpenAPI3RouterFactoryImpl(io.vertx.ext.web.api.contract.openapi3.impl.OpenAPI3RouterFactoryImpl) ArrayList(java.util.ArrayList) OpenAPI(io.swagger.v3.oas.models.OpenAPI) Map(java.util.Map) RequestParameters(io.vertx.ext.web.api.RequestParameters) JsonObject(io.vertx.core.json.JsonObject) AsyncResult(io.vertx.core.AsyncResult) Files(java.nio.file.Files) RequestParameter(io.vertx.ext.web.api.RequestParameter) Test(org.junit.Test) IOException(java.io.IOException) Collectors(java.util.stream.Collectors) StandardCharsets(java.nio.charset.StandardCharsets) RouterFactoryOptions(io.vertx.ext.web.api.contract.RouterFactoryOptions) WebTestValidationBase(io.vertx.ext.web.api.validation.WebTestValidationBase) ParseOptions(io.swagger.v3.parser.core.models.ParseOptions) JsonArray(io.vertx.core.json.JsonArray) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) Rule(org.junit.Rule) ExternalResource(org.junit.rules.ExternalResource) Paths(java.nio.file.Paths) HttpServerOptions(io.vertx.core.http.HttpServerOptions) Handler(io.vertx.core.Handler) OpenAPIV3Parser(io.swagger.v3.parser.OpenAPIV3Parser) RequestParameter(io.vertx.ext.web.api.RequestParameter) JsonObject(io.vertx.core.json.JsonObject) JsonObject(io.vertx.core.json.JsonObject) CountDownLatch(java.util.concurrent.CountDownLatch) AsyncResult(io.vertx.core.AsyncResult) RequestParameters(io.vertx.ext.web.api.RequestParameters) Test(org.junit.Test)

Example 40 with RequestParameter

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

the class OpenAPI3ParametersUnitTest method testPathSimpleNoexplodeArray.

/**
 * Test: path_simple_noexplode_array
 * Expected parameters sent:
 * color: blue,black,brown
 * Expected response: {"color":["blue","black","brown"]}
 * @throws Exception
 */
@Test
public void testPathSimpleNoexplodeArray() throws Exception {
    routerFactory.addHandlerByOperationId("path_simple_noexplode_array", routingContext -> {
        RequestParameters params = routingContext.get("parsedParameters");
        JsonObject res = new JsonObject();
        RequestParameter color_path = params.pathParameter("color");
        assertNotNull(color_path);
        assertTrue(color_path.isArray());
        res.put("color", new JsonArray(color_path.getArray().stream().map(param -> param.getString()).collect(Collectors.toList())));
        routingContext.response().setStatusCode(200).setStatusMessage("OK").putHeader("content-type", "application/json; charset=utf-8").end(res.encode());
    });
    CountDownLatch latch = new CountDownLatch(1);
    List<Object> color_path;
    color_path = new ArrayList<>();
    color_path.add("blue");
    color_path.add("black");
    color_path.add("brown");
    startServer();
    apiClient.pathSimpleNoexplodeArray(color_path, (AsyncResult<HttpResponse> ar) -> {
        if (ar.succeeded()) {
            assertEquals(200, ar.result().statusCode());
            assertTrue("Expected: " + new JsonObject("{\"color\":[\"blue\",\"black\",\"brown\"]}").encode() + " Actual: " + ar.result().bodyAsJsonObject().encode(), new JsonObject("{\"color\":[\"blue\",\"black\",\"brown\"]}").equals(ar.result().bodyAsJsonObject()));
        } else {
            assertTrue(ar.cause().getMessage(), false);
        }
        latch.countDown();
    });
    awaitLatch(latch);
}
Also used : JsonArray(io.vertx.core.json.JsonArray) HttpResponse(io.vertx.ext.web.client.HttpResponse) HashMap(java.util.HashMap) RoutingContext(io.vertx.ext.web.RoutingContext) OpenAPI3RouterFactoryImpl(io.vertx.ext.web.api.contract.openapi3.impl.OpenAPI3RouterFactoryImpl) ArrayList(java.util.ArrayList) OpenAPI(io.swagger.v3.oas.models.OpenAPI) Map(java.util.Map) RequestParameters(io.vertx.ext.web.api.RequestParameters) JsonObject(io.vertx.core.json.JsonObject) AsyncResult(io.vertx.core.AsyncResult) Files(java.nio.file.Files) RequestParameter(io.vertx.ext.web.api.RequestParameter) Test(org.junit.Test) IOException(java.io.IOException) Collectors(java.util.stream.Collectors) StandardCharsets(java.nio.charset.StandardCharsets) RouterFactoryOptions(io.vertx.ext.web.api.contract.RouterFactoryOptions) WebTestValidationBase(io.vertx.ext.web.api.validation.WebTestValidationBase) ParseOptions(io.swagger.v3.parser.core.models.ParseOptions) JsonArray(io.vertx.core.json.JsonArray) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) Rule(org.junit.Rule) ExternalResource(org.junit.rules.ExternalResource) Paths(java.nio.file.Paths) HttpServerOptions(io.vertx.core.http.HttpServerOptions) Handler(io.vertx.core.Handler) OpenAPIV3Parser(io.swagger.v3.parser.OpenAPIV3Parser) RequestParameter(io.vertx.ext.web.api.RequestParameter) JsonObject(io.vertx.core.json.JsonObject) JsonObject(io.vertx.core.json.JsonObject) CountDownLatch(java.util.concurrent.CountDownLatch) AsyncResult(io.vertx.core.AsyncResult) RequestParameters(io.vertx.ext.web.api.RequestParameters) Test(org.junit.Test)

Aggregations

RequestParameter (io.vertx.ext.web.api.RequestParameter)65 RequestParameters (io.vertx.ext.web.api.RequestParameters)57 Test (org.junit.Test)54 JsonObject (io.vertx.core.json.JsonObject)49 AsyncResult (io.vertx.core.AsyncResult)48 CountDownLatch (java.util.concurrent.CountDownLatch)48 HashMap (java.util.HashMap)34 ArrayList (java.util.ArrayList)21 HttpServerOptions (io.vertx.core.http.HttpServerOptions)18 RouterFactoryOptions (io.vertx.ext.web.api.contract.RouterFactoryOptions)18 Map (java.util.Map)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 Handler (io.vertx.core.Handler)17 JsonArray (io.vertx.core.json.JsonArray)17 RoutingContext (io.vertx.ext.web.RoutingContext)17 OpenAPI3RouterFactoryImpl (io.vertx.ext.web.api.contract.openapi3.impl.OpenAPI3RouterFactoryImpl)17 WebTestValidationBase (io.vertx.ext.web.api.validation.WebTestValidationBase)17 HttpResponse (io.vertx.ext.web.client.HttpResponse)17