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