/
RespImpl.java
585 lines (465 loc) · 12.9 KB
/
RespImpl.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
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
package org.rapidoid.http.impl;
import org.rapidoid.RapidoidThing;
import org.rapidoid.annotation.Authors;
import org.rapidoid.annotation.Since;
import org.rapidoid.buffer.Buf;
import org.rapidoid.cls.Cls;
import org.rapidoid.collection.Coll;
import org.rapidoid.config.BasicConfig;
import org.rapidoid.config.Conf;
import org.rapidoid.ctx.Ctxs;
import org.rapidoid.ctx.UserInfo;
import org.rapidoid.http.HttpUtils;
import org.rapidoid.http.MediaType;
import org.rapidoid.http.Req;
import org.rapidoid.http.Resp;
import org.rapidoid.http.customize.Customization;
import org.rapidoid.http.customize.LoginProvider;
import org.rapidoid.http.customize.RolesProvider;
import org.rapidoid.io.IO;
import org.rapidoid.net.AsyncLogic;
import org.rapidoid.u.U;
import org.rapidoid.util.Msc;
import org.rapidoid.util.MscOpts;
import org.rapidoid.util.Tokens;
import org.rapidoid.web.Screen;
import org.rapidoid.web.ScreenBean;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.Serializable;
import java.nio.ByteBuffer;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
/*
* #%L
* rapidoid-http-fast
* %%
* Copyright (C) 2014 - 2017 Nikolche Mihajlovski and contributors
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
@Authors("Nikolche Mihajlovski")
@Since("5.0.x")
public class RespImpl extends RapidoidThing implements Resp {
private final ReqImpl req;
private volatile Object result = null;
private volatile Object body = null;
private volatile Object raw = null;
private volatile int code = 200;
private volatile MediaType contentType = HttpUtils.getDefaultContentType();
private final Map<String, String> headers = Coll.synchronizedMap();
private final Map<String, String> cookies = Coll.synchronizedMap();
private final Map<String, Object> model = Coll.synchronizedMap();
private volatile String redirect = null;
private volatile String filename = null;
private volatile File file = null;
private volatile String view = null;
private volatile boolean mvc = false;
private volatile Screen screen;
private volatile ChunkedResponse chunked;
public RespImpl(ReqImpl req) {
this.req = req;
}
@Override
public synchronized Resp result(Object content) {
ensureCanChange();
this.result = content;
return this;
}
@Override
public synchronized Object result() {
return this.result;
}
@Override
public synchronized Resp body(byte[] body) {
ensureCanChange();
this.body = body;
return this;
}
@Override
public synchronized Resp body(ByteBuffer body) {
ensureCanChange();
this.body = body;
return this;
}
@Override
public synchronized Object body() {
return this.body;
}
@Override
public synchronized Resp raw(byte[] raw) {
ensureCanChange();
this.raw = raw;
return this;
}
@Override
public synchronized Resp raw(ByteBuffer raw) {
ensureCanChange();
this.raw = raw;
return this;
}
@Override
public synchronized Object raw() {
return this.raw;
}
@Override
public synchronized Resp code(int code) {
ensureCanChange();
this.code = code;
return this;
}
@Override
public synchronized int code() {
return this.code;
}
@Override
public Map<String, String> headers() {
return isReadOnly() ? Collections.unmodifiableMap(this.headers) : this.headers;
}
@Override
public Resp header(String name, String value) {
headers().put(name, value);
return this;
}
@Override
public Map<String, String> cookies() {
return isReadOnly() ? Collections.unmodifiableMap(this.cookies) : this.cookies;
}
@Override
public Resp cookie(String name, String value, String... extras) {
if (U.notEmpty(extras)) {
value += "; " + U.join("; ", extras);
}
if (!cookieContainsPath(extras)) {
value += "; path=" + HttpUtils.cookiePath();
}
cookies().put(name, value);
return this;
}
private static boolean cookieContainsPath(String[] extras) {
for (String extra : extras) {
if (extra.toLowerCase().startsWith("path=")) {
return true;
}
}
return false;
}
@Override
public Map<String, Serializable> session() {
return request().session();
}
@Override
public Resp session(String name, Serializable value) {
session().put(name, value);
return this;
}
@Override
public Map<String, Serializable> token() {
return request().token();
}
@Override
public Resp token(String name, Serializable value) {
token().put(name, value);
return this;
}
@Override
public Map<String, Object> model() {
return isReadOnly() ? Collections.unmodifiableMap(this.model) : this.model;
}
@Override
public Resp model(String name, Object value) {
model().put(name, value);
return this;
}
@Override
public synchronized Resp contentType(MediaType contentType) {
ensureCanChange();
this.contentType = contentType;
return this;
}
@Override
public synchronized MediaType contentType() {
return this.contentType;
}
@Override
public synchronized Resp redirect(String redirect) {
ensureCanChange();
this.redirect = redirect;
return this;
}
@Override
public synchronized String redirect() {
return this.redirect;
}
@Override
public synchronized Resp filename(String filename) {
ensureCanChange();
this.filename = filename;
return this;
}
@Override
public synchronized String filename() {
return this.filename;
}
@Override
public synchronized Resp file(File file) {
ensureCanChange();
this.file = file;
return this;
}
@Override
public synchronized File file() {
return this.file;
}
private void ensureCanChange() {
U.must(!req.isDone(), "The request was already processed, so the response can't be changed now!");
U.must(!req.isRendering(), "The response rendering has already started, so the response can't be changed now!");
}
private boolean isReadOnly() {
return req.isRendering() || req.isDone();
}
@Override
public Resp done() {
req.done();
return this;
}
@Override
public Resp html(Object content) {
return contentType(MediaType.HTML_UTF_8).result(content);
}
@Override
public Resp plain(Object content) {
return contentType(MediaType.PLAIN_TEXT_UTF_8).result(content);
}
@Override
public Resp json(Object content) {
return contentType(MediaType.JSON).result(content);
}
@Override
public Resp binary(Object content) {
return contentType(MediaType.BINARY).result(content);
}
@Override
public synchronized String view() {
return view != null ? view : HttpUtils.viewName(req);
}
@Override
public Resp noView() {
return view("");
}
boolean hasCustomView() {
return view != null;
}
@Override
public synchronized Resp view(String view) {
if (view != null) {
HttpUtils.validateViewName(view);
this.mvc(true);
}
this.view = view;
return this;
}
@Override
public synchronized boolean mvc() {
return mvc;
}
@Override
public synchronized Resp mvc(boolean mvc) {
if (mvc) {
U.must(MscOpts.hasRapidoidHTML(), "The rapidoid-html module must be included for the MVC feature!");
}
this.mvc = mvc;
return this;
}
@Override
public Req request() {
return req;
}
@Override
public boolean login(String username, String password) {
LoginProvider loginProvider = Customization.of(req).loginProvider();
U.must(loginProvider != null, "A login provider wasn't set!");
RolesProvider rolesProvider = Customization.of(req).rolesProvider();
U.must(rolesProvider != null, "A roles provider wasn't set!");
req.tokenChanged.set(true);
boolean success;
try {
success = loginProvider.login(req, username, password);
if (success) {
Set<String> roles = rolesProvider.getRolesForUser(req, username);
long ttl = Conf.TOKEN.entry("ttl").or(0);
long expiresOn = ttl > 0 ? U.time() + ttl : Long.MAX_VALUE;
UserInfo user = new UserInfo(username, roles, null);
Ctxs.required().setUser(user);
request().token().put(Tokens._USER, username);
request().token().put(Tokens._EXPIRES, expiresOn);
}
} catch (Throwable e) {
throw U.rte("Login error!", e);
}
return success;
}
@Override
public void logout() {
HttpUtils.clearUserData(request());
HttpUtils.setResponseTokenCookie(this, "");
req.tokenChanged.set(true);
}
@Override
public Screen screen() {
if (screen == null) {
synchronized (this) {
if (screen == null) {
screen = createScreen();
}
}
}
return screen;
}
@Override
public void resume(AsyncLogic asyncLogic) {
req.channel().resume(req.connectionId(), req.handle(), asyncLogic);
}
private Screen createScreen() {
Screen screen = MscOpts.hasRapidoidGUI() ? GUIUtil.newPage() : new ScreenBean();
initScreen(screen);
return screen;
}
private void initScreen(Screen screen) {
BasicConfig zone = HttpUtils.zone(req);
String brand = zone.entry("brand").str().getOrNull();
String title = zone.entry("title").str().getOrNull();
String siteName = req.host();
if (U.isEmpty(siteName)
|| siteName.equals("localhost") || siteName.startsWith("localhost:")
|| siteName.equals("127.0.0.1") || siteName.startsWith("127.0.0.1:")) {
siteName = "Rapidoid";
}
screen.brand(U.or(brand, siteName));
screen.title(U.or(title, siteName));
screen.home(zone.entry("home").str().or("/"));
screen.search(zone.entry("search").bool().or(false));
screen.navbar(zone.entry("navbar").bool().or(brand != null));
screen.fluid(zone.entry("fluid").bool().or(false));
String cdn = zone.entry("cdn").or("auto");
if (!"auto".equalsIgnoreCase(cdn)) {
screen.cdn(Cls.bool(cdn));
}
if (zone.has("menu")) {
screen.menu(zone.sub("menu").toMap());
}
}
@Override
public OutputStream out() {
if (chunked == null) {
synchronized (this) {
if (chunked == null) {
checkStreamingPreconditions();
// the chunked response object, which buffers the response data
chunked = new ChunkedResponse(this);
// set the header early, so it can be overwritten by the app, if necessary
header("Transfer-Encoding", "chunked");
}
}
}
return chunked;
}
private void checkStreamingPreconditions() {
U.must(result() == null, "The response result has already been set, so cannot write the response through OutputStream, too!");
U.must(body() == null, "The response body has already been set, so cannot write the response through OutputStream, too!");
U.must(raw() == null, "The raw response has already been set, so cannot write the response through OutputStream, too!");
}
void startChunkedOutputStream() {
req.doRendering(code(), null);
}
@Override
public String toString() {
return "RespImpl{" +
(result != null ? "result=" + result : "") +
(body != null ? ", body=" + body : "") +
(raw != null ? ", raw=" + raw : "") +
", code=" + code +
(contentType != null ? ", contentType=" + contentType : "") +
", headers=" + headers +
", cookies=" + cookies +
", model=" + model +
(redirect != null ? ", redirect='" + redirect + '\'' : "") +
(filename != null ? ", filename='" + filename + '\'' : "") +
(file != null ? ", file=" + file : "") +
(view != null ? ", view='" + view + '\'' : "") +
", mvc=" + mvc +
'}';
}
byte[] renderToBytes() {
if (mvc()) {
byte[] bytes = ResponseRenderer.renderMvc(req, this);
HttpUtils.postProcessResponse(this); // the response might have been changed, so post-process again
return bytes;
} else if (body() != null) {
return Msc.toBytes(body());
} else if (result() != null) {
return serializeResponseContent();
} else {
throw U.rte("There's nothing to render!");
}
}
private byte[] serializeResponseContent() {
return HttpUtils.responseToBytes(req, result(), contentType(), Customization.of(req).jsonResponseRenderer());
}
@Override
public Resp chunk(byte[] data) {
OutputStream chnk = out();
synchronized (chnk) {
try {
chnk.flush();
} catch (IOException e) {
throw U.rte(e);
}
chunk(data, 0, data.length);
}
return this;
}
public void chunk(final byte[] data, final int offset, final int length) {
U.notNull(data, "data");
resume(new AsyncLogic() {
@Override
public boolean resumeAsync() {
Buf out = req.channel().output();
out.append(Integer.toHexString(length));
out.append("\r\n");
out.append(data, offset, length);
out.append("\r\n");
req.channel().send();
return false;
}
});
}
void terminatingChunk() {
resume(new AsyncLogic() {
@Override
public boolean resumeAsync() {
Buf out = req.channel().output();
out.append("0\r\n\r\n");
return true;
}
});
}
void finish() {
if (chunked != null && !chunked.isClosed()) {
IO.close(chunked, false);
}
}
}