View Javadoc

1   /*
2    * $Id: SessionMap.java 724839 2008-12-09 19:19:19Z nilsga $
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                             Map.Entry<K, V> entry = (Map.Entry<K, V>) obj;
121 
122                             return ((key == null) ? (entry.getKey() == null) : key.equals(entry.getKey())) && ((value == null) ? (entry.getValue() == null) : value.equals(entry.getValue()));
123                         }
124 
125                         public int hashCode() {
126                             return ((key == null) ? 0 : key.hashCode()) ^ ((value == null) ? 0 : value.hashCode());
127                         }
128 
129                         public K getKey() {
130                             return (K) key;
131                         }
132 
133                         public V getValue() {
134                             return (V) value;
135                         }
136 
137                         public V setValue(Object obj) {
138                             session.setAttribute(key, obj);
139 
140                             return (V) value;
141                         }
142                     });
143                 }
144             }
145         }
146 
147         return entries;
148     }
149 
150     /***
151      * Returns the session attribute associated with the given key or <tt>null</tt> if it doesn't exist.
152      *
153      * @param key the name of the session attribute.
154      * @return the session attribute or <tt>null</tt> if it doesn't exist.
155      */
156     public V get(Object key) {
157         if (session == null) {
158             return null;
159         }
160 
161         synchronized (session) {
162             return (V) session.getAttribute(key.toString());
163         }
164     }
165 
166     /***
167      * Saves an attribute in the session.
168      *
169      * @param key   the name of the session attribute.
170      * @param value the value to set.
171      * @return the object that was just set.
172      */
173     public V put(K key, V value) {
174         synchronized (this) {
175             if (session == null) {
176                 session = request.getSession(true);
177             }
178         }
179 
180         synchronized (session) {
181             entries = null;
182             session.setAttribute(key.toString(), value);
183 
184             return get(key);
185         }
186     }
187 
188     /***
189      * Removes the specified session attribute.
190      *
191      * @param key the name of the attribute to remove.
192      * @return the value that was removed or <tt>null</tt> if the value was not found (and hence, not removed).
193      */
194     public V remove(Object key) {
195         if (session == null) {
196             return null;
197         }
198 
199         synchronized (session) {
200             entries = null;
201 
202             V value = get(key);
203             session.removeAttribute(key.toString());
204 
205             return value;
206         }
207     }
208 
209     
210     /***
211      * Checks if the specified session attribute with the given key exists.
212      *
213      * @param key the name of the session attribute.
214      * @return <tt>true</tt> if the session attribute exits or <tt>false</tt> if it doesn't exist.
215      */
216     public boolean containsKey(Object key) {
217         if (session == null) {
218             return false;
219         }
220 
221         synchronized (session) {
222             return (session.getAttribute(key.toString()) != null);
223         }
224     }
225 }