/
TodoVerticle.java
251 lines (222 loc) · 7.48 KB
/
TodoVerticle.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
package io.vertx.blueprint.todolist.verticles;
import io.vertx.blueprint.todolist.Constants;
import io.vertx.blueprint.todolist.entity.Todo;
import io.vertx.blueprint.todolist.service.JdbcTodoService;
import io.vertx.blueprint.todolist.service.RedisTodoService;
import io.vertx.blueprint.todolist.service.TodoService;
import io.vertx.core.AbstractVerticle;
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.HttpServerResponse;
import io.vertx.core.json.DecodeException;
import io.vertx.core.json.Json;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.RoutingContext;
import io.vertx.ext.web.handler.BodyHandler;
import io.vertx.ext.web.handler.CorsHandler;
import io.vertx.redis.RedisOptions;
import java.util.HashSet;
import java.util.Random;
import java.util.Set;
import java.util.function.Consumer;
/**
* Vert.x Blueprint Application - Todo Backend
* Application Verticle
*
* @author Eric Zhao
*/
public class TodoVerticle extends AbstractVerticle {
private static final String HOST = "0.0.0.0";
private static final int PORT = 8082;
private TodoService service;
private void initData() {
final String serviceType = config().getString("service.type", "redis");
System.out.println("[INFO]Service Type: " + serviceType);
switch (serviceType) {
case "redis":
RedisOptions config = new RedisOptions()
.setHost(config().getString("redis.host", "127.0.0.1"))
.setPort(config().getInteger("redis.port", 6379));
service = new RedisTodoService(vertx, config);
break;
case "jdbc":
service = new JdbcTodoService(vertx, config());
break;
}
service.initData().setHandler(res -> {
if (res.failed()) {
System.err.println("[Error] Persistence service is not running!");
res.cause().printStackTrace();
}
});
}
@Override
public void start(Future<Void> future) throws Exception {
initData();
Router router = Router.router(vertx);
// CORS support
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.POST);
allowMethods.add(HttpMethod.DELETE);
allowMethods.add(HttpMethod.PATCH);
router.route().handler(BodyHandler.create());
router.route().handler(CorsHandler.create("*")
.allowedHeaders(allowHeaders)
.allowedMethods(allowMethods));
// routes
router.get(Constants.API_GET).handler(this::handleGetTodo);
router.get(Constants.API_LIST_ALL).handler(this::handleGetAll);
router.post(Constants.API_CREATE).handler(this::handleCreateTodo);
router.patch(Constants.API_UPDATE).handler(this::handleUpdateTodo);
router.delete(Constants.API_DELETE).handler(this::handleDeleteOne);
router.delete(Constants.API_DELETE_ALL).handler(this::handleDeleteAll);
vertx.createHttpServer()
.requestHandler(router::accept)
.listen(config().getInteger("http.port", PORT),
config().getString("http.address", HOST), result -> {
if (result.succeeded())
future.complete();
else
future.fail(result.cause());
});
}
/**
* Wrap the result handler with failure handler (503 Service Unavailable)
*/
private <T> Handler<AsyncResult<T>> resultHandler(RoutingContext context, Consumer<T> consumer) {
return res -> {
if (res.succeeded()) {
consumer.accept(res.result());
} else {
serviceUnavailable(context);
}
};
}
private void handleCreateTodo(RoutingContext context) {
try {
final Todo todo = wrapObject(new Todo(context.getBodyAsString()), context);
final String encoded = Json.encodePrettily(todo);
service.insert(todo).setHandler(resultHandler(context, res -> {
if (res) {
context.response()
.setStatusCode(201)
.putHeader("content-type", "application/json")
.end(encoded);
} else {
serviceUnavailable(context);
}
}));
} catch (DecodeException e) {
sendError(400, context.response());
}
}
private void handleGetTodo(RoutingContext context) {
String todoID = context.request().getParam("todoId");
if (todoID == null) {
sendError(400, context.response());
return;
}
service.getCertain(todoID).setHandler(resultHandler(context, res -> {
if (!res.isPresent())
notFound(context);
else {
final String encoded = Json.encodePrettily(res.get());
context.response()
.putHeader("content-type", "application/json")
.end(encoded);
}
}));
}
private void handleGetAll(RoutingContext context) {
service.getAll().setHandler(resultHandler(context, res -> {
if (res == null) {
serviceUnavailable(context);
} else {
final String encoded = Json.encodePrettily(res);
context.response()
.putHeader("content-type", "application/json")
.end(encoded);
}
}));
}
private void handleUpdateTodo(RoutingContext context) {
try {
String todoID = context.request().getParam("todoId");
final Todo newTodo = new Todo(context.getBodyAsString());
// handle error
if (todoID == null) {
sendError(400, context.response());
return;
}
service.update(todoID, newTodo)
.setHandler(resultHandler(context, res -> {
if (res == null)
notFound(context);
else {
final String encoded = Json.encodePrettily(res);
context.response()
.putHeader("content-type", "application/json")
.end(encoded);
}
}));
} catch (DecodeException e) {
badRequest(context);
}
}
private Handler<AsyncResult<Boolean>> deleteResultHandler(RoutingContext context) {
return res -> {
if (res.succeeded()) {
if (res.result()) {
context.response().setStatusCode(204).end();
} else {
serviceUnavailable(context);
}
} else {
serviceUnavailable(context);
}
};
}
private void handleDeleteOne(RoutingContext context) {
String todoID = context.request().getParam("todoId");
service.delete(todoID)
.setHandler(deleteResultHandler(context));
}
private void handleDeleteAll(RoutingContext context) {
service.deleteAll()
.setHandler(deleteResultHandler(context));
}
private void sendError(int statusCode, HttpServerResponse response) {
response.setStatusCode(statusCode).end();
}
private void notFound(RoutingContext context) {
context.response().setStatusCode(404).end();
}
private void badRequest(RoutingContext context) {
context.response().setStatusCode(400).end();
}
private void serviceUnavailable(RoutingContext context) {
context.response().setStatusCode(503).end();
}
/**
* Wrap the Todo entity with appropriate id and url
*
* @param todo a todo entity
* @param context RoutingContext
* @return the wrapped todo entity
*/
private Todo wrapObject(Todo todo, RoutingContext context) {
if (todo.getId() == 0)
todo.setIncId();
todo.setUrl(context.request().absoluteURI() + "/" + todo.getId());
return todo;
}
}