forked from vert-x3/vertx-examples
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathValidationExampleServer.java
102 lines (89 loc) · 4.22 KB
/
ValidationExampleServer.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
package io.vertx.example.web.validation;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.http.HttpServerOptions;
import io.vertx.core.json.JsonObject;
import io.vertx.example.util.Runner;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.api.RequestParameter;
import io.vertx.ext.web.api.RequestParameters;
import io.vertx.ext.web.api.validation.HTTPRequestValidationHandler;
import io.vertx.ext.web.api.validation.ParameterType;
import io.vertx.ext.web.api.validation.ParameterTypeValidator;
import io.vertx.ext.web.api.validation.ValidationException;
import io.vertx.ext.web.handler.BodyHandler;
/*
* @author <a href="http://tfox.org">Tim Fox</a>
*/
public class ValidationExampleServer extends AbstractVerticle {
@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")
// Mount validation handler
.handler(validationHandler)
//Mount your handler
.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!
})
//Mount your failure handler
.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 % i == 0) // Number is not prime
throw ValidationException.ValidationExceptionFactory.generateNotMatchValidationException("Number is not prime!");
}
return RequestParameter.create(number); // We pass directly the parsed parameter
} 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()
// Mount the custom type validator
.addQueryParamWithCustomTypeValidator("primeNumber", primeCustomTypeValidator, true, false))
.handler((routingContext -> {
RequestParameters params = routingContext.get("parsedParameters");
Integer primeNumber = params.queryParameter("primeNumber").getInteger();
}));
vertx.createHttpServer().requestHandler(router::accept).listen();
}
// Convenience method so you can run it in your IDE
public static void main(String[] args) {
Runner.runExample(ValidationExampleServer.class);
}
}