KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > lutris > appserver > server > sessionEnhydra > BasicSession


1 /*
2  * Enhydra Java Application Server Project
3  *
4  * The contents of this file are subject to the Enhydra Public License
5  * Version 1.1 (the "License"); you may not use this file except in
6  * compliance with the License. You may obtain a copy of the License on
7  * the Enhydra web site ( http://www.enhydra.org/ ).
8  *
9  * Software distributed under the License is distributed on an "AS IS"
10  * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
11  * the License for the specific terms governing rights and limitations
12  * under the License.
13  *
14  * The Initial Developer of the Enhydra Application Server is Lutris
15  * Technologies, Inc. The Enhydra Application Server and portions created
16  * by Lutris Technologies, Inc. are Copyright Lutris Technologies, Inc.
17  * All Rights Reserved.
18  *
19  * Contributor(s):
20  *
21  * $Id: BasicSession.java,v 1.3 2005/03/24 12:19:15 slobodan Exp $
22  */

23
24 package com.lutris.appserver.server.sessionEnhydra;
25
26 import java.io.Serializable JavaDoc;
27 import java.util.Enumeration JavaDoc;
28 import java.util.Hashtable JavaDoc;
29 import java.util.Vector JavaDoc;
30
31 import javax.servlet.ServletContext JavaDoc;
32 import javax.servlet.http.HttpSession JavaDoc;
33 import javax.servlet.http.HttpSessionBindingEvent JavaDoc;
34 import javax.servlet.http.HttpSessionBindingListener JavaDoc;
35 import javax.servlet.http.HttpSessionContext JavaDoc;
36
37 import com.lutris.appserver.server.session.SessionData;
38 import com.lutris.appserver.server.session.SessionException;
39 import com.lutris.appserver.server.session.SessionManager;
40 import com.lutris.appserver.server.user.User;
41
42 /**
43  * The standard implementation of the StandardSession interface.
44  * The session reflects and instance of a client interacting
45  * with the application. A BasicSession maybe associated
46  * with a user or exist in a unauthenticated state. The
47  * session manager associated with a BasicSession object must be
48  * a StandardSessionManager or a derivation.
49  *
50  * @version $Revision: 1.3 $
51  * @author John Marco
52  * @author Shawn McMurdo
53  */

54 public class BasicSession implements StandardSession, HttpSession JavaDoc, Serializable JavaDoc{
55
56     // Intentionally transient
57
protected transient StandardSessionManager sessionManager = null;
58
59     protected User user = null;
60     private String JavaDoc sessionKey = null;
61     private long timeCreated; // Milliseconds.
62
private long timeLastUsed; // Milliseconds.
63
private long timeExpires; // Milliseconds.
64
private long maxIdleTime; // Milliseconds.
65
private long maxNoUserIdleTime; // Milliseconds.
66

67     /**
68      * The application specific data for this session.
69      */

70     public SessionData data;
71
72     // The number of references to this session.
73
private int refCount = 0;
74
75     /**
76      * Need the following constructor in order to serialize?
77      */

78     public BasicSession() {}
79
80     /**
81      * Construct a new session. Only called by
82      * <CODE>StandardSessionManager</CODE>.
83      *
84      * @param sessionManager
85      * The session manager that will manager this session.
86      * @param sessionKey
87      * The unique session key associated with the session.
88      */

89     protected BasicSession(StandardSessionManager sessionManager,
90                            String JavaDoc sessionKey) {
91         this(sessionManager, sessionKey, new SessionData());
92     }
93
94     /**
95      * Construct a new session. Only called by
96      * <CODE>StandardSessionManager</CODE>.
97      *
98      * @param sessionManager
99      * The session manager that will manager this session.
100      * @param sessionKey
101      * The unique session key associated with the session.
102      * @param sessionData
103      * The session data to associate with this session.
104      */

105     protected BasicSession(StandardSessionManager sessionManager,
106                            String JavaDoc sessionKey, SessionData sessionData) {
107         this.sessionManager = sessionManager;
108         this.sessionKey = sessionKey;
109         /*
110          * Set session information.
111          */

112         long now = System.currentTimeMillis();
113         timeCreated = now;
114         timeLastUsed = now;
115         long lifeTime = sessionManager.getMaxSessionLifeTime();
116         if (lifeTime > 0) {
117             // Convert timeExpires from delta seconds to an absolute
118
// millisecond-based date.
119
timeExpires = now + (lifeTime * 1000);
120         } else {
121             // Not using this feature.
122
timeExpires = 0;
123         }
124         maxIdleTime = sessionManager.getMaxSessionIdleTime() * 1000;
125         maxNoUserIdleTime = sessionManager.getMaxNoUserSessionIdleTime() * 1000;
126         this.data = sessionData;
127         initHttpSession();
128     }
129
130     /**
131      * Set the "last used" timestamp to the current time, resetting the
132      * idle period.
133      */

134     public void touch() {
135         timeLastUsed = System.currentTimeMillis();
136     }
137
138     /**
139      * Obtain the user associated with this session.
140      *
141      * @return The user object or <CODE>null</CODE> if the
142      * session is not logged in.
143      */

144     public User getUser() {
145         return user;
146     }
147
148     /**
149      * Set the user associated with this session. This will register the
150      * user with the <CODE>SessionManager</CODE>. <P>
151      *
152      * If it is neccessary to prevent a user from logging on multiple times,
153      * this can be accomplished by synchronizing on the
154      * <CODE>Sessionmanager</CODE> object and enquiring about the number of
155      * users associated with a session. It is then possible to delete other
156      * sessions before adding a new session.
157      *
158      * @param user
159      * the user object to associate with the session.
160      * @exception SessionException
161      * if the user cannot be associated with the session.
162      */

163     public void setUser(User sessionUser) throws SessionException {
164         if (user != null) {
165             sessionManager.unregisterUser(this);
166         }
167         user = sessionUser;
168         if (sessionUser != null) {
169             sessionManager.registerUser(this);
170         }
171     }
172
173     /**
174      * Remove the user association with this session. This will unregister the
175      * user with the <CODE>SessionManager</CODE>.
176      *
177      * @exception SessionException
178      * if an error occurs.
179      */

180     public void clearUser() throws SessionException {
181         if (user != null) {
182             sessionManager.unregisterUser(this);
183             user = null;
184         }
185     }
186
187     /**
188      * Obtain the unique key associated with this session.
189      *
190      * @return A String containing the key for this session.
191      */

192     public String JavaDoc getSessionKey() {
193         return sessionKey;
194     }
195
196     /**
197      * Obtain the session manager associated with this session.
198      *
199      * @return The session manager object.
200      */

201     public SessionManager getSessionManager() {
202         return sessionManager;
203     }
204
205     /**
206      * Obtain the application specific data for this session.
207      *
208      * @return A SessionData object containing application specific
209      * data for this session.
210      */

211     public SessionData getSessionData() {
212         return data;
213     }
214
215     /**
216      * Obtain the creation time for this object. The time is in
217      * milliseconds since Midnight, Jan 1, 1970 (epoch).
218      *
219      * @return The creation time since epoch for this object.
220      */

221     public long getTimeCreated() {
222         return timeCreated;
223     }
224
225     /**
226      * Obtain the time of last use for this object. The time is in
227      * milliseconds since Midnight, Jan 1, 1970 (epoch).
228      *
229      * @return The time of last use since epoch for this object.
230      */

231     public long getTimeLastUsed() {
232         return timeLastUsed;
233     }
234
235     /**
236      * Obtain the time of expiry for this object. The time is in
237      * milliseconds since Midnight, Jan 1, 1970 (epoch).
238      * Returns zero (or negative) if there is no expiration date.
239      * Note: this is a maximum lifespan for the session, regardless of activity.
240      *
241      * @return The time of expiry since epoch for this object.
242      */

243     public long getTimeExpires() {
244         return timeExpires;
245     }
246
247     /**
248      * Set the time of expiry for this object. The time is in
249      * milliseconds since Midnight, Jan 1, 1970 (epoch).
250      * Set this value to zero (or less) to indicate that the session does not
251      * have a maximum age.
252      *
253      * @param timeLastUsed The time of expiry since epoch.
254      */

255     public void setTimeExpires(long timeExpires) {
256         this.timeExpires = timeExpires;
257     }
258
259     /**
260      * Obtain the maximum idle time for this object. Zero (or negative)
261      * indicates that sessions may be idle indefinetly.
262      *
263      * @return The maximum number of milliseconds this session
264      * may be idle.
265      */

266     public long getMaxIdleTime() {
267         return maxIdleTime;
268     }
269
270     /**
271      * Set the maximum idle time for this object. Set this to zero
272      * (or negative) to disable idle checking.
273      *
274      * @param maxIdleTime The maximum number of milliseconds this
275      * session may be idle, or zero (or negative) to allow sessions to be idle
276      * indefinetly.
277      */

278     public void setMaxIdleTime(long maxIdleTime) {
279         this.maxIdleTime = maxIdleTime;
280     }
281
282     /**
283      * Obtain the maximum idle time when a <CODE>User</CODE> object
284      * is not associated with the session. Zero (or negative) indicates that
285      * sessions may be idle indefinetly.
286      *
287      * @return The maximum number of milliseconds this session
288      * may be idle.
289      */

290     public long getMaxNoUserIdleTime() {
291         return maxNoUserIdleTime;
292     }
293
294     /**
295      * set the maximum idle time when a <CODE>User</CODE> object
296      * is not associated with the session. Set this to zero (or negative) to
297      * disable idle checking.
298      *
299      * @param maxIdleTime The maximum number of milliseconds this
300      * session may be idle.
301      */

302     public void setMaxNoUserIdleTime(long maxIdleTime) {
303         this.maxNoUserIdleTime = maxIdleTime;
304     }
305
306     /**
307      * Returns true if the session is new. A session is new if it has
308      * been created but a client cookie was never used to reference it.
309      * In other words, the cookie associated with the session was
310      * never submitted by a client.
311      *
312      * @return true if the session is new.
313      */

314     public boolean isNew() {
315         checkValid();
316         return (timeCreated == timeLastUsed);
317     }
318
319     /**
320      * Returns the number of active references to this object.
321      *
322      * @return
323      * the number of references.
324      */

325     public int getRefCount() {
326         return refCount;
327     }
328
329     /**
330      * Returns the number of active references to this object.
331      *
332      * @return
333      * the number of references.
334      */

335     public int incrementRefCount() {
336         refCount++;
337         return refCount;
338     }
339
340     /**
341      * Returns the number of active references to this object.
342      *
343      * @return
344      * the number of references.
345      */

346     public int decrementRefCount() {
347         if (refCount > 0) {
348             refCount--;
349         }
350         return refCount;
351     }
352
353     /**
354      * Prints a string representation of this object.
355      *
356      * @return
357      * the string representation.
358      */

359     public String JavaDoc toString() {
360         StringBuffer JavaDoc str = new StringBuffer JavaDoc();
361         str.append("{");
362         str.append("sessionKey=" + sessionKey);
363         str.append(", ");
364         if (user != null) {
365             str.append("user=" + user.getName());
366         } else {
367             str.append("user=" + user);
368         }
369         str.append(", ");
370         str.append("timeCreated=" + timeCreated);
371         str.append(", ");
372         str.append("timeLastUsed=" + timeLastUsed);
373         str.append(", ");
374         str.append("timeExpires=" + timeExpires);
375         str.append(", ");
376         str.append("maxIdleTime=" + maxIdleTime);
377         str.append(", ");
378         str.append("maxNoUserIdleTime=" + maxNoUserIdleTime);
379         str.append(", ");
380         str.append("sessionData=" + data);
381         str.append("}");
382         return str.toString();
383     }
384
385
386
387    public HttpSession JavaDoc getHttpSession() {
388      // should be a ref to another object
389
return this;
390    }
391
392
393
394
395    // The HttpSession interface implementation
396
//
397

398     Hashtable JavaDoc attributes;
399     boolean valid;
400     //private Context context; //DACHA
401

402     private void initHttpSession() {
403         attributes = new Hashtable JavaDoc();
404         valid = true;
405        // context = null;//DACHA
406
}
407 /* DACHA
408     public void setContext(Context context) {
409         this.context = context;
410     }
411 */

412     public long getCreationTime() {
413         checkValid();
414         return getTimeCreated();
415     }
416
417     public String JavaDoc getId() {
418         return getSessionKey();
419     }
420
421     public long getLastAccessedTime() {
422         checkValid();
423         return getTimeLastUsed();
424     }
425
426     public void setMaxInactiveInterval(int interval) {
427         checkValid();
428         // convert from seconds to miliseconds
429
setMaxIdleTime(interval*1000);
430     }
431
432
433     public int getMaxInactiveInterval() {
434         checkValid();
435         // convert from miliseconds to seconds
436
return (int)(getMaxIdleTime()/1000);
437     }
438
439
440     public HttpSessionContext JavaDoc getSessionContext() {
441         checkValid();
442     //return new SessionContextImpl(); //DACHA
443
return null;
444     }
445
446     public ServletContext JavaDoc getServletContext(){
447         //FIXME to support servlet 2.3
448
return null;
449     }
450
451     public Object JavaDoc getAttribute(String JavaDoc name) {
452         checkValid();
453         Object JavaDoc o = attributes.get(name);
454         return attributes.get(name);
455     }
456
457     public Object JavaDoc getValue(String JavaDoc name) {
458         checkValid();
459         return getAttribute(name);
460     }
461
462
463     public Enumeration JavaDoc getAttributeNames() {
464         checkValid();
465         Hashtable JavaDoc attributesClone = (Hashtable JavaDoc)attributes.clone();
466         return (Enumeration JavaDoc)attributesClone.keys();
467     }
468
469     public String JavaDoc[] getValueNames() {
470         checkValid();
471         Enumeration JavaDoc e = getAttributeNames();
472         Vector JavaDoc names = new Vector JavaDoc();
473         while (e.hasMoreElements()) {
474             names.addElement(e.nextElement());
475         }
476         String JavaDoc[] valueNames = new String JavaDoc[names.size()];
477         names.copyInto(valueNames);
478         return valueNames;
479     }
480
481     public void setAttribute(String JavaDoc name, Object JavaDoc value) {
482         checkValid();
483     if (name == null) {
484             String JavaDoc msg = "null value";
485         throw new IllegalArgumentException JavaDoc(msg);
486     }
487         removeAttribute(name);
488     if (value != null && value instanceof HttpSessionBindingListener JavaDoc) {
489         HttpSessionBindingEvent JavaDoc e = new HttpSessionBindingEvent JavaDoc(this, name);
490         ((HttpSessionBindingListener JavaDoc)value).valueBound(e);
491     }
492         attributes.put(name,value);
493     }
494
495     public void putValue(String JavaDoc name, Object JavaDoc value) {
496         checkValid();
497         setAttribute(name, value);
498     }
499
500     public void removeAttribute(String JavaDoc name) {
501         checkValid();
502     if (name == null) {
503             String JavaDoc msg = "null value";
504         throw new IllegalArgumentException JavaDoc(msg);
505     }
506
507     Object JavaDoc o = attributes.get(name);
508     if (o instanceof HttpSessionBindingListener JavaDoc) {
509         HttpSessionBindingEvent JavaDoc e = new HttpSessionBindingEvent JavaDoc(this,name);
510         ((HttpSessionBindingListener JavaDoc)o).valueUnbound(e);
511     }
512         attributes.remove(name);
513     }
514
515     public void removeValue(String JavaDoc name) {
516         checkValid();
517         removeAttribute(name);
518     }
519
520     public void invalidate() {
521         checkValid();
522     Enumeration JavaDoc enumeration = attributes.keys();
523     while (enumeration.hasMoreElements()) {
524         String JavaDoc name = (String JavaDoc)enumeration.nextElement();
525         removeAttribute(name);
526     }
527 // valid = false;
528
try {
529             sessionManager.deleteSession(this);
530         }
531         catch (SessionException se) {
532             se.printStackTrace();
533         }
534 // 2003/01/23 Session is nvalid Error fixed
535
valid = false;
536     }
537
538
539     private void checkValid() {
540       if (! valid) {
541         String JavaDoc msg = "Session is invalid.";
542     throw new IllegalStateException JavaDoc(msg);
543       }
544
545     }
546
547
548
549 }
550
551
Popular Tags