View Javadoc

1   /*
2    * $Id: SessionMap.java 768855 2009-04-27 02:09:35Z wesw $
3    *
4    * Licensed to the Apache Software Foundation (ASF) under one
5    * or more contributor license agreements.  See the NOTICE file
6    * distributed with this work for additional information
7    * regarding copyright ownership.  The ASF licenses this file
8    * to you under the Apache License, Version 2.0 (the
9    * "License"); you may not use this file except in compliance
10   * with the License.  You may obtain a copy of the License at
11   *
12   *  http://www.apache.org/licenses/LICENSE-2.0
13   *
14   * Unless required by applicable law or agreed to in writing,
15   * software distributed under the License is distributed on an
16   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
17   * KIND, either express or implied.  See the License for the
18   * specific language governing permissions and limitations
19   * under the License.
20   */
21  
22  package org.apache.struts2.dispatcher;
23  
24  import java.io.Serializable;
25  import java.util.AbstractMap;
26  import java.util.Collections;
27  import java.util.Enumeration;
28  import java.util.HashSet;
29  import java.util.Map;
30  import java.util.Set;
31  
32  import javax.servlet.http.HttpServletRequest;
33  import javax.servlet.http.HttpSession;
34  
35  
36  /***
37   * A simple implementation of the {@link java.util.Map} interface to handle a collection of HTTP session
38   * attributes. The {@link #entrySet()} method enumerates over all session attributes and creates a Set of entries.
39   * Note, this will occur lazily - only when the entry set is asked for.
40   *
41   */
42  public class SessionMap<K, V> extends AbstractMap<K,V> implements Serializable {
43  
44      private static final long serialVersionUID = 4678843241638046854L;
45  
46      protected HttpSession session;
47      protected Set<Map.Entry<K,V>> entries;
48      protected HttpServletRequest request;
49  
50  
51      /***
52       * Creates a new session map given a http servlet request. Note, ths enumeration of request
53       * attributes will occur when the map entries are asked for.
54       *
55       * @param request the http servlet request object.
56       */
57      public SessionMap(HttpServletRequest request) {
58          // note, holding on to this request and relying on lazy session initalization will not work
59          // if you are running your action invocation in a background task, such as using the
60          // "execAndWait" interceptor
61          this.request = request;
62          this.session = request.getSession(false);
63      }
64  
65      /***
66       * Invalidate the http session.
67       */
68      public void invalidate() {
69          if (session == null) {
70              return;
71          }
72  
73          synchronized (session) {
74              session.invalidate();
75              session = null;
76              entries = null;
77          }
78      }
79  
80      /***
81       * Removes all attributes from the session as well as clears entries in this
82       * map.
83       */
84      public void clear() {
85          if (session == null ) {
86              return;
87          }
88  
89          synchronized (session) {
90              entries = null;
91              Enumeration<String> attributeNamesEnum = session.getAttributeNames();
92              while(attributeNamesEnum.hasMoreElements()) {
93                  session.removeAttribute(attributeNamesEnum.nextElement());
94              }
95          }
96  
97      }
98  
99      /***
100      * Returns a Set of attributes from the http session.
101      *
102      * @return a Set of attributes from the http session.
103      */
104     public Set<java.util.Map.Entry<K,V>> entrySet() {
105         if (session == null) {
106             return Collections.emptySet();
107         }
108 
109         synchronized (session) {
110             if (entries == null) {
111                 entries = new HashSet<Map.Entry<K,V>>();
112 
113                 Enumeration<? extends Object> enumeration = session.getAttributeNames();
114 
115                 while (enumeration.hasMoreElements()) {
116                     final String key = enumeration.nextElement().toString();
117                     final Object value = session.getAttribute(key);
118                     entries.add(new Map.Entry<K,V>() {
119                         public boolean equals(Object obj) {
120                             if (!(obj instanceof Map.Entry)) {
121                               return false;
122                             }
123                             Map.Entry<K, V> entry = (Map.Entry<K, V>) obj;
124 
125                             return ((key == null) ? (entry.getKey() == null) : key.equals(entry.getKey())) && ((value == null) ? (entry.getValue() == null) : value.equals(entry.getValue()));
126                         }
127 
128                         public int hashCode() {
129                             return ((key == null) ? 0 : key.hashCode()) ^ ((value == null) ? 0 : value.hashCode());
130                         }
131 
132                         public K getKey() {
133                             return (K) key;
134                         }
135 
136                         public V getValue() {
137                             return (V) value;
138                         }
139 
140                         public V setValue(Object obj) {
141                             session.setAttribute(key, obj);
142 
143                             return (V) value;
144                         }
145                     });
146                 }
147             }
148         }
149 
150         return entries;
151     }
152 
153     /***
154      * Returns the session attribute associated with the given key or <tt>null</tt> if it doesn't exist.
155      *
156      * @param key the name of the session attribute.
157      * @return the session attribute or <tt>null</tt> if it doesn't exist.
158      */
159     public V get(Object key) {
160         if (session == null) {
161             return null;
162         }
163 
164         synchronized (session) {
165             return (V) session.getAttribute(key.toString());
166         }
167     }
168 
169     /***
170      * Saves an attribute in the session.
171      *
172      * @param key   the name of the session attribute.
173      * @param value the value to set.
174      * @return the object that was just set.
175      */
176     public V put(K key, V value) {
177         synchronized (this) {
178             if (session == null) {
179                 session = request.getSession(true);
180             }
181         }
182 
183         synchronized (session) {
184             entries = null;
185             session.setAttribute(key.toString(), value);
186 
187             return get(key);
188         }
189     }
190 
191     /***
192      * Removes the specified session attribute.
193      *
194      * @param key the name of the attribute to remove.
195      * @return the value that was removed or <tt>null</tt> if the value was not found (and hence, not removed).
196      */
197     public V remove(Object key) {
198         if (session == null) {
199             return null;
200         }
201 
202         synchronized (session) {
203             entries = null;
204 
205             V value = get(key);
206             session.removeAttribute(key.toString());
207 
208             return value;
209         }
210     }
211 
212     
213     /***
214      * Checks if the specified session attribute with the given key exists.
215      *
216      * @param key the name of the session attribute.
217      * @return <tt>true</tt> if the session attribute exits or <tt>false</tt> if it doesn't exist.
218      */
219     public boolean containsKey(Object key) {
220         if (session == null) {
221             return false;
222         }
223 
224         synchronized (session) {
225             return (session.getAttribute(key.toString()) != null);
226         }
227     }
228 }