-
Notifications
You must be signed in to change notification settings - Fork 683
/
Scope.java
605 lines (525 loc) · 20 KB
/
Scope.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
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
package play.mvc;
import java.io.UnsupportedEncodingException;
import java.lang.annotation.Annotation;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import play.Logger;
import play.Play;
import play.data.binding.Binder;
import play.data.binding.ParamNode;
import play.data.binding.RootParamNode;
import play.data.parsing.DataParser;
import play.data.parsing.TextParser;
import play.data.validation.Validation;
import play.exceptions.UnexpectedException;
import play.libs.Codec;
import play.libs.Crypto;
import play.libs.Time;
import play.utils.Utils;
/**
* All application Scopes
*/
public class Scope {
public static final String COOKIE_PREFIX = Play.configuration.getProperty("application.session.cookie", "PLAY");
public static final boolean COOKIE_SECURE = Play.configuration.getProperty("application.session.secure", "false").toLowerCase().equals("true");
public static final String COOKIE_EXPIRE = Play.configuration.getProperty("application.session.maxAge");
public static final boolean SESSION_HTTPONLY = Play.configuration.getProperty("application.session.httpOnly", "false").toLowerCase().equals("true");
public static final boolean SESSION_SEND_ONLY_IF_CHANGED = Play.configuration.getProperty("application.session.sendOnlyIfChanged", "false").toLowerCase().equals("true");
/**
* Flash scope
*/
public static class Flash {
Map<String, String> data = new HashMap<String, String>();
Map<String, String> out = new HashMap<String, String>();
static Flash restore() {
try {
Flash flash = new Flash();
Http.Cookie cookie = Http.Request.current().cookies.get(COOKIE_PREFIX + "_FLASH");
if (cookie != null) {
CookieDataCodec.decode(flash.data, cookie.value);
}
return flash;
} catch (Exception e) {
throw new UnexpectedException("Flash corrupted", e);
}
}
void save() {
if (Http.Response.current() == null) {
// Some request like WebSocket don't have any response
return;
}
if (out.isEmpty()) {
if(Http.Request.current().cookies.containsKey(COOKIE_PREFIX + "_FLASH") || !SESSION_SEND_ONLY_IF_CHANGED) {
Http.Response.current().setCookie(COOKIE_PREFIX + "_FLASH", "", null, "/", 0, COOKIE_SECURE);
}
return;
}
try {
String flashData = CookieDataCodec.encode(out);
Http.Response.current().setCookie(COOKIE_PREFIX + "_FLASH", flashData, null, "/", null, COOKIE_SECURE);
} catch (Exception e) {
throw new UnexpectedException("Flash serializationProblem", e);
}
} // ThreadLocal access
public static ThreadLocal<Flash> current = new ThreadLocal<Flash>();
public static Flash current() {
return current.get();
}
public void put(String key, String value) {
if (key.contains(":")) {
throw new IllegalArgumentException("Character ':' is invalid in a flash key.");
}
data.put(key, value);
out.put(key, value);
}
public void put(String key, Object value) {
if (value == null) {
put(key, (String) null);
}
put(key, value + "");
}
public void now(String key, String value) {
if (key.contains(":")) {
throw new IllegalArgumentException("Character ':' is invalid in a flash key.");
}
data.put(key, value);
}
public void error(String value, Object... args) {
put("error", String.format(value, args));
}
public void success(String value, Object... args) {
put("success", String.format(value, args));
}
public void discard(String key) {
out.remove(key);
}
public void discard() {
out.clear();
}
public void keep(String key) {
if (data.containsKey(key)) {
out.put(key, data.get(key));
}
}
public void keep() {
out.putAll(data);
}
public String get(String key) {
return data.get(key);
}
public boolean remove(String key) {
return data.remove(key) != null;
}
public void clear() {
data.clear();
}
public boolean contains(String key) {
return data.containsKey(key);
}
@Override
public String toString() {
return data.toString();
}
}
/**
* Session scope
*/
public static class Session {
static final String AT_KEY = "___AT";
static final String ID_KEY = "___ID";
static final String TS_KEY = "___TS";
static Session restore() {
try {
Session session = new Session();
Http.Cookie cookie = Http.Request.current().cookies.get(COOKIE_PREFIX + "_SESSION");
final int duration = Time.parseDuration(COOKIE_EXPIRE) ;
final long expiration = (duration * 1000l);
if (cookie != null && Play.started && cookie.value != null && !cookie.value.trim().equals("")) {
String value = cookie.value;
int firstDashIndex = value.indexOf("-");
if(firstDashIndex > -1) {
String sign = value.substring(0, firstDashIndex);
String data = value.substring(firstDashIndex + 1);
if (CookieDataCodec.safeEquals(sign, Crypto.sign(data, Play.secretKey.getBytes()))) {
CookieDataCodec.decode(session.data, data);
}
}
if (COOKIE_EXPIRE != null) {
// Verify that the session contains a timestamp, and that it's not expired
if (!session.contains(TS_KEY)) {
session = new Session();
} else {
if ((Long.parseLong(session.get(TS_KEY))) < System.currentTimeMillis()) {
// Session expired
session = new Session();
}
}
session.put(TS_KEY, System.currentTimeMillis() + expiration);
} else {
// Just restored. Nothing changed. No cookie-expire.
session.changed = false;
}
} else {
// no previous cookie to restore; but we may have to set the timestamp in the new cookie
if (COOKIE_EXPIRE != null) {
session.put(TS_KEY, (System.currentTimeMillis() + expiration));
}
}
return session;
} catch (Exception e) {
throw new UnexpectedException("Corrupted HTTP session from " + Http.Request.current().remoteAddress, e);
}
}
Map<String, String> data = new HashMap<String, String>(); // ThreadLocal access
boolean changed = false;
public static ThreadLocal<Session> current = new ThreadLocal<Session>();
public static Session current() {
return current.get();
}
public String getId() {
if (!data.containsKey(ID_KEY)) {
data.put(ID_KEY, Codec.UUID());
}
return data.get(ID_KEY);
}
public Map<String, String> all() {
return data;
}
public String getAuthenticityToken() {
if (!data.containsKey(AT_KEY)) {
data.put(AT_KEY, Crypto.sign(UUID.randomUUID().toString()));
}
return data.get(AT_KEY);
}
void change() {
changed = true;
}
void save() {
if (Http.Response.current() == null) {
// Some request like WebSocket don't have any response
return;
}
if(!changed && SESSION_SEND_ONLY_IF_CHANGED && COOKIE_EXPIRE == null) {
// Nothing changed and no cookie-expire, consequently send nothing back.
return;
}
if (isEmpty()) {
// The session is empty: delete the cookie
if(Http.Request.current().cookies.containsKey(COOKIE_PREFIX + "_SESSION") || !SESSION_SEND_ONLY_IF_CHANGED) {
Http.Response.current().setCookie(COOKIE_PREFIX + "_SESSION", "", null, "/", 0, COOKIE_SECURE, SESSION_HTTPONLY);
}
return;
}
try {
String sessionData = CookieDataCodec.encode(data);
String sign = Crypto.sign(sessionData, Play.secretKey.getBytes());
if (COOKIE_EXPIRE == null) {
Http.Response.current().setCookie(COOKIE_PREFIX + "_SESSION", sign + "-" + sessionData, null, "/", null, COOKIE_SECURE, SESSION_HTTPONLY);
} else {
Http.Response.current().setCookie(COOKIE_PREFIX + "_SESSION", sign + "-" + sessionData, null, "/", Time.parseDuration(COOKIE_EXPIRE), COOKIE_SECURE, SESSION_HTTPONLY);
}
} catch (Exception e) {
throw new UnexpectedException("Session serializationProblem", e);
}
}
public void put(String key, String value) {
if (key.contains(":")) {
throw new IllegalArgumentException("Character ':' is invalid in a session key.");
}
change();
if (value == null) {
data.remove(key);
} else {
data.put(key, value);
}
}
public void put(String key, Object value) {
change();
if (value == null) {
put(key, (String) null);
}
put(key, value + "");
}
public String get(String key) {
return data.get(key);
}
public boolean remove(String key) {
change();
return data.remove(key) != null;
}
public void remove(String... keys) {
for (String key : keys) {
remove(key);
}
}
public void clear() {
change();
data.clear();
}
/**
* Returns true if the session is empty,
* e.g. does not contain anything else than the timestamp
*/
public boolean isEmpty() {
for (String key : data.keySet()) {
if (!TS_KEY.equals(key)) {
return false;
}
}
return true;
}
public boolean contains(String key) {
return data.containsKey(key);
}
@Override
public String toString() {
return data.toString();
}
}
/**
* HTTP params
*/
public static class Params {
// ThreadLocal access
public static ThreadLocal<Params> current = new ThreadLocal<Params>();
public static Params current() {
return current.get();
}
boolean requestIsParsed;
public Map<String, String[]> data = new HashMap<String, String[]>();
boolean rootParamsNodeIsGenerated = false;
private RootParamNode rootParamNode = null;
public RootParamNode getRootParamNode() {
checkAndParse();
if (!rootParamsNodeIsGenerated) {
rootParamNode = ParamNode.convert(data);
rootParamsNodeIsGenerated = true;
}
return rootParamNode;
}
public RootParamNode getRootParamNodeFromRequest() {
return ParamNode.convert(data);
}
public void checkAndParse() {
if (!requestIsParsed) {
Http.Request request = Http.Request.current();
if (request == null) {
throw new UnexpectedException("Current request undefined");
} else {
String contentType = request.contentType;
if (contentType != null) {
DataParser dataParser = DataParser.parsers
.get(contentType);
if (dataParser != null) {
_mergeWith(dataParser.parse(request.body));
} else {
if (contentType.startsWith("text/")) {
_mergeWith(new TextParser().parse(request.body));
}
}
}
try {
request.body.close();
} catch (Exception e) {
//
}
requestIsParsed = true;
}
}
}
public void put(String key, String value) {
checkAndParse();
data.put(key, new String[]{value});
// make sure rootsParamsNode is regenerated if needed
rootParamsNodeIsGenerated = false;
}
public void put(String key, String[] values) {
checkAndParse();
data.put(key, values);
// make sure rootsParamsNode is regenerated if needed
rootParamsNodeIsGenerated = false;
}
public void remove(String key) {
checkAndParse();
data.remove(key);
// make sure rootsParamsNode is regenerated if needed
rootParamsNodeIsGenerated = false;
}
public String get(String key) {
if (!_contains(key)) {
checkAndParse();
}
if (data.containsKey(key)) {
return data.get(key)[0];
}
return null;
}
@SuppressWarnings("unchecked")
public <T> T get(String key, Class<T> type) {
try {
// TODO: This is used by the test, but this is not the most convenient.
return (T) Binder.bind(getRootParamNode(), key, type, type, null);
} catch (Exception e) {
Validation.addError(key, "validation.invalid");
return null;
}
}
@SuppressWarnings("unchecked")
public <T> T get(Annotation[] annotations, String key, Class<T> type) {
try {
return (T) Binder.directBind(annotations, get(key), type, null);
} catch (Exception e) {
Validation.addError(key, "validation.invalid");
return null;
}
}
public boolean _contains(String key) {
return data.containsKey(key);
}
public String[] getAll(String key) {
if (!_contains(key)) {
checkAndParse();
}
return data.get(key);
}
public Map<String, String[]> all() {
checkAndParse();
return data;
}
public Map<String, String[]> sub(String prefix) {
checkAndParse();
Map<String, String[]> result = new HashMap<String, String[]>();
for (String key : data.keySet()) {
if (key.startsWith(prefix + ".")) {
result.put(key.substring(prefix.length() + 1), data.get(key));
}
}
return result;
}
public Map<String, String> allSimple() {
checkAndParse();
Map<String, String> result = new HashMap<String, String>();
for (String key : data.keySet()) {
result.put(key, data.get(key)[0]);
}
return result;
}
void _mergeWith(Map<String, String[]> map) {
for (Map.Entry<String, String[]> entry : map.entrySet()) {
Utils.Maps.mergeValueInMap(data, entry.getKey(), entry.getValue());
}
}
void __mergeWith(Map<String, String> map) {
for (Map.Entry<String, String> entry : map.entrySet()) {
Utils.Maps.mergeValueInMap(data, entry.getKey(), entry.getValue());
}
}
public String urlEncode() {
checkAndParse();
String encoding = Http.Response.current().encoding;
StringBuilder ue = new StringBuilder();
for (String key : data.keySet()) {
if (key.equals("body")) {
continue;
}
String[] values = data.get(key);
for (String value : values) {
try {
ue.append(URLEncoder.encode(key, encoding)).append("=").append(URLEncoder.encode(value, encoding)).append("&");
} catch (Exception e) {
Logger.error(e, "Error (encoding ?)");
}
}
}
return ue.toString();
}
public void flash(String... params) {
if (params.length == 0) {
for (String key : all().keySet()) {
if (data.get(key).length > 1) {
StringBuilder sb = new StringBuilder();
boolean coma = false;
for (String d : data.get(key)) {
if (coma) {
sb.append(",");
}
sb.append(d);
coma = true;
}
Flash.current().put(key, sb.toString());
} else {
Flash.current().put(key, get(key));
}
}
} else {
for (String key : params) {
if (data.get(key).length > 1) {
StringBuilder sb = new StringBuilder();
boolean coma = false;
for (String d : data.get(key)) {
if (coma) {
sb.append(",");
}
sb.append(d);
coma = true;
}
Flash.current().put(key, sb.toString());
} else {
Flash.current().put(key, get(key));
}
}
}
}
@Override
public String toString() {
return data.toString();
}
}
/**
* Render args (used in template rendering)
*/
public static class RenderArgs {
public Map<String, Object> data = new HashMap<String, Object>(); // ThreadLocal access
public static ThreadLocal<RenderArgs> current = new ThreadLocal<RenderArgs>();
public static RenderArgs current() {
return current.get();
}
public void put(String key, Object arg) {
this.data.put(key, arg);
}
public Object get(String key) {
return data.get(key);
}
@SuppressWarnings("unchecked")
public <T> T get(String key, Class<T> clazz) {
return (T) this.get(key);
}
@Override
public String toString() {
return data.toString();
}
}
/**
* Routes args (used in reserve routing)
*/
public static class RouteArgs {
public Map<String, Object> data = new HashMap<String, Object>(); // ThreadLocal access
public static ThreadLocal<RouteArgs> current = new ThreadLocal<RouteArgs>();
public static RouteArgs current() {
return current.get();
}
public void put(String key, Object arg) {
this.data.put(key, arg);
}
public Object get(String key) {
return data.get(key);
}
@Override
public String toString() {
return data.toString();
}
}
}