01: package org.wings.util;
02:
03: import org.wings.session.SessionManager;
04:
05: /**
06: * A helper class for storing session local variables similar to {@link ThreadLocal} for thread local variables.
07: */
08: public class SessionLocal<T> {
09:
10: private final String propertyName;
11:
12: public SessionLocal() {
13: this .propertyName = getClass().getName() + "."
14: + System.identityHashCode(this );
15: }
16:
17: /**
18: * use a wrapper for the value so that it is possible
19: * to get and set a null value, and also to determine
20: * whether the property has been initialized
21: * for the current session
22: */
23: private static class ValueWrapper<T> {
24: T value;
25: }
26:
27: /**
28: * return the current value of this variable from the session
29: *
30: * @return The current value or the result of {@link #initialValue()} if called for the first time.
31: */
32: public T get() {
33: ValueWrapper<T> valueWrapper = (ValueWrapper<T>) SessionManager
34: .getSession().getProperty(this .propertyName);
35: /*
36: * null means that the property is being used for the first time this session,
37: * initialize the value, which may be null.
38: */
39: if (valueWrapper == null) {
40: T value = initialValue();
41: set(value);
42: return value;
43: } else {
44: return valueWrapper.value;
45: }
46: }
47:
48: /**
49: * override this method to get the initial value for a new session
50: *
51: * @return The stored value
52: */
53: protected T initialValue() {
54: return null;
55: }
56:
57: /**
58: * Set the value. the value which is set may be null,
59: * but the object set is never null because it is wrapped.
60: *
61: * @param value Value. <code>null</code> is also a valid value.
62: */
63: public void set(T value) {
64: ValueWrapper<T> valueWrapper = new ValueWrapper<T>();
65: valueWrapper.value = value;
66: SessionManager.getSession().setProperty(this .propertyName,
67: valueWrapper);
68: }
69:
70: /**
71: * remove the value,
72: * if get is called, the value will be reinitialized
73: */
74: public void remove() {
75: SessionManager.getSession()
76: .setProperty(this.propertyName, null);
77: }
78:
79: }
|