forked from actframework/actframework
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathActionContext.java
More file actions
1154 lines (1006 loc) · 33.8 KB
/
ActionContext.java
File metadata and controls
1154 lines (1006 loc) · 33.8 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
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
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package act.app;
/*-
* #%L
* ACT Framework
* %%
* Copyright (C) 2014 - 2017 ActFramework
* %%
* 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%
*/
import act.Act;
import act.Destroyable;
import act.ActResponse;
import act.conf.AppConfig;
import act.controller.ResponseCache;
import act.data.MapUtil;
import act.data.RequestBodyParser;
import act.event.ActEvent;
import act.event.EventBus;
import act.event.SystemEvent;
import act.handler.RequestHandler;
import act.i18n.LocaleResolver;
import act.route.Router;
import act.security.CORS;
import act.util.ActContext;
import act.util.MissingAuthenticationHandler;
import act.util.PropertySpec;
import act.util.RedirectToLoginUrl;
import act.view.RenderAny;
import org.osgl.$;
import org.osgl.concurrent.ContextLocal;
import org.osgl.http.H;
import org.osgl.http.H.Cookie;
import org.osgl.mvc.result.Result;
import org.osgl.storage.ISObject;
import org.osgl.util.C;
import org.osgl.util.E;
import org.osgl.util.S;
import org.osgl.web.util.UserAgent;
import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import javax.validation.ConstraintViolation;
import java.util.*;
import static act.controller.Controller.Util.*;
import static org.osgl.http.H.Header.Names.*;
/**
* {@code AppContext} encapsulate contextual properties needed by
* an application session
*/
@RequestScoped
public class ActionContext extends ActContext.Base<ActionContext> implements Destroyable {
public static final String ATTR_CSRF_TOKEN = "__csrf__";
public static final String ATTR_CSR_TOKEN_PREFETCH = "__csrf_prefetch__";
public static final String ATTR_WAS_UNAUTHENTICATED = "__was_unauthenticated__";
public static final String ATTR_HANDLER = "__act_handler__";
public static final String ATTR_RESULT = "__result__";
public static final String ATTR_EXCEPTION = "__exception__";
public static final String ATTR_CURRENT_FILE_INDEX = "__file_id__";
public static final String REQ_BODY = "_body";
private H.Request request;
private ActResponse<?> response;
private H.Session session;
private H.Flash flash;
private Set<Map.Entry<String, String[]>> requestParamCache;
private Map<String, String> extraParams;
private volatile Map<String, String[]> bodyParams;
private Map<String, String[]> allParams;
private String actionPath; // e.g. com.mycorp.myapp.controller.AbcController.foo
private State state;
private Map<String, Object> controllerInstances;
private Map<String, ISObject[]> uploads;
private Router router;
private RequestHandler handler;
private UserAgent ua;
private String sessionKeyUsername;
private LocaleResolver localeResolver;
private boolean disableCors;
private boolean disableCsrf;
private Boolean hasTemplate;
private $.Visitor<H.Format> templateChangeListener;
private H.Status forceResponseStatus;
private boolean cacheEnabled;
private MissingAuthenticationHandler forceMissingAuthenticationHandler;
private MissingAuthenticationHandler forceCsrfCheckingFailureHandler;
private String urlContext;
private boolean byPassImplicitTemplateVariable;
private int pathVarCount;
private Set<String> pathVarNames = new HashSet<>();
@Inject
private ActionContext(App app, H.Request request, ActResponse<?> response) {
super(app);
E.NPE(app, request, response);
request.context(this);
response.context(this);
this.request = request;
this.response = response;
this._init();
this.state = State.CREATED;
AppConfig config = app.config();
this.disableCors = !config.corsEnabled();
this.disableCsrf = req().method().safe();
this.sessionKeyUsername = config.sessionKeyUsername();
this.localeResolver = new LocaleResolver(this);
}
public State state() {
return state;
}
public boolean isSessionDissolved() {
return state == State.SESSION_DISSOLVED;
}
public boolean isSessionResolved() {
return state == State.SESSION_RESOLVED;
}
public H.Request req() {
return request;
}
public ActResponse<?> resp() {
return response;
}
public ActResponse<?> prepareRespForWrite() {
response.markReady();
return response;
}
public H.Cookie cookie(String name) {
return req().cookie(name);
}
public H.Session session() {
return session;
}
public String session(String key) {
return session.get(key);
}
public H.Session session(String key, String value) {
return session.put(key, value);
}
/**
* Returns HTTP session's id
* @return HTTP session id
*/
public String sessionId() {
return session().id();
}
public H.Flash flash() {
return flash;
}
public String flash(String key) {
return flash.get(key);
}
public H.Flash flash(String key, String value) {
return flash.put(key, value);
}
public Router router() {
return router;
}
public ActionContext router(Router router) {
this.router = $.notNull(router);
return this;
}
public MissingAuthenticationHandler missingAuthenticationHandler() {
if (null != forceMissingAuthenticationHandler) {
return forceMissingAuthenticationHandler;
}
return isAjax() ? config().ajaxMissingAuthenticationHandler() : config().missingAuthenticationHandler();
}
public MissingAuthenticationHandler csrfFailureHandler() {
if (null != forceCsrfCheckingFailureHandler) {
return forceCsrfCheckingFailureHandler;
}
return isAjax() ? config().ajaxCsrfCheckFailureHandler() : config().csrfCheckFailureHandler();
}
public ActionContext forceMissingAuthenticationHandler(MissingAuthenticationHandler handler) {
this.forceMissingAuthenticationHandler = handler;
return this;
}
public ActionContext forceCsrfCheckingFailureHandler(MissingAuthenticationHandler handler) {
this.forceCsrfCheckingFailureHandler = handler;
return this;
}
public ActionContext byPassImplicitVariable() {
this.byPassImplicitTemplateVariable = true;
return this;
}
public boolean isByPassImplicitTemplateVariable() {
return this.byPassImplicitTemplateVariable;
}
public ActionContext urlContext(String context) {
this.urlContext = context;
return this;
}
public String urlContext() {
return urlContext;
}
// !!!IMPORTANT! the following methods needs to be kept to allow enhancer work correctly
@Override
public <T> T renderArg(String name) {
return super.renderArg(name);
}
@Override
public ActionContext renderArg(String name, Object val) {
return super.renderArg(name, val);
}
@Override
public Map<String, Object> renderArgs() {
return super.renderArgs();
}
@Override
public ActionContext templatePath(String templatePath) {
hasTemplate = null;
if (null != templateChangeListener) {
templateChangeListener.visit(accept());
}
return super.templatePath(templatePath);
}
public ActionContext templateChangeListener($.Visitor<H.Format> listener) {
this.templateChangeListener = $.notNull(listener);
return this;
}
public RequestHandler handler() {
return handler;
}
public ActionContext handler(RequestHandler handler) {
E.NPE(handler);
this.handler = handler;
return this;
}
public H.Format accept() {
return req().accept();
}
public ActionContext accept(H.Format fmt) {
req().accept(fmt);
return this;
}
public Boolean hasTemplate() {
return hasTemplate;
}
public ActionContext setHasTemplate(boolean b) {
hasTemplate = b;
return this;
}
public ActionContext enableCache() {
E.illegalArgumentIf(this.cacheEnabled, "cache already enabled in the action context");
this.cacheEnabled = true;
this.response = new ResponseCache(response);
return this;
}
public int pathVarCount() {
return pathVarCount;
}
public boolean isPathVar(String name) {
return pathVarNames.contains(name);
}
public String portId() {
return router().portId();
}
public int port() {return router().port(); }
public UserAgent userAgent() {
if (null == ua) {
ua = UserAgent.parse(req().header(H.Header.Names.USER_AGENT));
}
return ua;
}
public boolean jsonEncoded() {
return req().contentType() == H.Format.JSON;
}
public boolean acceptJson() {
return accept() == H.Format.JSON;
}
public boolean acceptXML() {
return accept() == H.Format.XML;
}
public boolean isAjax() {
return req().isAjax();
}
public boolean isOptionsMethod() {
return req().method() == H.Method.OPTIONS;
}
public String username() {
return session().get(sessionKeyUsername);
}
public boolean isLoggedIn() {
return S.notBlank(username());
}
public String body() {
return paramVal(REQ_BODY);
}
public ActionContext param(String name, String value) {
extraParams.put(name, value);
return this;
}
public ActionContext urlPathParam(String name, String value) {
pathVarCount++;
pathVarNames.add(name);
return param(name, value);
}
@Override
public Set<String> paramKeys() {
Set<String> set = new HashSet<String>();
set.addAll(C.<String>list(request.paramNames()));
set.addAll(extraParams.keySet());
set.addAll(bodyParams().keySet());
return set;
}
@Override
public String paramVal(String name) {
String val = extraParams.get(name);
if (null != val) {
return val;
}
val = request.paramVal(name);
if (null == val) {
String[] sa = getBody(name);
if (null != sa && sa.length > 0) {
val = sa[0];
}
}
return val;
}
public String[] paramVals(String name) {
String val = extraParams.get(name);
if (null != val) {
return new String[]{val};
}
String[] sa = request.paramVals(name);
return null == sa ? getBody(name) : sa;
}
private String[] getBody(String name) {
Map<String, String[]> body = bodyParams();
String[] sa = body.get(name);
return null == sa ? new String[0] : sa;
}
private Map<String, String[]> bodyParams() {
if (null == bodyParams) {
synchronized (this) {
if (null == bodyParams) {
Map<String, String[]> map = C.newMap();
H.Method method = request.method();
if (H.Method.POST == method || H.Method.PUT == method || H.Method.PATCH == method) {
RequestBodyParser parser = RequestBodyParser.get(request);
map = parser.parse(this);
}
bodyParams = map;
}
}
}
return bodyParams;
}
public Map<String, String[]> allParams() {
return allParams;
}
public ISObject upload(String name) {
Integer index = attribute(ATTR_CURRENT_FILE_INDEX);
if (null == index) {
index = 0;
}
return upload(name, index);
}
public ISObject upload(String name, int index) {
body();
ISObject[] a = uploads.get(name);
return null != a && a.length > index ? a[index] : null;
}
public ActionContext addUpload(String name, ISObject sobj) {
ISObject[] a = uploads.get(name);
if (null == a) {
a = new ISObject[1];
a[0] = sobj;
} else {
ISObject[] newA = new ISObject[a.length + 1];
System.arraycopy(a, 0, newA, 0, a.length);
newA[a.length] = sobj;
a = newA;
}
uploads.put(name, a);
return this;
}
public H.Status successStatus() {
if (null != forceResponseStatus) {
return forceResponseStatus;
}
return H.Method.POST == req().method() ? H.Status.CREATED : H.Status.OK;
}
public ActionContext forceResponseStatus(H.Status status) {
this.forceResponseStatus = $.notNull(status);
return this;
}
public Result nullValueResult() {
if (hasRenderArgs()) {
RenderAny result = new RenderAny();
if (renderArgs().size() == fieldOutputVarCount() && req().isAjax()) {
result.ignoreMissingTemplate();
}
return result;
}
return nullValueResultIgnoreRenderArgs();
}
public Result nullValueResultIgnoreRenderArgs() {
if (null != forceResponseStatus) {
return new Result(forceResponseStatus){};
} else {
if (req().method() == H.Method.POST) {
H.Format accept = accept();
if (H.Format.JSON == accept) {
return CREATED_JSON;
} else if (H.Format.XML == accept) {
return CREATED_XML;
} else {
return CREATED;
}
} else {
return NO_CONTENT;
}
}
}
public void preCheckCsrf() {
if (!disableCsrf) {
handler().csrfSpec().preCheck(this);
}
}
public void checkCsrf(H.Session session) {
if (!disableCsrf) {
handler().csrfSpec().check(this, session);
}
}
public void setCsrfCookieAndRenderArgs() {
handler().csrfSpec().setCookieAndRenderArgs(this);
}
public void disableCORS() {
this.disableCors = true;
}
/**
* Apply content type to response with result provided.
*
* If `result` is an error then it might not apply content type as requested:
* * If request is not ajax request, then use `text/html`
* * If request is ajax request then apply requested content type only when `json` or `xml` is requested
* * otherwise use `text/html`
*
* @param result
* the result used to check if it is error result
* @return
* this `ActionContext`.
*/
public ActionContext applyContentType(Result result) {
if (!result.status().isError()) {
return applyContentType();
}
if (req().isAjax()) {
H.Request req = req();
H.Format fmt = req.accept();
if (H.Format.UNKNOWN == fmt) {
fmt = req.contentType();
}
if (H.Format.JSON == fmt || H.Format.XML == fmt) {
applyContentType(fmt);
} else {
applyContentType(H.Format.HTML);
}
} else {
applyContentType(H.Format.HTML);
}
return this;
}
public ActionContext applyContentType() {
H.Request req = req();
H.Format fmt = req.accept();
if (H.Format.UNKNOWN == fmt) {
fmt = req.contentType();
}
applyContentType(fmt);
return this;
}
public ActionContext applyCorsSpec() {
RequestHandler handler = handler();
if (null != handler) {
CORS.Spec spec = handler.corsSpec();
spec.applyTo(this);
}
applyGlobalCorsSetting();
return this;
}
private void applyContentType(H.Format fmt) {
if (null != fmt) {
ActResponse resp = resp();
resp.initContentType(fmt.contentType());
resp.commitContentType();
}
}
private void applyGlobalCorsSetting() {
if (this.disableCors) {
return;
}
AppConfig conf = config();
if (!conf.corsEnabled()) {
return;
}
H.Response r = resp();
r.addHeaderIfNotAdded(ACCESS_CONTROL_ALLOW_ORIGIN, conf.corsAllowOrigin());
if (request.method() == H.Method.OPTIONS || !conf.corsOptionCheck()) {
r.addHeaderIfNotAdded(ACCESS_CONTROL_ALLOW_HEADERS, conf.corsAllowHeaders());
r.addHeaderIfNotAdded(ACCESS_CONTROL_ALLOW_CREDENTIALS, S.string(conf.corsAllowCredentials()));
r.addHeaderIfNotAdded(ACCESS_CONTROL_EXPOSE_HEADERS, conf.corsExposeHeaders());
r.addHeaderIfNotAdded(ACCESS_CONTROL_MAX_AGE, S.string(conf.corsMaxAge()));
}
}
/**
* Called by bytecode enhancer to set the name list of the render arguments that is update
* by the enhancer
*
* @param names the render argument names separated by ","
* @return this AppContext
*/
public ActionContext __appRenderArgNames(String names) {
return renderArg("__arg_names__", C.listOf(names.split(",")));
}
public List<String> __appRenderArgNames() {
return renderArg("__arg_names__");
}
public ActionContext __controllerInstance(String className, Object instance) {
if (null == controllerInstances) {
controllerInstances = C.newMap();
}
controllerInstances.put(className, instance);
return this;
}
public Object __controllerInstance(String className) {
return null == controllerInstances ? null : controllerInstances.get(className);
}
/**
* Return cached object by key. The key will be concatenated with
* current session id when fetching the cached object
*
* @param key
* @param <T> the object type
* @return the cached object
*/
public <T> T cached(String key) {
H.Session sess = session();
if (null != sess) {
return sess.cached(key);
} else {
return app().cache().get(key);
}
}
/**
* Add an object into cache by key. The key will be used in conjunction with session id if
* there is a session instance
*
* @param key the key to index the object within the cache
* @param obj the object to be cached
*/
public void cache(String key, Object obj) {
H.Session sess = session();
if (null != sess) {
sess.cache(key, obj);
} else {
app().cache().put(key, obj);
}
}
/**
* Add an object into cache by key with expiration time specified
*
* @param key the key to index the object within the cache
* @param obj the object to be cached
* @param expiration the seconds after which the object will be evicted from the cache
*/
public void cache(String key, Object obj, int expiration) {
H.Session session = this.session;
if (null != session) {
session.cache(key, obj, expiration);
} else {
app().cache().put(key, obj, expiration);
}
}
/**
* Add an object into cache by key and expired after one hour
*
* @param key the key to index the object within the cache
* @param obj the object to be cached
*/
public void cacheForOneHour(String key, Object obj) {
cache(key, obj, 60 * 60);
}
/**
* Add an object into cache by key and expired after half hour
*
* @param key the key to index the object within the cache
* @param obj the object to be cached
*/
public void cacheForHalfHour(String key, Object obj) {
cache(key, obj, 30 * 60);
}
/**
* Add an object into cache by key and expired after 10 minutes
*
* @param key the key to index the object within the cache
* @param obj the object to be cached
*/
public void cacheForTenMinutes(String key, Object obj) {
cache(key, obj, 10 * 60);
}
/**
* Add an object into cache by key and expired after one minute
*
* @param key the key to index the object within the cache+
* @param obj the object to be cached
*/
public void cacheForOneMinute(String key, Object obj) {
cache(key, obj, 60);
}
/**
* Evict cached object
*
* @param key the key indexed the cached object to be evicted
*/
public void evictCache(String key) {
H.Session sess = session();
if (null != sess) {
sess.evict(key);
} else {
app().cache().evict(key);
}
}
public S.Buffer buildViolationMessage(S.Buffer builder) {
return buildViolationMessage(builder, "\n");
}
public S.Buffer buildViolationMessage(S.Buffer builder, String separator) {
Map<String, ConstraintViolation> violations = violations();
if (violations.isEmpty()) return builder;
for (Map.Entry<String, ConstraintViolation> entry : violations.entrySet()) {
builder.append(entry.getKey()).append(": ").append(entry.getValue().getMessage()).append(separator);
}
int n = builder.length();
builder.delete(n - separator.length(), n);
return builder;
}
public String violationMessage(String separator) {
return buildViolationMessage(S.newBuffer(), separator).toString();
}
public String violationMessage() {
return violationMessage("\n");
}
public ActionContext flashViolationMessage() {
return flashViolationMessage("\n");
}
public ActionContext flashViolationMessage(String separator) {
if (violations().isEmpty()) return this;
flash().error(violationMessage(separator));
return this;
}
public String actionPath() {
return actionPath;
}
public ActionContext actionPath(String path) {
actionPath = path;
return this;
}
@Override
public String methodPath() {
return actionPath;
}
public void startIntercepting() {
state = State.INTERCEPTING;
}
public void startHandling() {
state = State.HANDLING;
}
/**
* Update the context session to mark a user logged in
* @param username the username
*/
public void login(String username) {
session().put(config().sessionKeyUsername(), username);
}
/**
* Login the user and redirect back to original URL
* @param username
* the username
*/
public void loginAndRedirectBack(String username) {
login(username);
RedirectToLoginUrl.redirectToOriginalUrl(this);
}
/**
* Login the user and redirect back to original URL. If no
* original URL found then redirect to `defaultLandingUrl`.
*
* @param username
* The username
* @param defaultLandingUrl
* the URL to be redirected if original URL not found
*/
public void loginAndRedirectBack(String username, String defaultLandingUrl) {
login(username);
RedirectToLoginUrl.redirectToOriginalUrl(this, defaultLandingUrl);
}
/**
* Login the user and redirect to specified URL
* @param username
* the username
* @param url
* the URL to be redirected to
*/
public void loginAndRedirect(String username, String url) {
login(username);
redirect(url);
}
/**
* Logout the current session. After calling this method,
* the session will be cleared
*/
public void logout() {
session().clear();
}
/**
* Initialize params/renderArgs/attributes and then
* resolve session and flash from cookies
*/
public void resolve() {
E.illegalStateIf(state != State.CREATED);
boolean sessionFree = handler.sessionFree();
attribute(ATTR_WAS_UNAUTHENTICATED, true);
if (!sessionFree) {
resolveSession();
resolveFlash();
}
localeResolver.resolve();
state = State.SESSION_RESOLVED;
if (!sessionFree) {
handler.prepareAuthentication(this);
EventBus eventBus = app().eventBus();
eventBus.emit(new PreFireSessionResolvedEvent(session, this));
Act.sessionManager().fireSessionResolved(this);
eventBus.emit(new SessionResolvedEvent(session, this));
if (isLoggedIn()) {
attribute(ATTR_WAS_UNAUTHENTICATED, false);
}
}
}
@Override
public Locale locale(boolean required) {
if (required) {
if (null == locale()) {
localeResolver.resolve();
}
}
return super.locale(required);
}
/**
* Dissolve session and flash into cookies.
* <p><b>Note</b> this method must be called
* before any content has been committed to
* response output stream/writer</p>
*/
public void dissolve() {
if (state == State.SESSION_DISSOLVED) {
return;
}
if (handler.sessionFree()) {
return;
}
if (null == session) {
// only case is when CSRF token check failed
// while resolving session
// we need to generate new session anyway
// because it is required to cache the
// original URL
// see RedirectToLoginUrl
session = new H.Session();
}
localeResolver.dissolve();
app().eventBus().emit(new SessionWillDissolveEvent(this));
try {
dissolveFlash();
dissolveSession();
state = State.SESSION_DISSOLVED;
} finally {
app().eventBus().emit(new SessionDissolvedEvent(this));
}
}
/**
* Clear all internal data store/cache and then
* remove this context from thread local
*/
@Override
protected void releaseResources() {
super.releaseResources();
PropertySpec.current.remove();
if (this.state != State.DESTROYED) {
this.allParams = null;
this.extraParams = null;
this.requestParamCache = null;
this.router = null;
this.handler = null;
// xio impl might need this this.request = null;
// xio impl might need this this.response = null;
this.flash = null;
this.session = null;
this.controllerInstances = null;
clearLocal();
this.uploads.clear();
}
this.state = State.DESTROYED;
}
public void saveLocal() {
_local.set(this);
}
public static void clearLocal() {
clearCurrent();
}
private Set<Map.Entry<String, String[]>> requestParamCache() {
if (null != requestParamCache) {
return requestParamCache;
}
requestParamCache = new HashSet<>();
Map<String, String[]> map = new HashMap<>();
// url queries
Iterator<String> paramNames = request.paramNames().iterator();
while (paramNames.hasNext()) {
final String key = paramNames.next();
final String[] val = request.paramVals(key);
MapUtil.mergeValueInMap(map, key, val);
}
// post bodies
Map<String, String[]> map2 = bodyParams();
for (String key : map2.keySet()) {
String[] val = map2.get(key);
if (null != val) {
MapUtil.mergeValueInMap(map, key, val);
}
}
requestParamCache.addAll(map.entrySet());
return requestParamCache;
}
private void _init() {
uploads = new HashMap<>();
extraParams = new HashMap<>();
final Set<Map.Entry<String, String[]>> paramEntrySet = new AbstractSet<Map.Entry<String, String[]>>() {
@Override
public Iterator<Map.Entry<String, String[]>> iterator() {
final Iterator<Map.Entry<String, String[]>> extraItr = new Iterator<Map.Entry<String, String[]>>() {
Iterator<Map.Entry<String, String>> parent = extraParams.entrySet().iterator();
@Override
public boolean hasNext() {
return parent.hasNext();
}
@Override
public Map.Entry<String, String[]> next() {
final Map.Entry<String, String> parentEntry = parent.next();
return new Map.Entry<String, String[]>() {
@Override
public String getKey() {
return parentEntry.getKey();
}
@Override
public String[] getValue() {
return new String[]{parentEntry.getValue()};
}
@Override
public String[] setValue(String[] value) {
throw E.unsupport();
}
};
}
@Override
public void remove() {