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");
}
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);
}
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());
}
});
});
}
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();
}
Aggregations