Search in sources :

Example 71 with RequestParameters

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

the class OpenAPI3ParametersUnitTest method testHeaderSimpleNoexplodeArray.

/**
 * Test: header_simple_noexplode_array
 * Expected parameters sent:
 * color: blue,black,brown
 * Expected response: {"color":["blue","black","brown"]}
 * @throws Exception
 */
@Test
public void testHeaderSimpleNoexplodeArray() throws Exception {
    routerFactory.addHandlerByOperationId("header_simple_noexplode_array", routingContext -> {
        RequestParameters params = routingContext.get("parsedParameters");
        JsonObject res = new JsonObject();
        RequestParameter color_header = params.headerParameter("color");
        assertNotNull(color_header);
        assertTrue(color_header.isArray());
        res.put("color", new JsonArray(color_header.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_header;
    color_header = new ArrayList<>();
    color_header.add("blue");
    color_header.add("black");
    color_header.add("brown");
    startServer();
    apiClient.headerSimpleNoexplodeArray(color_header, (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 72 with RequestParameters

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

the class OpenAPI3RouterFactoryTest method mountHandlerEncodedTest.

@Test
public void mountHandlerEncodedTest() 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(HANDLERS_TESTS_OPTIONS);
        routerFactory.addHandlerByOperationId("encodedParamTest", routingContext -> {
            RequestParameters params = routingContext.get("parsedParameters");
            assertEquals("a:b", params.pathParameter("p1").toString());
            assertEquals("a:b", params.queryParameter("p2").toString());
            routingContext.response().setStatusCode(200).setStatusMessage(params.pathParameter("p1").toString()).end();
        });
        latch.countDown();
    });
    awaitLatch(latch);
    startServer();
    testRequest(HttpMethod.GET, "/foo/a%3Ab?p2=a%3Ab", 200, "a:b");
}
Also used : CountDownLatch(java.util.concurrent.CountDownLatch) RequestParameters(io.vertx.ext.web.api.RequestParameters) Test(org.junit.Test)

Example 73 with RequestParameters

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

the class OpenAPI3Examples method addRoute.

public void addRoute(Vertx vertx, OpenAPI3RouterFactory routerFactory) {
    routerFactory.addHandlerByOperationId("awesomeOperation", routingContext -> {
        RequestParameters params = routingContext.get("parsedParameters");
        RequestParameter body = params.body();
        JsonObject jsonBody = body.getJsonObject();
    // Do something with body
    });
    routerFactory.addFailureHandlerByOperationId("awesomeOperation", routingContext -> {
    // Handle failure
    });
}
Also used : RequestParameter(io.vertx.ext.web.api.RequestParameter) JsonObject(io.vertx.core.json.JsonObject) RequestParameters(io.vertx.ext.web.api.RequestParameters)

Example 74 with RequestParameters

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

Example 75 with RequestParameters

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

the class OpenAPI3ValidationTest method testQueryParameterArrayDefaultStyle.

@Test
public void testQueryParameterArrayDefaultStyle() throws Exception {
    Operation op = testSpec.getPaths().get("/queryTests/arrayTests/default").getGet();
    OpenAPI3RequestValidationHandler validationHandler = new OpenAPI3RequestValidationHandlerImpl(op, op.getParameters(), testSpec);
    loadHandlers("/queryTests/arrayTests/default", HttpMethod.GET, false, validationHandler, (routingContext) -> {
        RequestParameters params = routingContext.get("parsedParameters");
        List<String> result = new ArrayList<>();
        for (RequestParameter r : params.queryParameter("parameter").getArray()) result.add(r.getInteger().toString());
        routingContext.response().setStatusMessage(serializeInCSVStringArray(result)).end();
    });
    List<String> values = new ArrayList<>();
    values.add("4");
    values.add("2");
    values.add("26");
    testRequest(HttpMethod.GET, "/queryTests/arrayTests/default?parameter=" + serializeInCSVStringArray(values), 200, serializeInCSVStringArray(values));
}
Also used : OpenAPI3RequestValidationHandlerImpl(io.vertx.ext.web.api.contract.openapi3.impl.OpenAPI3RequestValidationHandlerImpl) RequestParameter(io.vertx.ext.web.api.RequestParameter) ArrayList(java.util.ArrayList) Operation(io.swagger.v3.oas.models.Operation) RequestParameters(io.vertx.ext.web.api.RequestParameters) Test(org.junit.Test)

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