KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > jcorporate > expresso > core > controller > session > HTTPPersistentSession


1 /* ====================================================================
2  * The Jcorporate Apache Style Software License, Version 1.2 05-07-2002
3  *
4  * Copyright (c) 1995-2002 Jcorporate Ltd. All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  *
10  * 1. Redistributions of source code must retain the above copyright
11  * notice, this list of conditions and the following disclaimer.
12  *
13  * 2. Redistributions in binary form must reproduce the above copyright
14  * notice, this list of conditions and the following disclaimer in
15  * the documentation and/or other materials provided with the
16  * distribution.
17  *
18  * 3. The end-user documentation included with the redistribution,
19  * if any, must include the following acknowledgment:
20  * "This product includes software developed by Jcorporate Ltd.
21  * (http://www.jcorporate.com/)."
22  * Alternately, this acknowledgment may appear in the software itself,
23  * if and wherever such third-party acknowledgments normally appear.
24  *
25  * 4. "Jcorporate" and product names such as "Expresso" must
26  * not be used to endorse or promote products derived from this
27  * software without prior written permission. For written permission,
28  * please contact info@jcorporate.com.
29  *
30  * 5. Products derived from this software may not be called "Expresso",
31  * or other Jcorporate product names; nor may "Expresso" or other
32  * Jcorporate product names appear in their name, without prior
33  * written permission of Jcorporate Ltd.
34  *
35  * 6. No product derived from this software may compete in the same
36  * market space, i.e. framework, without prior written permission
37  * of Jcorporate Ltd. For written permission, please contact
38  * partners@jcorporate.com.
39  *
40  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
41  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
42  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
43  * DISCLAIMED. IN NO EVENT SHALL JCORPORATE LTD OR ITS CONTRIBUTORS
44  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
45  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
46  * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
47  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
48  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
49  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
50  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
51  * SUCH DAMAGE.
52  * ====================================================================
53  *
54  * This software consists of voluntary contributions made by many
55  * individuals on behalf of the Jcorporate Ltd. Contributions back
56  * to the project(s) are encouraged when you make modifications.
57  * Please send them to support@jcorporate.com. For more information
58  * on Jcorporate Ltd. and its products, please see
59  * <http://www.jcorporate.com/>.
60  *
61  * Portions of this software are based upon other open source
62  * products and are subject to their respective licenses.
63  */

64 package com.jcorporate.expresso.core.controller.session;
65
66 import com.jcorporate.expresso.core.jsdkapi.GenericSession;
67 import com.jcorporate.expresso.core.misc.CookieUtil;
68 import com.jcorporate.expresso.core.misc.SerializableString;
69 import com.jcorporate.expresso.core.misc.StringUtil;
70 import com.jcorporate.expresso.kernel.exception.ChainedException;
71 import org.apache.log4j.Logger;
72
73 import javax.servlet.ServletException JavaDoc;
74 import javax.servlet.http.Cookie JavaDoc;
75 import javax.servlet.http.HttpServletRequest JavaDoc;
76 import javax.servlet.http.HttpServletResponse JavaDoc;
77 import java.io.Serializable JavaDoc;
78 import java.util.Enumeration JavaDoc;
79
80
81 /**
82  * A <code>HTTPPersistentSession</code> is simply a place to stash some values
83  * between states of a controller object. Different environments may employ
84  * different ways of doing this - the simplest being this one, where a
85  * hashtable does all the required work.
86  * </p>
87  * <p/>
88  * A servlet environment must use <code>HTTPPersistentSession</code>, which
89  * stores it's values in the HTTPSession for storage from one invokation to
90  * the next.</p>
91  * <p>If you are inside a controller environment, then call ControllerRequest.getSession()
92  * to get a <code>PersistentSession</code> object, and do not install this class
93  * directly. See the PersistentSession javadoc documentation for an example
94  * usage of this class</p>
95  *
96  * @author Michael Nash
97  * @see com.jcorporate.expresso.core.controller.session.PersistentSession
98  * @since Expresso 4.0
99  */

100 public class HTTPPersistentSession implements PersistentSession {
101     /**
102      * The log object
103      */

104     private static final transient Logger log = Logger.getLogger(HTTPPersistentSession.class);
105
106     /**
107      * The servlet request
108      */

109     private transient HttpServletRequest JavaDoc request = null;
110
111     /**
112      * The servlet response object.
113      */

114     private transient HttpServletResponse JavaDoc response = null;
115
116     /**
117      * Creates new HTTPPersistentSession
118      */

119     public HTTPPersistentSession() {
120     }
121
122     /**
123      * Creates new HTTPPersistentSession and set the request object in one step
124      *
125      * @param req a <code>HttpServletRequest</code> object
126      * @param res a <code>HttpServletResponse</code> object
127      */

128     public HTTPPersistentSession(HttpServletRequest JavaDoc req, HttpServletResponse JavaDoc res) {
129         this();
130         setRequest(req);
131         setResponse(res);
132     }
133
134     /**
135      * Sets an attribute on the Servlet request
136      *
137      * @param attribName The name of the object you wish to set.
138      * @param attribValue the object you want to set.
139      * @throws IllegalArgumentException if the current object's Request object
140      * has not be set yet.
141      */

142     public void setAttribute(String JavaDoc attribName, Object JavaDoc attribValue) {
143         if (request == null) {
144             throw new IllegalArgumentException JavaDoc("HTTPPersistentSession not initialized correctly");
145         }
146
147         request.setAttribute(attribName, attribValue);
148     }
149
150     /**
151      * Retrieves the object from the request context.
152      *
153      * @param attribName the name of the object to retrieve
154      * @return the object or null if it doesn't exist.
155      */

156     public Object JavaDoc getAttribute(String JavaDoc attribName) {
157         if (request == null) {
158             return null;
159         }
160
161         return request.getAttribute(attribName);
162     }
163
164     /**
165      * Retrieves all attribute names in the request context.
166      *
167      * @return java.util.Enumeration
168      */

169     public Enumeration JavaDoc getAttributeNames() {
170         return request.getAttributeNames();
171     }
172
173     /**
174      * Sets a cookie in the client's system. Note that this cookie is
175      * encrypted with the password you set up in your
176      * <code>expresso-config.xml</code> file.
177      *
178      * @param attribName the name of the attribute to
179      * @param attribValue the value of the attribute to set.
180      * @throws IllegalArgumentException If the cookie encryption fails for
181      * some reason. The actual chained exception is logged.
182      */

183     public void setClientAttribute(String JavaDoc attribName, String JavaDoc attribValue) {
184         Cookie JavaDoc c1;
185
186         try {
187             if ((attribValue != null) && (attribValue.length() > 0)) {
188                 c1 = new Cookie JavaDoc(attribName, CookieUtil.cookieEncode(attribValue));
189                 c1.setMaxAge(2592000); /* 30 days */
190             } else {
191                 c1 = new Cookie JavaDoc(attribName, "");
192                 c1.setMaxAge(0);
193             }
194
195             c1.setPath("/");
196             response.addCookie(c1);
197         } catch (ChainedException ce) {
198             log.error(ce);
199             throw new IllegalArgumentException JavaDoc(ce.getMessage());
200         }
201     }
202     /* setClientAttrib(String, String) */
203
204     /**
205      * Retrieves a value of a cookie set on the client's system. It also
206      * decrypts the value with the password you set up in your
207      * <code>expresso-config.xml</code> file.
208      *
209      * @param attribName the name of the cookie to retrieve
210      * @return java.lang.String the value of the cookie or null if the cookie
211      * doesn't exist.
212      * @throws IllegalArgumentException If there's a problem decrypting the
213      * cookie. The full error is logged. [Especially important for chained
214      * exceptions]
215      */

216     public String JavaDoc getClientAttribute(String JavaDoc attribName) {
217         Cookie JavaDoc[] cookies = request.getCookies();
218
219         try {
220             if (cookies != null) {
221                 for (int i = 0; i < cookies.length; i++) {
222                     String JavaDoc name = StringUtil.notNull(cookies[i].getName());
223                     String JavaDoc value = StringUtil.notNull(cookies[i].getValue());
224
225                     if (name.equalsIgnoreCase(attribName)) {
226                         return CookieUtil.cookieDecode(value);
227                     }
228                 }
229                 /* for each cookie */
230             }
231             /* if there are any cookies */
232         } catch (Exception JavaDoc ce) {
233             log.error(ce);
234             throw new IllegalArgumentException JavaDoc(ce.getMessage());
235         }
236
237         return null;
238     }
239
240     /**
241      * Retrieves all attribute names from the session context.
242      *
243      * @return java.util.Enumeration
244      */

245     public Enumeration JavaDoc getPeristentAttributeNames() {
246         try {
247             return GenericSession.getAttributeNames(request);
248         } catch (ServletException JavaDoc se) {
249             log.error(se);
250         }
251
252         return null;
253     }
254
255     /**
256      * Saves an attribute to the actual session, rather than simply the
257      * response. Use this for storing objects between requests, but only use
258      * it with care since the extra memory used may bog down systems under
259      * high load.
260      *
261      * @param attribName the name of the attribute to set
262      * @param attribValue a <code>Serializable</code> java object.
263      * @throws IllegalArgumentException If there is an error storing the cookie
264      * to the session.
265      * @see java.io.Serializable
266      */

267     public void setPersistentAttribute(String JavaDoc attribName, Object JavaDoc attribValue) {
268         if (attribValue == null) {
269             throw new IllegalArgumentException JavaDoc("Value must not be null");
270         }
271
272         if (attribValue instanceof String JavaDoc) {
273             attribValue = new SerializableString((String JavaDoc) attribValue);
274         }
275
276         if (attribValue instanceof Serializable JavaDoc) {
277             try {
278                 GenericSession.setAttribute(request, attribName,
279                         (Serializable JavaDoc) attribValue);
280             } catch (ServletException JavaDoc se) {
281                 log.error(se);
282                 throw new IllegalArgumentException JavaDoc("Unable to store value in session:" + se.getMessage());
283             }
284         } else {
285             throw new IllegalArgumentException JavaDoc("Attribute value object must be serializable. '" +
286                     attribValue.getClass().getName() + "' is not serializable.");
287         }
288     }
289
290     /**
291      * Retrieves the object from the session context.
292      *
293      * @param attribName the name of the object to retrieve
294      * @return the object or null if it doesn't exist.
295      */

296     public Object JavaDoc getPersistentAttribute(String JavaDoc attribName) {
297         try {
298             return GenericSession.getAttribute(request, attribName);
299         } catch (ServletException JavaDoc se) {
300             log.error(se);
301
302             return null;
303         }
304     }
305
306     /**
307      * Set the request object so we can get to the session.
308      *
309      * @param req An HttpServletRequest object.
310      */

311     public void setRequest(HttpServletRequest JavaDoc req) {
312         request = req;
313     }
314
315     /**
316      * Set the response object so we can get to all the http objects we need.
317      *
318      * @param res A HttpServletResponse object
319      */

320     public void setResponse(HttpServletResponse JavaDoc res) {
321         response = res;
322     }
323
324     /**
325      * Clear out the session. Invalidates the entire session.
326      */

327     public void invalidate() {
328         try {
329             GenericSession.invalidate(request);
330         } catch (ServletException JavaDoc ce) {
331             log.error(ce);
332         }
333
334         request = null;
335     }
336
337     /**
338      * Clears an attribute from the request context
339      *
340      * @param attribName the name of the attribute to remove.
341      */

342     public void removeAttribute(String JavaDoc attribName) {
343         request.removeAttribute(attribName);
344     }
345
346     /**
347      * Clears an attribute from the session context
348      *
349      * @param attribName the name of the attribute to remove.
350      */

351     public void removePersistentAttribute(String JavaDoc attribName) {
352         try {
353             GenericSession.removeAttribute(request, attribName);
354         } catch (ServletException JavaDoc se) {
355             log.error(se);
356         }
357     }
358 }
359
Popular Tags