Repository navigation
Expand file tree
/
Copy pathSparkApp.java
More file actions
350 lines (296 loc) · 10.7 KB
/
Copy pathSparkApp.java
File metadata and controls
350 lines (296 loc) · 10.7 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
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
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
package act.boot.spark;
import act.app.ActionContext;
import act.app.App;
import act.app.ProjectLayout;
import act.boot.ProjectLayoutBuilder;
import act.conf.AppConfig;
import act.controller.Controller;
import act.handler.DelegateRequestHandler;
import act.handler.RequestHandler;
import act.handler.RequestHandlerBase;
import act.handler.builtin.Echo;
import act.handler.builtin.Redirect;
import act.handler.builtin.StaticFileGetter;
import act.route.Router;
import act.view.ActServerError;
import act.xio.NetworkHandler;
import act.xio.Network;
import act.xio.undertow.UndertowNetwork;
import org.osgl.http.H;
import org.osgl.logging.L;
import org.osgl.logging.Logger;
import org.osgl.mvc.result.Forbidden;
import org.osgl.mvc.result.Result;
import org.osgl.util.C;
import org.osgl.util.E;
import java.io.File;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import static act.boot.spark.SparkApp.Filter.filter;
/**
* Support Spark framework style app
*/
public final class SparkApp extends App {
private static Logger logger = L.get(SparkApp.class);
private static final String GLOBAL = "__G__";
private static volatile SparkApp app;
private static volatile boolean started;
private static Network service;
private static NetworkHandler client;
private static Map<String, List<RequestHandler>> beforeHandlers = C.newMap();
private static Map<String, List<RequestHandler>> afterHandlers = C.newMap();
private static List<Filter> patternMatchedBeforeHandlers = C.newList();
private static List<Filter> patternMatchedAfterHandlers = C.newList();
private static C.List<Class<? extends Exception>> registeredExceptions = C.newList();
private static Map<Class<? extends Exception>, List<RequestHandler>> exceptionHandlers = C.newMap();
private AppConfig config;
private Router router;
private ProjectLayoutBuilder layout;
private SparkApp() {
config = new AppConfig();
router = new Router(this);
layout = new ProjectLayoutBuilder();
}
@Override
public ProjectLayout layout() {
return layout;
}
@Override
public AppConfig config() {
return config;
}
@Override
public Router router() {
return router;
}
private static SparkApp _app() {
if (null != app) {
return app;
}
synchronized (SparkApp.class) {
if (null == app) {
app = new SparkApp();
}
}
return app;
}
private static void _start() {
if (started) return;
synchronized (SparkApp.class) {
if (started) return;
started = true;
_startAct();
}
}
private static void _startAct() {
service = new UndertowNetwork();
client = new NetworkHandler(_app());
service.register(_app().config().httpPort(), client);
service.start();
}
private static Router _router() {
return _app().router;
}
public static void staticFileLocation(String location) {
staticFileLocation(location, location);
}
public static void staticFileLocation(String path, String location) {
_router().addMapping(H.Method.GET, path, filteredHandler(path, new StaticFileGetter(location, app)));
_start();
}
public static void externalFileLocation(String location) {
externalFileLocation(location, location);
}
public static void externalFileLocation(String path, String location) {
_router().addMapping(H.Method.GET, path, filteredHandler(path, new StaticFileGetter(new File(location))));
_start();
}
public static RequestHandler echo(String msg) {
return new Echo(msg);
}
public static RequestHandler redirect(String url) {
return new Redirect(url);
}
public static RequestHandler forbidden() {
return constant(new Forbidden());
}
public static void get(String path, RequestHandler handler) {
_router().addMapping(H.Method.GET, path, filteredHandler(path, handler));
_start();
}
public static void post(String path, RequestHandler handler) {
_router().addMapping(H.Method.POST, path, filteredHandler(path, handler));
_start();
}
public static void put(String path, RequestHandler handler) {
_router().addMapping(H.Method.PUT, path, filteredHandler(path, handler));
_start();
}
public static void delete(String path, RequestHandler handler) {
_router().addMapping(H.Method.DELETE, path, filteredHandler(path, handler));
_start();
}
public static void on(Class<? extends Exception> e, RequestHandler handler) {
E.illegalArgumentIf(Result.class.isAssignableFrom(e), "Result is handled by framework already...");
List<RequestHandler> l = exceptionHandlers.get(e);
if (null == l) {
l = C.newList(handler);
exceptionHandlers.put(e, l);
registeredExceptions = registeredExceptions.append(e).sorted();
} else {
l.add(handler);
}
}
public static void before(RequestHandler handler) {
before(GLOBAL, handler);
}
public static void before(String path, RequestHandler handler) {
RequestHandler handler1 = filter(path, handler);
if (handler == handler1) {
addFilter(path, handler, beforeHandlers);
} else {
addFilter((Filter) handler1, patternMatchedBeforeHandlers);
}
}
public static void after(RequestHandler handler) {
after(GLOBAL, handler);
}
public static void after(String path, RequestHandler handler) {
RequestHandler handler1 = filter(path, handler);
if (handler == handler1) {
addFilter(path, handler, afterHandlers);
} else {
addFilter((Filter) handler1, patternMatchedAfterHandlers);
}
}
private static void addFilter(String path, RequestHandler filter, Map<String, List<RequestHandler>> registry) {
List<RequestHandler> handlers = registry.get(path);
if (null == handlers) {
handlers = C.newList();
registry.put(path, handlers);
}
if (!handlers.contains(filter)) {
handlers.add(filter);
}
}
private static void addFilter(Filter filter, List<Filter> registry) {
registry.add(filter);
}
private static RequestHandler filteredHandler(String path, RequestHandler handler) {
return new FilteredHandler(path, (RequestHandlerBase)handler);
}
private static RequestHandler constant(final Result result) {
return new RequestHandlerBase() {
@Override
public void handle(ActionContext context) {
throw result;
}
};
}
static class Filter extends DelegateRequestHandler {
private Pattern ptn;
Filter(Pattern ptn, RequestHandler realHandler) {
super((RequestHandlerBase)realHandler);
E.NPE(ptn, realHandler);
this.ptn = ptn;
}
boolean matches(String path) {
return ptn.matcher(path).matches();
}
static RequestHandler filter(String path, RequestHandler realHandler) {
if (path.contains("*") || path.contains("[") || path.contains("(")) {
return new Filter(Pattern.compile(path), realHandler);
} else {
return new FilteredHandler(path, realHandler);
}
}
}
public abstract static class Handler extends RequestHandlerBase {
@Override
public void handle(ActionContext context) {
Result result;
try {
Object obj = handle(context.req(), context.resp());
result = Controller.Util.inferResult(null, obj, context, false);
} catch (Result r) {
result = r;
} catch (RuntimeException e) {
logger.error(e, "Error handling request: %s", e.getMessage());
result = ActServerError.of(e);
}
}
public Object handle(H.Request req, H.Response resp) {
return Controller.Util.ok();
}
}
private static class FilteredHandler extends DelegateRequestHandler {
private String path;
FilteredHandler(String path, RequestHandler realHandler) {
super((RequestHandlerBase)realHandler);
this.path = path;
}
@Override
public void handle(ActionContext ctx) {
try {
//ctx.saveLocal();
try {
handleBefore(ctx);
super.handle(ctx);
handleAfter(ctx);
} catch (Exception e) {
onException(e, ctx);
}
} catch (Result result) {
onResult(result, ctx);
} finally {
//ctx.clearLocal();
}
}
private void onResult(Result result, ActionContext context) {
H.Request req = context.req();
H.Response resp = context.resp();
result.apply(req, resp);
}
private void onException(Exception e, ActionContext ctx) {
for (Class<? extends Exception> c: registeredExceptions) {
if (c.isInstance(e)) {
List<RequestHandler> l = exceptionHandlers.get(c);
for (RequestHandler r: l) {
r.handle(ctx);
}
}
}
}
private void handleBefore(ActionContext ctx) {
runFilters(ctx, beforeHandlers);
runPatternMatchedFilters(ctx, patternMatchedBeforeHandlers);
}
private void handleAfter(ActionContext ctx) {
runFilters(ctx, afterHandlers);
runPatternMatchedFilters(ctx, patternMatchedAfterHandlers);
}
private void runFilters(ActionContext ctx, Map<String, List<RequestHandler>> staticRegistry) {
List<RequestHandler> l = staticRegistry.get(GLOBAL);
if (null != l) {
runFilters(ctx, l);
}
l = staticRegistry.get(path);
if (null != l) {
runFilters(ctx, l);
}
}
private void runFilters(ActionContext ctx, List<RequestHandler> handlers) {
for (RequestHandler h : handlers) {
h.handle(ctx);
}
}
private void runPatternMatchedFilters(ActionContext ctx, List<Filter> patternMatchedRegistry) {
for (Filter f : patternMatchedRegistry) {
if (f.matches(ctx.req().fullPath())) {
f.handle(ctx);
}
}
}
}
}