This repository was archived by the owner on Mar 20, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 57
Expand file tree
/
Copy pathELFlash.java
More file actions
1706 lines (1379 loc) · 63 KB
/
ELFlash.java
File metadata and controls
1706 lines (1379 loc) · 63 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
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright (c) 1997-2010 Oracle and/or its affiliates. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common Development
* and Distribution License("CDDL") (collectively, the "License"). You
* may not use this file except in compliance with the License. You can
* obtain a copy of the License at
* https://glassfish.java.net/public/CDDL+GPL_1_1.html
* or packager/legal/LICENSE.txt. See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each
* file and include the License file at packager/legal/LICENSE.txt.
*
* GPL Classpath Exception:
* Oracle designates this particular file as subject to the "Classpath"
* exception as provided by Oracle in the GPL Version 2 section of the License
* file that accompanied this code.
*
* Modifications:
* If applicable, add the following below the License Header, with the fields
* enclosed by brackets [] replaced by your own identifying information:
* "Portions Copyright [year] [name of copyright owner]"
*
* Contributor(s):
* If you wish your version of this file to be governed by only the CDDL or
* only the GPL Version 2, indicate your decision by adding "[Contributor]
* elects to include this software in this distribution under the [CDDL or GPL
* Version 2] license." If you don't indicate a single choice of license, a
* recipient has the option to distribute your version of this file under
* either the CDDL, the GPL Version 2 or to extend the choice of license to
* its licensees as provided above. However, if you add GPL Version 2 code
* and therefore, elected the GPL Version 2 license, then the option applies
* only if the new code is made subject to such option by the copyright
* holder.
*/
package com.sun.faces.context.flash;
import static com.sun.faces.config.WebConfiguration.BooleanWebContextInitParameter.EnableDistributable;
import static com.sun.faces.config.WebConfiguration.BooleanWebContextInitParameter.ForceAlwaysWriteFlashCookie;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIViewRoot;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.context.Flash;
import javax.faces.event.PhaseId;
import javax.faces.event.PostKeepFlashValueEvent;
import javax.faces.event.PostPutFlashValueEvent;
import javax.faces.event.PreClearFlashEvent;
import javax.faces.event.PreRemoveFlashValueEvent;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import com.sun.faces.config.WebConfiguration;
import com.sun.faces.config.WebConfiguration.WebContextInitParameter;
import com.sun.faces.facelets.tag.ui.UIDebug;
import com.sun.faces.util.ByteArrayGuardAESCTR;
import com.sun.faces.util.FacesLogger;
/**
* <p>How this implementation works</p>
* <p>This class is an application singleton. It has one ivar,
* innerMap. Entries are added to and removed from this map as needed
* according to how the flash scope is defined in the spec. This
* implementation never touches the session, nor does it cause the
* session to be created.</p>
* <p>Most of the hairy logic is encapsulated with in the inner class
* PreviousNextFlashInfoManager. An instance of this class is
* obtained by calling one of the variants of getCurrentFlashManager().
* When the instance is no longer needed for this request, call
* releaseCurrentFlashManager().</p>
* <p>Two very important methods are getPhaseMapForWriting() and
* getPhaseMapForReading(). These methods are the basis for the
* Map implementation methods. Methods that need to write to the map
* use getPhaseMapForWriting(), those that need to read use
* getPhaseMapForReading(). These methods allow for the laziness that
* allows us to only incur a cost when the flash is actually written
* to.</p>
* <p>The operation of this class is intimately tied to the request
* processing lifecycle. Let's break down every run thru the request
* processing lifecycle into two parts called "previous" and "next". We
* use the names "previous" and "next" to indicate the persistence and
* timing of the data that is stored in the flash. Consider two runs
* through the requset processing lifecle: N and N+1. On request N,
* there is no "previous" request. On Request N, any writes to the
* flash that happen during RENDER RESPONSE go to the "next" flash map.
* This means they are available for the ENTIRE run though the request
* processing lifecycle on request N+1. Any entries put into the "next"
* flash map on request N will be expired at the end of request N+1.
* Now, when we get into request N+1 what was considered "next" on
* request N, is now called "previous" from the perspective of request
* N+1. Any reads from the flash during request N+1 come from the
* "previous" map. Any writes to the flash before RENDER RESPONSE go to
* the "previous" map. Any writes to the flash during RENDER RESPNOSE
* go to the "next" map.</p>
*/
public class ELFlash extends Flash {
// <editor-fold defaultstate="collapsed" desc="ivars">
/**
* <p>Keys in this map are the string version of sequence numbers
* obtained via calls to {@link #getNewSequenceNumber}. Values are
* the actual Map instances that back the actual Map methods on this
* class. All writes to and reads from this map are done by the
* {@link PreviousNextFlashInfoManager} inner class.</p>
*
*/
private Map<String,Map<String, Object>> flashInnerMap = null;
private final AtomicLong sequenceNumber = new AtomicLong(0);
private int numberOfConcurentFlashUsers = Integer.
parseInt(WebContextInitParameter.NumberOfConcurrentFlashUsers.getDefaultValue());
private long numberOfFlashesBetweenFlashReapings = Long.
parseLong(WebContextInitParameter.NumberOfFlashesBetweenFlashReapings.getDefaultValue());
private final boolean distributable;
private ByteArrayGuardAESCTR guard;
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="class vars">
private static final String ELEMENT_TYPE_MISMATCH = "element-type-mismatch";
private static final Logger LOGGER = FacesLogger.FLASH.getLogger();
/**
* <p>These constants are referenced from other source files in this
* package. This one is a disambiguator prefix.</p>
*/
static final String PREFIX = "csfcf";
/**
* <p>This constant is used as the key in the application map that
* stores the singleton ELFlash instance.</p>
*/
static final String FLASH_ATTRIBUTE_NAME = PREFIX + "f";
/**
* <p>This constant is used as the name of the cookie sent to the
* client. The cookie is used to allow the flash scope to
* be used to support POST REDIRECT GET navigation.</p>
*/
static final String FLASH_COOKIE_NAME = PREFIX + "c";
/**
* <p>This constant is used as the key the request map used, in the
* FlashELResolver, to convey the name of the property being
* accessed via 'now'.</p>
*/
static final String FLASH_NOW_REQUEST_KEY = FLASH_ATTRIBUTE_NAME + "n";
private enum CONSTANTS {
/**
* The key in the FacesContext attributes map (hereafter
* referred to as contextMap) for the request scoped {@link
* PreviousNextFlashInfoManager}.
*/
RequestFlashManager,
/**
* At the beginning of every phase, we save the value of the
* facesContext.getResponseComplete() into the contextMap under
* this key. We check this value after the phase to see if this
* is the phase where the user called responseComplete(). This
* is important to cover cases when the user does some funny
* lifecycle stuff.
*/
SavedResponseCompleteFlagValue,
/**
* This is used as the key in the flash itself to store the messages
* if they are being tracked.
*/
FacesMessageAttributeName,
/**
* This is used as the key in the flash itself to track whether or not
* messages are being saved across request/response boundaries.
*/
KeepAllMessagesAttributeName,
/**
* This key is used in the contextMap to indicate that the next
* get should be treated as a keep.
*
*/
KeepFlagAttributeName,
/**
* This key is used in the contextMap to prevent setting the cookie
* twice.
*/
DidWriteCookieAttributeName,
/**
* Force setMaxAge(0)
*/
ForceSetMaxAgeZero,
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="Constructors and instance accessors">
/** Creates a new instance of ELFlash */
private ELFlash(ExternalContext extContext) {
flashInnerMap = new ConcurrentHashMap<>();
WebConfiguration config = WebConfiguration.getInstance(extContext);
String value;
try {
value = config.getOptionValue(WebContextInitParameter.NumberOfConcurrentFlashUsers);
numberOfConcurentFlashUsers = Integer.parseInt(value);
} catch (NumberFormatException nfe) {
if (LOGGER.isLoggable(Level.WARNING)) {
LOGGER.log(Level.WARNING, "Unable to set number of concurrent flash users. Defaulting to {0}", numberOfConcurentFlashUsers);
}
}
try {
value = config.getOptionValue(WebContextInitParameter.NumberOfFlashesBetweenFlashReapings);
numberOfFlashesBetweenFlashReapings = Long.parseLong(value);
} catch (NumberFormatException nfe) {
if (LOGGER.isLoggable(Level.WARNING)) {
LOGGER.log(Level.WARNING, "Unable to set number flashes between flash repaings. Defaulting to {0}", numberOfFlashesBetweenFlashReapings);
}
}
distributable = config.isOptionEnabled(EnableDistributable);
guard = new ByteArrayGuardAESCTR();
}
/**
* <p>Returns the flash <code>Map</code> for this application. This is
* a convenience method that calls
* <code>FacesContext.getCurrentInstance()</code> and then calls the
* overloaded <code>getFlash()</code> that takes a
* <code>FacesContext</code> with it.</p>
*
* @return The flash <code>Map</code> for this session.
*/
public static Map<String,Object> getFlash() {
FacesContext context = FacesContext.getCurrentInstance();
return getFlash(context.getExternalContext(), true);
}
/**
*
* @param extContext the <code>ExternalContext</code> for this request.
*
* @param create <code>true</code> to create a new instance for this request if
* necessary; <code>false</code> to return <code>null</code> if there's no
* instance in the current <code>session</code>.
*
* @return The flash <code>Map</code> for this session.
*/
static ELFlash getFlash(ExternalContext extContext, boolean create) {
Map<String, Object> appMap = extContext.getApplicationMap();
ELFlash flash = (ELFlash)
appMap.get(FLASH_ATTRIBUTE_NAME);
if (null == flash && create) {
synchronized (extContext.getContext()) {
if (null == (flash = (ELFlash)
appMap.get(FLASH_ATTRIBUTE_NAME))) {
flash = new ELFlash(extContext);
appMap.put(FLASH_ATTRIBUTE_NAME, flash);
}
}
}
/*
* If we are in a clustered environment and a session is active, store
* a helper to ensure our innerMap gets successfully replicated.
*/
if (appMap.get(EnableDistributable.getQualifiedName()) != null) {
synchronized (extContext.getContext()) {
if (extContext.getSession(false) != null) {
SessionHelper sessionHelper = SessionHelper.getInstance(extContext);
if (sessionHelper == null) {
sessionHelper = new SessionHelper();
}
sessionHelper.update(extContext, flash);
}
}
}
return flash;
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="Abstract class overrides">
@Override
public boolean isKeepMessages() {
boolean result = false;
Map<String, Object> phaseMap;
if (null != (phaseMap = loggingGetPhaseMapForReading(false))) {
Object value = phaseMap.get(CONSTANTS.KeepAllMessagesAttributeName.toString());
result = (null != value) ? (Boolean) value : false;
}
return result;
}
@Override
public void setKeepMessages(boolean newValue) {
loggingGetPhaseMapForWriting(false).put(CONSTANTS.KeepAllMessagesAttributeName.toString(),
Boolean.valueOf(newValue));
}
@Override
public boolean isRedirect() {
boolean result = false;
FacesContext context = FacesContext.getCurrentInstance();
Map<Object, Object> contextMap = context.getAttributes();
PreviousNextFlashInfoManager flashManager;
if (null != (flashManager = getCurrentFlashManager(contextMap, false))) {
result = flashManager.getPreviousRequestFlashInfo().isIsRedirect();
}
return result;
}
// PENDING(edburns): I'm going to make an entry to the errata. This
// method can't be implemented because the decision of whether or
// not to redirect is made by the navigationHandler.
@Override
public void setRedirect(boolean newValue) {
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="Map overrides">
@SuppressWarnings(ELEMENT_TYPE_MISMATCH)
@Override
public Object get(Object key) {
Object result = null;
FacesContext context = FacesContext.getCurrentInstance();
if (null != key) {
if (key.equals("keepMessages")) {
result = this.isKeepMessages();
} else if (key.equals("redirect")) {
result = this.isRedirect();
} else {
if (isKeepFlagSet(context)) {
result = getPhaseMapForReading().get(key);
keep(key.toString());
clearKeepFlag(context);
return result;
}
}
}
if (null == result) {
result = getPhaseMapForReading().get(key);
}
if (distributable && context.getExternalContext().getSession(false) != null) {
SessionHelper sessionHelper =
SessionHelper.getInstance(context.getExternalContext());
if (sessionHelper != null) {
sessionHelper.update(context.getExternalContext(), this);
}
}
if (LOGGER.isLoggable(Level.FINEST)) {
LOGGER.log(Level.FINEST, "get({0}) = {1}", new Object [] { key, result});
}
return result;
}
@Override
public Object put(String key, Object value) {
Boolean b = null;
Object result = null;
boolean wasSpecialPut = false;
if (null != key) {
if (key.equals("keepMessages")) {
this.setKeepMessages(b = Boolean.parseBoolean((String) value));
wasSpecialPut = true;
}
if (key.equals("redirect")) {
this.setRedirect(b = Boolean.parseBoolean((String) value));
wasSpecialPut = true;
}
}
FacesContext context = FacesContext.getCurrentInstance();
if (!wasSpecialPut) {
result = (null == b) ? getPhaseMapForWriting().put(key, value) : b;
if (LOGGER.isLoggable(Level.FINEST)) {
LOGGER.log(Level.FINEST, "put({0},{1})", new Object [] { key, value});
}
context.getApplication().publishEvent(context, PostPutFlashValueEvent.class, key);
}
if (distributable && context.getExternalContext().getSession(false) != null) {
SessionHelper sessionHelper =
SessionHelper.getInstance(context.getExternalContext());
if (sessionHelper != null) {
sessionHelper.update(context.getExternalContext(), this);
}
}
return result;
}
@SuppressWarnings(ELEMENT_TYPE_MISMATCH)
@Override
public Object remove(Object key) {
Object result = null;
FacesContext context = FacesContext.getCurrentInstance();
context.getApplication().publishEvent(context, PreRemoveFlashValueEvent.class, key);
result = getPhaseMapForWriting().remove(key);
return result;
}
@SuppressWarnings(ELEMENT_TYPE_MISMATCH)
@Override
public boolean containsKey(Object key) {
boolean result = false;
result = getPhaseMapForReading().containsKey(key);
return result;
}
@Override
public boolean containsValue(Object value) {
boolean result = false;
result = getPhaseMapForReading().containsValue(value);
return result;
}
@Override
public void putAll(Map<? extends String, ?> t) {
getPhaseMapForWriting().putAll(t);
}
@Override
public Collection<Object> values() {
Collection<Object> result = null;
result = getPhaseMapForReading().values();
return result;
}
@Override
public int size() {
int result = 0;
result = getPhaseMapForReading().size();
return result;
}
@Override
public void clear() {
getPhaseMapForWriting().clear();
}
@SuppressWarnings({"CloneDoesntCallSuperClone"})
@Override
protected Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException();
}
@Override
public Set<Map.Entry<String, Object>> entrySet() {
Set<Map.Entry<String, Object>>
readingMapEntrySet = getPhaseMapForReading().entrySet(),
writingMapEntrySet = getPhaseMapForWriting().entrySet(),
result = null;
result = new HashSet<>();
result.addAll(readingMapEntrySet);
result.addAll(writingMapEntrySet);
return result;
}
@Override
public boolean isEmpty() {
boolean
readingMapIsEmpty = getPhaseMapForReading().isEmpty(),
writingMapIsEmpty = getPhaseMapForWriting().isEmpty(),
result = false;
result = readingMapIsEmpty && writingMapIsEmpty;
return result;
}
@Override
public Set<String> keySet() {
Set<String>
readingMapKeySet = getPhaseMapForReading().keySet(),
writingMapKeySet = getPhaseMapForWriting().keySet(),
result = null;
result = new HashSet<>();
result.addAll(readingMapKeySet);
result.addAll(writingMapKeySet);
return result;
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="Flash overrides">
@Override
public void keep(String key) {
FacesContext context = FacesContext.getCurrentInstance();
Map<String, Object> requestMap = context.getExternalContext().getRequestMap();
Map<Object, Object> contextMap = context.getAttributes();
PreviousNextFlashInfoManager flashManager;
if (null != (flashManager = getCurrentFlashManager(contextMap, true))) {
Object toKeep;
if (null == (toKeep = requestMap.remove(key))) {
FlashInfo flashInfo = null;
if (null != (flashInfo = flashManager.getPreviousRequestFlashInfo())) {
toKeep = flashInfo.getFlashMap().get(key);
}
}
if (null != toKeep) {
getPhaseMapForWriting().put(key, toKeep);
context.getApplication().publishEvent(context, PostKeepFlashValueEvent.class, key);
}
}
}
@Override
public void putNow(String key, Object value) {
FacesContext context = FacesContext.getCurrentInstance();
Map<Object, Object> contextMap = context.getAttributes();
PreviousNextFlashInfoManager flashManager;
if (null != (flashManager = getCurrentFlashManager(contextMap, true))) {
FlashInfo flashInfo = null;
if (null != (flashInfo = flashManager.getPreviousRequestFlashInfo())) {
flashInfo.getFlashMap().put(key, value);
}
}
}
@Override
public void doPrePhaseActions(FacesContext context) {
PhaseId currentPhase = context.getCurrentPhaseId();
Map<Object, Object> contextMap = context.getAttributes();
contextMap.put(CONSTANTS.SavedResponseCompleteFlagValue,
context.getResponseComplete());
Cookie cookie = null;
if (currentPhase.equals(PhaseId.RESTORE_VIEW)) {
if (null != (cookie = getCookie(context.getExternalContext()))) {
getCurrentFlashManager(context, contextMap, cookie);
}
if (this.isKeepMessages()) {
this.restoreAllMessages(context);
}
} else if (currentPhase.equals(PhaseId.RENDER_RESPONSE) &&
contextMap.containsKey(ForceAlwaysWriteFlashCookie) &&
(Boolean) contextMap.get(ForceAlwaysWriteFlashCookie)) {
PreviousNextFlashInfoManager flashManager = getCurrentFlashManager(contextMap, true);
cookie = flashManager.encode();
if (null != cookie) {
setCookie(context, flashManager, cookie, true);
} else {
if (LOGGER.isLoggable(Level.WARNING)) {
LOGGER.log(Level.WARNING,
"jsf.externalcontext.flash.force.write.cookie.failed");
}
}
}
}
@Override
public void doPostPhaseActions(FacesContext context) {
if (context.getAttributes().containsKey(ACT_AS_DO_LAST_PHASE_ACTIONS)) {
Boolean outgoingResponseIsRedirect =
(Boolean) context.getAttributes().get(ACT_AS_DO_LAST_PHASE_ACTIONS);
doLastPhaseActions(context, outgoingResponseIsRedirect);
return;
}
PhaseId currentPhase = context.getCurrentPhaseId();
Map<Object, Object> contextMap = context.getAttributes();
boolean
responseCompleteJustSetTrue = responseCompleteWasJustSetTrue(context, contextMap),
lastPhaseForThisRequest = responseCompleteJustSetTrue ||
currentPhase == PhaseId.RENDER_RESPONSE;
if (lastPhaseForThisRequest) {
doLastPhaseActions(context, false);
}
}
public static final String ACT_AS_DO_LAST_PHASE_ACTIONS =
ELFlash.class.getPackage().getName() + ".ACT_AS_DO_LAST_PHASE_ACTIONS";
/**
* <p>This is the most magic of methods. There are several scenarios
* in which this method can be called, but the first time it is
* called for a request it takes action, while on subsequent times
* it returns without taking action. This is due to the call to
* {@link #releaseCurrentFlashManager}. After this call, any calls
* to {@link #getCurrentFlashManager} will return null.</p>
* <p>Scenario 1: normal request ending. This will be called after
* the RENDER_RESPONSE phase executes. outgoingResponseIsRedirect will be false.</p>
* <p>Scenario 2: navigationHandler asks extContext for redirect.
* In this case, extContext calls this method directly,
* outgoingResponseIsRedirect will be true.</p>
* <p>Scenario 3: extContext.flushBuffer(): As far as I can tell,
* this is only called in the JSP case, but it's good to call it
* from there anyway, because we need to write our cookie before the
* response is committed. outgoingResponseIsRedirect is false.</p>
* <p>Scenario 4: after rendering the response in JSP, but before
* the buffer is flushed. In the JSP case, I've found this necessary
* because the call to extContext.flushBuffer() is too late, the
* response has already been committed by that
* point. outgoingResponseIsRedirect is false.</p>
*/
public void doLastPhaseActions(FacesContext context, boolean outgoingResponseIsRedirect) {
Map<Object, Object> contextMap = context.getAttributes();
PreviousNextFlashInfoManager flashManager = getCurrentFlashManager(contextMap, false);
if (null == flashManager) {
return;
}
if (this.isKeepMessages()) {
this.saveAllMessages(context);
}
releaseCurrentFlashManager(contextMap);
// What we do in this if-else statement has consequences for
// PreviousNextFlashInfoManager.decode().
if (outgoingResponseIsRedirect) {
FlashInfo previousRequestFlashInfo = flashManager.getPreviousRequestFlashInfo();
// Next two methods are VITALLY IMPORTANT!
previousRequestFlashInfo.setIsRedirect(true);
flashManager.expireNext_MovePreviousToNext();
} else {
FlashInfo flashInfo = flashManager.getPreviousRequestFlashInfo();
if (null != flashInfo && flashInfo.getLifetimeMarker() ==
LifetimeMarker.SecondTimeThru) {
flashManager.expirePrevious();
}
}
if (LOGGER.isLoggable(Level.FINEST)) {
LOGGER.log(Level.FINEST, "---------------------------------------");
}
setCookie(context, flashManager, flashManager.encode(), false);
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="Helpers">
void setFlashInnerMap(Map<String,Map<String, Object>> flashInnerMap) {
this.flashInnerMap = flashInnerMap;
}
Map<String, Map<String,Object>> getFlashInnerMap() {
return flashInnerMap;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("[\n");
for (Map.Entry<String, Object> entry : this.entrySet()) {
builder.append("{").append(entry.getKey()).append(", ").append(entry.getValue()).append("}\n");
}
builder.append("]\n");
return builder.toString();
}
private void maybeWriteCookie(FacesContext context,
PreviousNextFlashInfoManager flashManager) {
FlashInfo flashInfo = flashManager.getPreviousRequestFlashInfo();
if (null != flashInfo && flashInfo.getLifetimeMarker() ==
LifetimeMarker.SecondTimeThru) {
PreviousNextFlashInfoManager copiedFlashManager =
flashManager.copyWithoutInnerMap();
copiedFlashManager.expirePrevious();
setCookie(context, flashManager,
copiedFlashManager.encode(), false);
}
}
static void setKeepFlag(FacesContext context) {
context.getAttributes().put(CONSTANTS.KeepFlagAttributeName, Boolean.TRUE);
}
void clearKeepFlag(FacesContext context) {
context.getAttributes().remove(CONSTANTS.KeepFlagAttributeName);
}
boolean isKeepFlagSet(FacesContext context) {
return Boolean.TRUE ==
context.getAttributes().get(CONSTANTS.KeepFlagAttributeName);
}
private long getNewSequenceNumber() {
long result = sequenceNumber.incrementAndGet();
if (0 == result % numberOfFlashesBetweenFlashReapings) {
reapFlashes();
}
if (result == Long.MAX_VALUE) {
result = 1;
sequenceNumber.set(1);
}
return result;
}
private void reapFlashes() {
if (flashInnerMap.size() < numberOfConcurentFlashUsers) {
return;
}
Set<String> keys = flashInnerMap.keySet();
long
sequenceNumberToTest,
currentSequenceNumber = sequenceNumber.get();
Map<String, Object> curFlash;
for (String cur : keys) {
sequenceNumberToTest = Long.parseLong(cur);
if (numberOfConcurentFlashUsers < currentSequenceNumber - sequenceNumberToTest) {
if (null != (curFlash = flashInnerMap.get(cur))) {
curFlash.clear();
}
flashInnerMap.remove(cur);
}
}
if (distributable && FacesContext.getCurrentInstance().getExternalContext().getSession(false) != null) {
ExternalContext extContext = FacesContext.getCurrentInstance().getExternalContext();
SessionHelper sessionHelper = SessionHelper.getInstance(extContext);
if (null != sessionHelper) {
sessionHelper.remove(extContext);
sessionHelper = new SessionHelper();
sessionHelper.update(extContext, this);
}
}
}
private boolean responseCompleteWasJustSetTrue(FacesContext context,
Map<Object, Object> contextMap) {
boolean result = false;
// If it was false, but it's now true, return true
result = (Boolean.FALSE == contextMap.get(CONSTANTS.SavedResponseCompleteFlagValue) &&
context.getResponseComplete());
return result;
}
private static String getLogPrefix(FacesContext context) {
StringBuilder result = new StringBuilder();
ExternalContext extContext = context.getExternalContext();
Object request = extContext.getRequest();
if (request instanceof HttpServletRequest) {
result.append(((HttpServletRequest)request).getMethod()).append(" ");
}
UIViewRoot root = context.getViewRoot();
if (null != root) {
String viewId = root.getViewId();
if (null != viewId) {
result.append(viewId).append(" ");
}
}
return result.toString();
}
private Map<String, Object> loggingGetPhaseMapForWriting(boolean loggingEnabled) {
FacesContext context = FacesContext.getCurrentInstance();
Map<String, Object> result = null;
PhaseId currentPhase = context.getCurrentPhaseId();
Map<Object, Object> contextMap = context.getAttributes();
PreviousNextFlashInfoManager flashManager;
if (null != (flashManager = getCurrentFlashManager(contextMap, true))) {
FlashInfo flashInfo;
boolean isDebugLog = loggingEnabled && LOGGER.isLoggable(Level.FINEST);
if (currentPhase.getOrdinal() < PhaseId.RENDER_RESPONSE.getOrdinal()) {
flashInfo = flashManager.getPreviousRequestFlashInfo();
if (isDebugLog) {
LOGGER.log(Level.FINEST, "{0}previous[{1}]",
new Object[]{getLogPrefix(context),
flashInfo.getSequenceNumber()});
}
} else {
flashInfo = flashManager.getNextRequestFlashInfo(this, true);
if (isDebugLog) {
LOGGER.log(Level.FINEST, "{0}next[{1}]",
new Object[]{getLogPrefix(context),
flashInfo.getSequenceNumber()});
}
maybeWriteCookie(context, flashManager);
}
result = flashInfo.getFlashMap();
}
return result;
}
/**
* <p>If the current phase is earlier than RENDER_RESPONSE, return
* the map for the "previous" request. Otherwise, return the map
* for the "next" request. Note that we use
* getCurrentFlashManager(contextMap,true). This is because if this
* method is being called, we know we actually need the map, so we
* have to ensure the underlying data structure is present before
* trying to access it.</p>
*/
private Map<String, Object> getPhaseMapForWriting() {
return loggingGetPhaseMapForWriting(true);
}
private Map<String, Object> loggingGetPhaseMapForReading(boolean loggingEnabled) {
FacesContext context = FacesContext.getCurrentInstance();
Map<String, Object> result = Collections.emptyMap();
Map<Object, Object> contextMap = context.getAttributes();
PreviousNextFlashInfoManager flashManager;
if (null != (flashManager = getCurrentFlashManager(contextMap, false))) {
FlashInfo flashInfo;
if (null != (flashInfo = flashManager.getPreviousRequestFlashInfo())) {
boolean isDebugLog = loggingEnabled && LOGGER.isLoggable(Level.FINEST);
if (isDebugLog) {
LOGGER.log(Level.FINEST, "{0}previous[{1}]",
new Object[]{getLogPrefix(context),
flashInfo.getSequenceNumber()});
}
result = flashInfo.getFlashMap();
}
}
return result;
}
/**
* <p>Always return the map for the "previous" request. Note that
* we use getCurrentFlashManager(contextMap,false). This is because
* if this method is being called, and there is pre-existing data in
* the flash from a previous write, then the
* PreviousNextFlashInfoManager will already have been created. If
* there is not pre-existing data, we don't create the
* PreviousNextFlashInfoManager, and therefore just return the empty
* map.</p>
*/
private Map<String, Object> getPhaseMapForReading() {
return loggingGetPhaseMapForReading(true);
}
void saveAllMessages(FacesContext context) {
// take no action on the GET that comes after a REDIRECT
Map<Object, Object> contextMap = context.getAttributes();
PreviousNextFlashInfoManager flashManager;
if (null == (flashManager = getCurrentFlashManager(contextMap, true))) {
return;
}
if (flashManager.getPreviousRequestFlashInfo().isIsRedirect()) {
return;
}
Iterator<String> messageClientIds = context.getClientIdsWithMessages();
List<FacesMessage> facesMessages;
Map<String, List<FacesMessage>> allFacesMessages = null;
Iterator<FacesMessage> messageIter;
String curMessageId;
// Save all the FacesMessages into a Map, which we store in the flash.
// Step 1, go through the FacesMessage instances for each clientId
// in the messageClientIds list.
while (messageClientIds.hasNext()) {
curMessageId = messageClientIds.next();
// Get the messages for this clientId
messageIter = context.getMessages(curMessageId);
facesMessages = new ArrayList<>();
while (messageIter.hasNext()) {
facesMessages.add(messageIter.next());
}
// Add the list to the map
if (null == allFacesMessages) {
allFacesMessages = new HashMap<>();
}
allFacesMessages.put(curMessageId, facesMessages);
}
facesMessages = null;