/
Session.java
1062 lines (955 loc) · 32.4 KB
/
Session.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
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
//
// ========================================================================
// Copyright (c) 1995-2021 Mort Bay Consulting Pty Ltd and others.
//
// This program and the accompanying materials are made available under the
// terms of the Eclipse Public License v. 2.0 which is available at
// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0
// which is available at https://www.apache.org/licenses/LICENSE-2.0.
//
// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
// ========================================================================
//
package org.eclipse.jetty.server.session;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSessionActivationListener;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionBindingListener;
import javax.servlet.http.HttpSessionContext;
import javax.servlet.http.HttpSessionEvent;
import org.eclipse.jetty.io.CyclicTimeout;
import org.eclipse.jetty.util.thread.AutoLock;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Session
*
* A heavy-weight Session object representing an HttpSession. Session objects
* relating to a context are kept in a {@link SessionCache}. The purpose of the
* SessionCache is to keep the working set of Session objects in memory so that
* they may be accessed quickly, and facilitate the sharing of a Session object
* amongst multiple simultaneous requests referring to the same session id.
*
* The {@link SessionHandler} coordinates the lifecycle of Session objects with
* the help of the SessionCache.
*
* @see SessionHandler
* @see org.eclipse.jetty.server.SessionIdManager
*/
public class Session implements SessionHandler.SessionIf
{
private static final Logger LOG = LoggerFactory.getLogger(Session.class);
/**
*
*/
public static final String SESSION_CREATED_SECURE = "org.eclipse.jetty.security.sessionCreatedSecure";
/**
* State
*
* Validity states of a session
*/
public enum State
{
VALID, INVALID, INVALIDATING, CHANGING
}
public enum IdState
{
SET, CHANGING
}
protected final SessionData _sessionData; // the actual data associated with
// a session
protected final SessionHandler _handler; // the manager of the session
protected String _extendedId; // the _id plus the worker name
protected long _requests;
protected boolean _idChanged;
protected boolean _newSession;
protected State _state = State.VALID; // state of the session:valid,invalid
// or being invalidated
protected AutoLock _lock = new AutoLock();
protected Condition _stateChangeCompleted = _lock.newCondition();
protected boolean _resident = false;
protected final SessionInactivityTimer _sessionInactivityTimer;
/**
* SessionInactivityTimer
*
* Each Session has a timer associated with it that fires whenever it has
* been idle (ie not accessed by a request) for a configurable amount of
* time, or the Session expires.
*
* @see SessionCache
*/
public class SessionInactivityTimer
{
protected final CyclicTimeout _timer;
public SessionInactivityTimer()
{
_timer = new CyclicTimeout((getSessionHandler().getScheduler()))
{
@Override
public void onTimeoutExpired()
{
if (LOG.isDebugEnabled())
LOG.debug("Timer expired for session {}", getId());
long now = System.currentTimeMillis();
//handle what to do with the session after the timer expired
getSessionHandler().sessionInactivityTimerExpired(Session.this, now);
try (AutoLock l = Session.this.lock())
{
//grab the lock and check what happened to the session: if it didn't get evicted and
//it hasn't expired, we need to reset the timer
if (Session.this.isResident() && Session.this.getRequests() <= 0 && Session.this.isValid() &&
!Session.this.isExpiredAt(now))
{
//session wasn't expired or evicted, we need to reset the timer
SessionInactivityTimer.this.schedule(Session.this.calculateInactivityTimeout(now));
}
}
}
};
}
/**
* @param time the timeout to set; -1 means that the timer will not be
* scheduled
*/
public void schedule(long time)
{
if (time >= 0)
{
if (LOG.isDebugEnabled())
LOG.debug("(Re)starting timer for session {} at {}ms", getId(), time);
_timer.schedule(time, TimeUnit.MILLISECONDS);
}
else
{
if (LOG.isDebugEnabled())
LOG.debug("Not starting timer for session {}", getId());
}
}
public void cancel()
{
_timer.cancel();
if (LOG.isDebugEnabled())
LOG.debug("Cancelled timer for session {}", getId());
}
public void destroy()
{
_timer.destroy();
if (LOG.isDebugEnabled())
LOG.debug("Destroyed timer for session {}", getId());
}
}
/**
* Create a new session
*
* @param handler the SessionHandler that manages this session
* @param request the request the session should be based on
* @param data the session data
*/
public Session(SessionHandler handler, HttpServletRequest request, SessionData data)
{
_handler = handler;
_sessionData = data;
_newSession = true;
_sessionData.setDirty(true);
_sessionInactivityTimer = new SessionInactivityTimer();
}
/**
* Re-inflate an existing session from some eg persistent store.
*
* @param handler the SessionHandler managing the session
* @param data the session data
*/
public Session(SessionHandler handler, SessionData data)
{
_handler = handler;
_sessionData = data;
_sessionInactivityTimer = new SessionInactivityTimer();
}
/**
* Returns the current number of requests that are active in the Session.
*
* @return the number of active requests for this session
*/
public long getRequests()
{
try (AutoLock l = _lock.lock())
{
return _requests;
}
}
public void setExtendedId(String extendedId)
{
_extendedId = extendedId;
}
protected void cookieSet()
{
try (AutoLock l = _lock.lock())
{
_sessionData.setCookieSet(_sessionData.getAccessed());
}
}
protected void use()
{
try (AutoLock l = _lock.lock())
{
_requests++;
// temporarily stop the idle timer
if (LOG.isDebugEnabled())
LOG.debug("Session {} in use, stopping timer, active requests={}", getId(), _requests);
_sessionInactivityTimer.cancel();
}
}
protected boolean access(long time)
{
try (AutoLock l = _lock.lock())
{
if (!isValid() || !isResident())
return false;
_newSession = false;
long lastAccessed = _sessionData.getAccessed();
_sessionData.setAccessed(time);
_sessionData.setLastAccessed(lastAccessed);
_sessionData.calcAndSetExpiry(time);
if (isExpiredAt(time))
{
invalidate();
return false;
}
return true;
}
}
protected void complete()
{
try (AutoLock l = _lock.lock())
{
_requests--;
if (LOG.isDebugEnabled())
LOG.debug("Session {} complete, active requests={}", getId(), _requests);
// start the inactivity timer if necessary
if (_requests == 0)
{
//update the expiry time to take account of the time all requests spent inside of the
//session.
long now = System.currentTimeMillis();
_sessionData.calcAndSetExpiry(now);
_sessionInactivityTimer.schedule(calculateInactivityTimeout(now));
}
}
}
/**
* Check to see if session has expired as at the time given.
*
* @param time the time since the epoch in ms
* @return true if expired
*/
protected boolean isExpiredAt(long time)
{
try (AutoLock l = _lock.lock())
{
return _sessionData.isExpiredAt(time);
}
}
/**
* Check if the Session has been idle longer than a number of seconds.
*
* @param sec the number of seconds
* @return true if the session has been idle longer than the interval
*/
protected boolean isIdleLongerThan(int sec)
{
long now = System.currentTimeMillis();
try (AutoLock l = _lock.lock())
{
return ((_sessionData.getAccessed() + (sec * 1000)) <= now);
}
}
/**
* Call binding and attribute listeners based on the new and old values of
* the attribute.
*
* @param name name of the attribute
* @param newValue new value of the attribute
* @param oldValue previous value of the attribute
* @throws IllegalStateException if no session manager can be find
*/
protected void callSessionAttributeListeners(String name, Object newValue, Object oldValue)
{
if (newValue == null || !newValue.equals(oldValue))
{
if (oldValue != null)
unbindValue(name, oldValue);
if (newValue != null)
bindValue(name, newValue);
if (_handler == null)
throw new IllegalStateException("No session manager for session " + _sessionData.getId());
_handler.doSessionAttributeListeners(this, name, oldValue, newValue);
}
}
/**
* Unbind value if value implements {@link HttpSessionBindingListener}
* (calls
* {@link HttpSessionBindingListener#valueUnbound(HttpSessionBindingEvent)})
*
* @param name the name with which the object is bound or unbound
* @param value the bound value
*/
public void unbindValue(java.lang.String name, Object value)
{
if (value instanceof HttpSessionBindingListener)
((HttpSessionBindingListener)value).valueUnbound(new HttpSessionBindingEvent(this, name));
}
/**
* Bind value if value implements {@link HttpSessionBindingListener} (calls
* {@link HttpSessionBindingListener#valueBound(HttpSessionBindingEvent)})
*
* @param name the name with which the object is bound or unbound
* @param value the bound value
*/
public void bindValue(java.lang.String name, Object value)
{
if (value instanceof HttpSessionBindingListener)
((HttpSessionBindingListener)value).valueBound(new HttpSessionBindingEvent(this, name));
}
/**
* Call the activation listeners. This must be called holding the lock.
*/
public void didActivate()
{
//A passivate listener might remove a non-serializable attribute that
//the activate listener might put back in again, which would spuriously
//set the dirty bit to true, causing another round of passivate/activate
//when the request exits. The store clears the dirty bit if it does a
//save, so ensure dirty flag is set to the value determined by the store,
//not a passivation listener.
boolean dirty = getSessionData().isDirty();
try
{
HttpSessionEvent event = new HttpSessionEvent(this);
for (String name : _sessionData.getKeys())
{
Object value = _sessionData.getAttribute(name);
if (value instanceof HttpSessionActivationListener)
{
HttpSessionActivationListener listener = (HttpSessionActivationListener)value;
listener.sessionDidActivate(event);
}
}
}
finally
{
getSessionData().setDirty(dirty);
}
}
/**
* Call the passivation listeners. This must be called holding the lock
*/
public void willPassivate()
{
HttpSessionEvent event = new HttpSessionEvent(this);
for (String name : _sessionData.getKeys())
{
Object value = _sessionData.getAttribute(name);
if (value instanceof HttpSessionActivationListener)
{
HttpSessionActivationListener listener = (HttpSessionActivationListener)value;
listener.sessionWillPassivate(event);
}
}
}
public boolean isValid()
{
try (AutoLock l = _lock.lock())
{
return _state == State.VALID;
}
}
public boolean isInvalid()
{
try (AutoLock l = _lock.lock())
{
return _state == State.INVALID || _state == State.INVALIDATING;
}
}
public long getCookieSetTime()
{
try (AutoLock l = _lock.lock())
{
return _sessionData.getCookieSet();
}
}
@Override
public long getCreationTime() throws IllegalStateException
{
try (AutoLock l = _lock.lock())
{
checkValidForRead();
return _sessionData.getCreated();
}
}
@Override
public String getId()
{
try (AutoLock l = _lock.lock())
{
return _sessionData.getId();
}
}
public String getExtendedId()
{
return _extendedId;
}
public String getContextPath()
{
return _sessionData.getContextPath();
}
public String getVHost()
{
return _sessionData.getVhost();
}
@Override
public long getLastAccessedTime()
{
try (AutoLock l = _lock.lock())
{
checkValidForRead();
return _sessionData.getLastAccessed();
}
}
@Override
public ServletContext getServletContext()
{
if (_handler == null)
throw new IllegalStateException("No session manager for session " + _sessionData.getId());
return _handler._context;
}
@Override
public void setMaxInactiveInterval(int secs)
{
try (AutoLock l = _lock.lock())
{
_sessionData.setMaxInactiveMs((long)secs * 1000L);
_sessionData.calcAndSetExpiry();
//dirty metadata writes can be skipped, but changing the
//maxinactiveinterval should write the session out because
//it may affect the session on other nodes, or on the same
//node in the case of the nullsessioncache
_sessionData.setDirty(true);
if (LOG.isDebugEnabled())
{
if (secs <= 0)
LOG.debug("Session {} is now immortal (maxInactiveInterval={})", _sessionData.getId(), secs);
else
LOG.debug("Session {} maxInactiveInterval={}", _sessionData.getId(), secs);
}
}
}
/**
* Calculate what the session timer setting should be based on:
* the time remaining before the session expires
* and any idle eviction time configured.
* The timer value will be the lesser of the above.
*
* @param now the time at which to calculate remaining expiry
* @return the time remaining before expiry or inactivity timeout
*/
public long calculateInactivityTimeout(long now)
{
long time = 0;
try (AutoLock l = _lock.lock())
{
long remaining = _sessionData.getExpiry() - now;
long maxInactive = _sessionData.getMaxInactiveMs();
int evictionPolicy = getSessionHandler().getSessionCache().getEvictionPolicy();
if (maxInactive <= 0)
{
// sessions are immortal, they never expire
if (evictionPolicy < SessionCache.EVICT_ON_INACTIVITY)
{
// we do not want to evict inactive sessions
time = -1;
if (LOG.isDebugEnabled())
LOG.debug("Session {} is immortal && no inactivity eviction", getId());
}
else
{
// sessions are immortal but we want to evict after
// inactivity
time = TimeUnit.SECONDS.toMillis(evictionPolicy);
if (LOG.isDebugEnabled())
LOG.debug("Session {} is immortal; evict after {} sec inactivity", getId(), evictionPolicy);
}
}
else
{
// sessions are not immortal
if (evictionPolicy == SessionCache.NEVER_EVICT)
{
// timeout is the time remaining until its expiry
time = (remaining > 0 ? remaining : 0);
if (LOG.isDebugEnabled())
LOG.debug("Session {} no eviction", getId());
}
else if (evictionPolicy == SessionCache.EVICT_ON_SESSION_EXIT)
{
// session will not remain in the cache, so no timeout
time = -1;
if (LOG.isDebugEnabled())
LOG.debug("Session {} evict on exit", getId());
}
else
{
// want to evict on idle: timer is lesser of the session's
// expiration remaining and the time to evict
time = (remaining > 0 ? (Math.min(maxInactive, TimeUnit.SECONDS.toMillis(evictionPolicy))) : 0);
if (LOG.isDebugEnabled())
LOG.debug("Session {} timer set to lesser of maxInactive={} and inactivityEvict={}", getId(),
maxInactive, evictionPolicy);
}
}
}
return time;
}
@Override
public int getMaxInactiveInterval()
{
try (AutoLock l = _lock.lock())
{
long maxInactiveMs = _sessionData.getMaxInactiveMs();
return (int)(maxInactiveMs < 0 ? -1 : maxInactiveMs / 1000);
}
}
@Override
@Deprecated(since = "Servlet API 2.1")
public HttpSessionContext getSessionContext()
{
checkValidForRead();
return SessionHandler.__nullSessionContext;
}
public SessionHandler getSessionHandler()
{
return _handler;
}
/**
* Check that the session can be modified.
*
* @throws IllegalStateException if the session is invalid
*/
protected void checkValidForWrite() throws IllegalStateException
{
if (_state == State.INVALID)
throw new IllegalStateException("Not valid for write: id=" + _sessionData.getId() +
" created=" + _sessionData.getCreated() +
" accessed=" + _sessionData.getAccessed() +
" lastaccessed=" + _sessionData.getLastAccessed() +
" maxInactiveMs=" + _sessionData.getMaxInactiveMs() +
" expiry=" + _sessionData.getExpiry());
if (_state == State.INVALIDATING)
return; // in the process of being invalidated, listeners may try to
// remove attributes
if (!isResident())
throw new IllegalStateException("Not valid for write: id=" + _sessionData.getId() + " not resident");
}
/**
* Chech that the session data can be read.
*
* @throws IllegalStateException if the session is invalid
*/
protected void checkValidForRead() throws IllegalStateException
{
if (_state == State.INVALID)
throw new IllegalStateException("Invalid for read: id=" + _sessionData.getId() +
" created=" + _sessionData.getCreated() +
" accessed=" + _sessionData.getAccessed() +
" lastaccessed=" + _sessionData.getLastAccessed() +
" maxInactiveMs=" + _sessionData.getMaxInactiveMs() +
" expiry=" + _sessionData.getExpiry());
if (_state == State.INVALIDATING)
return;
if (!isResident())
throw new IllegalStateException("Invalid for read: id=" + _sessionData.getId() + " not resident");
}
@Override
public Object getAttribute(String name)
{
try (AutoLock l = _lock.lock())
{
checkValidForRead();
return _sessionData.getAttribute(name);
}
}
@Override
@Deprecated(since = "Servlet API 2.2")
public Object getValue(String name)
{
try (AutoLock l = _lock.lock())
{
checkValidForRead();
return _sessionData.getAttribute(name);
}
}
@Override
public Enumeration<String> getAttributeNames()
{
try (AutoLock l = _lock.lock())
{
checkValidForRead();
final Iterator<String> itor = _sessionData.getKeys().iterator();
return new Enumeration<>()
{
@Override
public boolean hasMoreElements()
{
return itor.hasNext();
}
@Override
public String nextElement()
{
return itor.next();
}
};
}
}
public int getAttributes()
{
return _sessionData.getKeys().size();
}
public Set<String> getNames()
{
return Collections.unmodifiableSet(_sessionData.getKeys());
}
/**
* @deprecated As of Servlet 2.2, this method is replaced by
* {@link #getAttributeNames}
*/
@Override
@Deprecated(since = "Servlet API 2.2")
public String[] getValueNames() throws IllegalStateException
{
try (AutoLock l = _lock.lock())
{
checkValidForRead();
Iterator<String> itor = _sessionData.getKeys().iterator();
if (!itor.hasNext())
return new String[0];
ArrayList<String> names = new ArrayList<>();
while (itor.hasNext())
{
names.add(itor.next());
}
return names.toArray(new String[names.size()]);
}
}
@Override
public void setAttribute(String name, Object value)
{
Object old = null;
try (AutoLock l = _lock.lock())
{
// if session is not valid, don't accept the set
checkValidForWrite();
old = _sessionData.setAttribute(name, value);
}
if (value == null && old == null)
return; // if same as remove attribute but attribute was already
// removed, no change
callSessionAttributeListeners(name, value, old);
}
@Override
@Deprecated(since = "Servlet API 2.2")
public void putValue(String name, Object value)
{
setAttribute(name, value);
}
@Override
public void removeAttribute(String name)
{
setAttribute(name, null);
}
@Override
@Deprecated(since = "Servlet API 2.1")
public void removeValue(String name)
{
setAttribute(name, null);
}
/**
* Force a change to the id of a session.
*
* @param request the Request associated with the call to change id.
*/
public void renewId(HttpServletRequest request)
{
if (_handler == null)
throw new IllegalStateException("No session manager for session " + _sessionData.getId());
String id = null;
String extendedId = null;
try (AutoLock l = _lock.lock())
{
while (true)
{
switch (_state)
{
case INVALID:
case INVALIDATING:
throw new IllegalStateException();
case CHANGING:
try
{
_stateChangeCompleted.await();
}
catch (InterruptedException e)
{
throw new RuntimeException(e);
}
continue;
case VALID:
_state = State.CHANGING;
break;
default:
throw new IllegalStateException();
}
break;
}
id = _sessionData.getId(); // grab the values as they are now
extendedId = getExtendedId();
}
String newId = _handler._sessionIdManager.renewSessionId(id, extendedId, request);
try (AutoLock l = _lock.lock())
{
switch (_state)
{
case CHANGING:
if (id.equals(newId))
throw new IllegalStateException("Unable to change session id");
// this shouldn't be necessary to do here EXCEPT that when a
// null session cache is
// used, a new Session object will be created during the
// call to renew, so this
// Session object will not have been modified.
_sessionData.setId(newId);
setExtendedId(_handler._sessionIdManager.getExtendedId(newId, request));
setIdChanged(true);
_state = State.VALID;
_stateChangeCompleted.signalAll();
break;
case INVALID:
case INVALIDATING:
throw new IllegalStateException("Session invalid");
default:
throw new IllegalStateException();
}
}
}
/**
* Called by users to invalidate a session, or called by the access method
* as a request enters the session if the session has expired, or called by
* manager as a result of scavenger expiring session
*
* @see javax.servlet.http.HttpSession#invalidate()
*/
@Override
public void invalidate()
{
if (_handler == null)
throw new IllegalStateException("No session manager for session " + _sessionData.getId());
boolean result = beginInvalidate();
try
{
// if the session was not already invalid, or in process of being
// invalidated, do invalidate
if (result)
{
try
{
// do the invalidation
_handler.callSessionDestroyedListeners(this);
}
catch (Exception e)
{
LOG.warn("Error during Session destroy listener", e);
}
finally
{
// call the attribute removed listeners and finally mark it
// as invalid
finishInvalidate();
// tell id mgr to remove sessions with same id from all contexts
_handler.getSessionIdManager().invalidateAll(_sessionData.getId());
}
}
}
catch (Exception e)
{
LOG.warn("Unable to invalidate Session {}", this, e);
}
}
/**
* Grab the lock on the session
*
* @return the lock
*/
public AutoLock lock()
{
return _lock.lock();
}
/**
* @return true if the session is not already invalid or being invalidated.
*/
protected boolean beginInvalidate()
{
boolean result = false;
try (AutoLock l = _lock.lock())
{
while (true)
{
switch (_state)
{
case INVALID:
{
throw new IllegalStateException(); // spec does not
// allow invalidate
// of already invalid
// session
}
case INVALIDATING:
{
if (LOG.isDebugEnabled())
LOG.debug("Session {} already being invalidated", _sessionData.getId());
break;
}
case CHANGING:
{
try
{
if (LOG.isDebugEnabled())
LOG.debug("Session {} waiting for id change to complete", _sessionData.getId());
_stateChangeCompleted.await();
}
catch (InterruptedException e)
{
throw new RuntimeException(e);
}
continue;
}
case VALID:
{
// only first change from valid to invalidating should
// be actionable
result = true;
_state = State.INVALIDATING;
break;
}
default:
throw new IllegalStateException();
}
break;
}
}
return result;
}
/**
* Call HttpSessionAttributeListeners as part of invalidating a Session.
*
* @throws IllegalStateException if no session manager can be find
*/
protected void finishInvalidate() throws IllegalStateException
{
try (AutoLock l = _lock.lock())
{
try
{
if (LOG.isDebugEnabled())
LOG.debug("invalidate {}", _sessionData.getId());
if (_state == State.VALID || _state == State.INVALIDATING)
{
Set<String> keys = null;
do
{
keys = _sessionData.getKeys();
for (String key : keys)
{
Object old = _sessionData.setAttribute(key, null);
// if same as remove attribute but attribute was
// already removed, no change
if (old == null)
continue;
callSessionAttributeListeners(key, null, old);
}
}
while (!keys.isEmpty());
}
}
finally
{
// mark as invalid
_state = State.INVALID;
_handler.recordSessionTime(this);
_stateChangeCompleted.signalAll();
}
}
}
@Override
public boolean isNew() throws IllegalStateException
{
try (AutoLock l = _lock.lock())