forked from vert-x3/vertx-examples
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathOpenAPI3Server.java
More file actions
63 lines (55 loc) · 2.55 KB
/
OpenAPI3Server.java
File metadata and controls
63 lines (55 loc) · 2.55 KB
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
package io.vertx.example.web.openapi3;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.http.HttpServer;
import io.vertx.core.http.HttpServerOptions;
import io.vertx.example.util.Runner;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.openapi.RouterBuilder;
import io.vertx.ext.web.openapi.RouterBuilderOptions;
import io.vertx.ext.web.validation.RequestParameter;
import io.vertx.ext.web.validation.RequestParameters;
import io.vertx.ext.web.validation.ValidationHandler;
public class OpenAPI3Server extends AbstractVerticle {
// Convenience method so you can run it in your IDE
public static void main(String[] args) {
Runner.runExample(OpenAPI3Server.class);
}
private HttpServer server;
@Override
public void start() {
// Load the api spec. This operation is asynchronous
RouterBuilder.create(this.vertx, "petstore.yaml")
.onFailure(Throwable::printStackTrace) // In case the contract loading failed print the stacktrace
.onSuccess(routerBuilder -> {
// Before router creation you can enable/disable various router factory behaviours
RouterBuilderOptions factoryOptions = new RouterBuilderOptions()
.setMountResponseContentTypeHandler(true); // Mount ResponseContentTypeHandler automatically
routerBuilder.setOptions(factoryOptions);
// Setup an handler for listPets
routerBuilder.operation("listPets")
.handler(routingContext -> {
// Load the parsed parameters
RequestParameters params = routingContext.get(ValidationHandler.REQUEST_CONTEXT_KEY);
// 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().setStatusCode(200).end();
});
// Create the router
Router router = routerBuilder.createRouter();
// Now you can use your Router instance
server = vertx
.createHttpServer(new HttpServerOptions().setPort(8080).setHost("localhost"))
.requestHandler(router);
server.listen()
.onSuccess(server -> System.out.println("Server started on port " + server.actualPort()))
.onFailure(Throwable::printStackTrace);
});
}
}