-
Notifications
You must be signed in to change notification settings - Fork 302
/
RestAPIVerticle.java
335 lines (306 loc) · 10.5 KB
/
RestAPIVerticle.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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
package io.vertx.blueprint.microservice.common;
import io.vertx.core.AsyncResult;
import io.vertx.core.Future;
import io.vertx.core.Handler;
import io.vertx.core.http.HttpMethod;
import io.vertx.core.http.HttpServer;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.RoutingContext;
import io.vertx.ext.web.handler.CookieHandler;
import io.vertx.ext.web.handler.CorsHandler;
import io.vertx.ext.web.handler.SessionHandler;
import io.vertx.ext.web.sstore.ClusteredSessionStore;
import io.vertx.ext.web.sstore.LocalSessionStore;
import java.util.HashSet;
import java.util.Optional;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.function.Function;
/**
* An abstract base verticle that provides several helper methods for REST API.
*
* @author Eric Zhao
*/
public abstract class RestAPIVerticle extends BaseMicroserviceVerticle {
/**
* Create http server for the REST service.
*
* @param router router instance
* @param host http host
* @param port http port
* @return async result of the procedure
*/
protected Future<Void> createHttpServer(Router router, String host, int port) {
Future<HttpServer> httpServerFuture = Future.future();
vertx.createHttpServer()
.requestHandler(router::accept)
.listen(port, host, httpServerFuture.completer());
return httpServerFuture.map(r -> null);
}
/**
* Enable CORS support.
*
* @param router router instance
*/
protected void enableCorsSupport(Router router) {
Set<String> allowHeaders = new HashSet<>();
allowHeaders.add("x-requested-with");
allowHeaders.add("Access-Control-Allow-Origin");
allowHeaders.add("origin");
allowHeaders.add("Content-Type");
allowHeaders.add("accept");
Set<HttpMethod> allowMethods = new HashSet<>();
allowMethods.add(HttpMethod.GET);
allowMethods.add(HttpMethod.PUT);
allowMethods.add(HttpMethod.OPTIONS);
allowMethods.add(HttpMethod.POST);
allowMethods.add(HttpMethod.DELETE);
allowMethods.add(HttpMethod.PATCH);
router.route().handler(CorsHandler.create("*")
.allowedHeaders(allowHeaders)
.allowedMethods(allowMethods));
}
/**
* Enable local session storage in requests.
*
* @param router router instance
*/
protected void enableLocalSession(Router router) {
router.route().handler(CookieHandler.create());
router.route().handler(SessionHandler.create(
LocalSessionStore.create(vertx, "shopping.user.session")));
}
/**
* Enable clustered session storage in requests.
*
* @param router router instance
*/
protected void enableClusteredSession(Router router) {
router.route().handler(CookieHandler.create());
router.route().handler(SessionHandler.create(
ClusteredSessionStore.create(vertx, "shopping.user.session")));
}
// Auth helper method
/**
* Validate if a user exists in the request scope.
*/
protected void requireLogin(RoutingContext context, BiConsumer<RoutingContext, JsonObject> biHandler) {
Optional<JsonObject> principal = Optional.ofNullable(context.request().getHeader("user-principal"))
.map(JsonObject::new);
if (principal.isPresent()) {
biHandler.accept(context, principal.get());
} else {
context.response()
.setStatusCode(401)
.end(new JsonObject().put("message", "need_auth").encode());
}
}
// helper result handler within a request context
/**
* This method generates handler for async methods in REST APIs.
*/
protected <T> Handler<AsyncResult<T>> resultHandler(RoutingContext context, Handler<T> handler) {
return res -> {
if (res.succeeded()) {
handler.handle(res.result());
} else {
internalError(context, res.cause());
res.cause().printStackTrace();
}
};
}
/**
* This method generates handler for async methods in REST APIs.
* Use the result directly and invoke `toString` as the response. The content type is JSON.
*/
protected <T> Handler<AsyncResult<T>> resultHandler(RoutingContext context) {
return ar -> {
if (ar.succeeded()) {
T res = ar.result();
context.response()
.putHeader("content-type", "application/json")
.end(res == null ? "{}" : res.toString());
} else {
internalError(context, ar.cause());
ar.cause().printStackTrace();
}
};
}
/**
* This method generates handler for async methods in REST APIs.
* Use the result directly and use given {@code converter} to convert result to string
* as the response. The content type is JSON.
*
* @param context routing context instance
* @param converter a converter that converts result to a string
* @param <T> result type
* @return generated handler
*/
protected <T> Handler<AsyncResult<T>> resultHandler(RoutingContext context, Function<T, String> converter) {
return ar -> {
if (ar.succeeded()) {
T res = ar.result();
if (res == null) {
serviceUnavailable(context, "invalid_result");
} else {
context.response()
.putHeader("content-type", "application/json")
.end(converter.apply(res));
}
} else {
internalError(context, ar.cause());
ar.cause().printStackTrace();
}
};
}
/**
* This method generates handler for async methods in REST APIs.
* The result requires non-empty. If empty, return <em>404 Not Found</em> status.
* The content type is JSON.
*
* @param context routing context instance
* @param <T> result type
* @return generated handler
*/
protected <T> Handler<AsyncResult<T>> resultHandlerNonEmpty(RoutingContext context) {
return ar -> {
if (ar.succeeded()) {
T res = ar.result();
if (res == null) {
notFound(context);
} else {
context.response()
.putHeader("content-type", "application/json")
.end(res.toString());
}
} else {
internalError(context, ar.cause());
ar.cause().printStackTrace();
}
};
}
/**
* This method generates handler for async methods in REST APIs.
* The content type is originally raw text.
*
* @param context routing context instance
* @param <T> result type
* @return generated handler
*/
protected <T> Handler<AsyncResult<T>> rawResultHandler(RoutingContext context) {
return ar -> {
if (ar.succeeded()) {
T res = ar.result();
context.response()
.end(res == null ? "" : res.toString());
} else {
internalError(context, ar.cause());
ar.cause().printStackTrace();
}
};
}
protected Handler<AsyncResult<Void>> resultVoidHandler(RoutingContext context, JsonObject result) {
return resultVoidHandler(context, result, 200);
}
/**
* This method generates handler for async methods in REST APIs.
* The result is not needed. Only the state of the async result is required.
*
* @param context routing context instance
* @param result result content
* @param status status code
* @return generated handler
*/
protected Handler<AsyncResult<Void>> resultVoidHandler(RoutingContext context, JsonObject result, int status) {
return ar -> {
if (ar.succeeded()) {
context.response()
.setStatusCode(status == 0 ? 200 : status)
.putHeader("content-type", "application/json")
.end(result.encodePrettily());
} else {
internalError(context, ar.cause());
ar.cause().printStackTrace();
}
};
}
protected Handler<AsyncResult<Void>> resultVoidHandler(RoutingContext context, int status) {
return ar -> {
if (ar.succeeded()) {
context.response()
.setStatusCode(status == 0 ? 200 : status)
.putHeader("content-type", "application/json")
.end();
} else {
internalError(context, ar.cause());
ar.cause().printStackTrace();
}
};
}
/**
* This method generates handler for async methods in REST DELETE APIs.
* Return format in JSON (successful status = 204):
* <code>
* {"message": "delete_success"}
* </code>
*
* @param context routing context instance
* @return generated handler
*/
protected Handler<AsyncResult<Void>> deleteResultHandler(RoutingContext context) {
return res -> {
if (res.succeeded()) {
context.response().setStatusCode(204)
.putHeader("content-type", "application/json")
.end(new JsonObject().put("message", "delete_success").encodePrettily());
} else {
internalError(context, res.cause());
res.cause().printStackTrace();
}
};
}
// helper method dealing with failure
protected void badRequest(RoutingContext context, Throwable ex) {
context.response().setStatusCode(400)
.putHeader("content-type", "application/json")
.end(new JsonObject().put("error", ex.getMessage()).encodePrettily());
}
protected void notFound(RoutingContext context) {
context.response().setStatusCode(404)
.putHeader("content-type", "application/json")
.end(new JsonObject().put("message", "not_found").encodePrettily());
}
protected void internalError(RoutingContext context, Throwable ex) {
context.response().setStatusCode(500)
.putHeader("content-type", "application/json")
.end(new JsonObject().put("error", ex.getMessage()).encodePrettily());
}
protected void notImplemented(RoutingContext context) {
context.response().setStatusCode(501)
.putHeader("content-type", "application/json")
.end(new JsonObject().put("message", "not_implemented").encodePrettily());
}
protected void badGateway(Throwable ex, RoutingContext context) {
ex.printStackTrace();
context.response()
.setStatusCode(502)
.putHeader("content-type", "application/json")
.end(new JsonObject().put("error", "bad_gateway")
//.put("message", ex.getMessage())
.encodePrettily());
}
protected void serviceUnavailable(RoutingContext context) {
context.fail(503);
}
protected void serviceUnavailable(RoutingContext context, Throwable ex) {
context.response().setStatusCode(503)
.putHeader("content-type", "application/json")
.end(new JsonObject().put("error", ex.getMessage()).encodePrettily());
}
protected void serviceUnavailable(RoutingContext context, String cause) {
context.response().setStatusCode(503)
.putHeader("content-type", "application/json")
.end(new JsonObject().put("error", cause).encodePrettily());
}
}