KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > rift > coad > lib > security > user > UserSessionManager


1 /*
2  * CoadunationLib: The coaduntion implementation library.
3  * Copyright (C) 2006 Rift IT Contracting
4  *
5  * This library is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Lesser General Public
7  * License as published by the Free Software Foundation; either
8  * version 2.1 of the License, or (at your option) any later version.
9  *
10  * This library is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13  * Lesser General Public License for more details.
14  *
15  * You should have received a copy of the GNU Lesser General Public
16  * License along with this library; if not, write to the Free Software
17  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
18  *
19  * UserSessionManager.java
20  *
21  * The user session manager is responsible for creating new session for users.
22  */

23
24 // the package
25
package com.rift.coad.lib.security.user;
26
27 // java
28
import java.util.Iterator JavaDoc;
29 import java.util.Map JavaDoc;
30 import java.util.HashMap JavaDoc;
31
32 // logging import
33
import org.apache.log4j.Logger;
34
35 // coadunation
36
import com.rift.coad.lib.configuration.Configuration;
37 import com.rift.coad.lib.configuration.ConfigurationFactory;
38 import com.rift.coad.lib.security.ThreadsPermissionContainer;
39 import com.rift.coad.lib.security.ThreadPermissionSession;
40 import com.rift.coad.lib.security.UserSession;
41 import com.rift.coad.lib.thread.ThreadStateMonitor;
42
43 /**
44  * The user session manager is responsible for creating new session for users.
45  *
46  * @author Brett Chaldecott
47  */

48 public class UserSessionManager {
49     
50     /**
51      * This object is responsible for maintaining the user session
52      */

53     public class UserSessionIndex {
54         // Private member variables
55
private Map JavaDoc sessionIdMap = new HashMap JavaDoc();
56         
57         
58         /**
59          * The default constructor of the user session index
60          */

61         public UserSessionIndex() {
62             
63         }
64         
65         
66         /**
67          * This method will add add a user session to the indexs appropriatly.
68          *
69          * @param userSession The reference to the user session object.
70          */

71         public synchronized void putUser(UserSession userSession) {
72             sessionIdMap.put(userSession.getSessionId(),userSession);
73         }
74         
75         
76         /**
77          * This method returns the user session object instance.
78          *
79          * @return The reference to the user session object.
80          * @param sessionId The id of the users session
81          * @exception UserException
82          */

83         public synchronized UserSession getSessionById(String JavaDoc sessionId)
84                 throws UserException {
85             try {
86                 if (!sessionIdMap.containsKey(sessionId)) {
87                     throw new UserException("No session exists for session id.");
88                 }
89                 UserSession userSession =
90                         (UserSession)sessionIdMap.get(sessionId);
91                 if (userSession.isExpired()) {
92                     sessionIdMap.remove(userSession.getSessionId());
93                     throw new UserException("No session exists for user.");
94                 }
95                 userSession.touch();
96                 return userSession;
97             } catch (SecurityException JavaDoc ex) {
98                 throw ex;
99             } catch (Exception JavaDoc ex) {
100                 throw new UserException("Failed to retrieve the user session : "
101                         + ex.getMessage(),ex);
102             }
103         }
104         
105         
106         /**
107          * This method removes a session identifed by a session id
108          *
109          * @param sessionId The id of the users session
110          */

111         public synchronized void removeSessionById(String JavaDoc sessionId) {
112             if (!sessionIdMap.containsKey(sessionId)) {
113                 return;
114             }
115             UserSession userSession =
116                     (UserSession)sessionIdMap.get(sessionId);
117             sessionIdMap.remove(userSession.getSessionId());
118         }
119     }
120     
121     
122     /**
123      * This is a thread that is responsible for cleaning up the old user
124      * sessions. It does not inhert from BasicThread because the environment
125      * has not been configured properly yet for a basic thread to be started.
126      */

127     public class TimeoutThread extends Thread JavaDoc
128     {
129         // the classes constants
130
private final static String JavaDoc DELAY = "session_timeout_delay";
131         private final static long DELAY_DEFAULT = 60 * 1000;
132         
133         // private member variables
134
private ThreadStateMonitor stateMonitor = null;
135         
136         /**
137          * The constructor of the timeout thread.
138          *
139          * @exception UserException
140          */

141         public TimeoutThread() throws UserException {
142             try {
143                 Configuration config = ConfigurationFactory.getInstance().
144                         getConfig(this.getClass());
145                 long delay = config.getLong(DELAY,DELAY_DEFAULT);
146                 stateMonitor = new ThreadStateMonitor(delay);
147             } catch (Exception JavaDoc ex) {
148                 log.error("Failed to init the timeout thread : " +
149                         ex.getMessage(),ex);
150                 throw new UserException("Failed to init the timeout thread : " +
151                         ex.getMessage(),ex);
152             }
153         }
154         
155         
156         /**
157          * This method runs through and removes sessions that have expired.
158          */

159         public void run() {
160             while(!stateMonitor.isTerminated()) {
161                 stateMonitor.monitor();
162                 Map JavaDoc sessionMapCopy = new HashMap JavaDoc();
163                 synchronized(userSessionIndex) {
164                     sessionMapCopy.putAll(userSessionIndex.sessionIdMap);
165                 }
166                 for (Iterator JavaDoc iter = sessionMapCopy.keySet().iterator();
167                         iter.hasNext() && !stateMonitor.isTerminated();) {
168                     UserSession userSession = (UserSession)sessionMapCopy.get(
169                             iter.next());
170                     // we check the expiry date twice to deal with race
171
// conditions that exist with aquiring the lock on the
172
// user session index.
173
if (userSession.isExpired()) {
174                         synchronized(userSessionIndex) {
175                             if (userSession.isExpired()) {
176                                 userSessionIndex.sessionIdMap.remove(
177                                         userSession.getSessionId());
178                             }
179                         }
180                     }
181                 }
182             }
183         }
184         
185         
186         /**
187          * This method terminates the timeout thread.
188          */

189         public void terminte() {
190             stateMonitor.terminate(true);
191         }
192     }
193     
194     // the user session logger
195
private Logger log =
196         Logger.getLogger(UserSessionManager.class.getName());
197     
198     // the classes member variables
199
private UserSessionIndex userSessionIndex = new UserSessionIndex();
200     private TimeoutThread timeoutThread = null;
201     private ThreadsPermissionContainer permissions = null;
202     private UserStoreManager userStoreManager = null;
203     
204     /**
205      * Creates a new instance of UserSessionManager
206      *
207      * @param permissions The permissions for the threads.
208      * @param userStoreManager The reference to the user store manager.
209      */

210     public UserSessionManager(ThreadsPermissionContainer permissions,
211             UserStoreManager userStoreManager) {
212         this.permissions = permissions;
213         this.userStoreManager = userStoreManager;
214     }
215     
216     
217     /**
218      * This method will create a new session for the calling thread using the
219      * supplied username.
220      *
221      * @param username The name of the user that the session must be created for.
222      * @exception UserException
223      */

224     public void initSessionForUser(String JavaDoc username) throws UserException {
225         try {
226             UserSession user = userStoreManager.getUserInfo(username);
227             Long JavaDoc threadId = new Long JavaDoc(Thread.currentThread().getId());
228             permissions.putSession(threadId,new ThreadPermissionSession(
229                     threadId,user));
230             userSessionIndex.putUser(user);
231         } catch (Exception JavaDoc ex) {
232             throw new UserException("Failed to init the session for [" +
233                     username + "] : " + ex.getMessage(),ex);
234         }
235     }
236     
237     
238     /**
239      * This method will create a new session for the calling thread using the
240      * supplied username.
241      *
242      * @param user The user
243      * @exception UserException
244      */

245     public void initSessionForUser(UserSession user) throws UserException {
246         try {
247             Long JavaDoc threadId = new Long JavaDoc(Thread.currentThread().getId());
248             permissions.putSession(threadId,new ThreadPermissionSession(
249                     threadId,user));
250             userSessionIndex.putUser(user);
251         } catch (Exception JavaDoc ex) {
252             throw new UserException("Failed to init the session for [" +
253                     user.getName() + "] : " + ex.getMessage(),ex);
254         }
255     }
256     
257     
258     /**
259      * This method adds a session for a user to the user session index so that
260      * it can be refered to later. It does not over ride the session on the
261      * thread as this will be done when the thread Sudo's to that user.
262      *
263      * @param user The user
264      * @exception UserException
265      */

266     public void addUserSession(UserSession user) throws UserException {
267         try {
268             userSessionIndex.putUser(user);
269         } catch (Exception JavaDoc ex) {
270             throw new UserException("Failed to init the session for [" +
271                     user.getName() + "] : " + ex.getMessage(),ex);
272         }
273     }
274     
275     
276     /**
277      * This method returns the user session id.
278      *
279      * @return The reference to the user session object.
280      * @param sessionId The references to the user session id.
281      * @exception UserException
282      */

283     public UserSession getSessionById(String JavaDoc sessionId) throws UserException {
284         return userSessionIndex.getSessionById(sessionId);
285     }
286     
287     
288     /**
289      * This method starts the clean up thread
290      *
291      * @exception UserException
292      */

293     public void startCleanup() throws UserException {
294         timeoutThread = new TimeoutThread();
295         timeoutThread.start();
296     }
297     
298     
299     /**
300      * This method is responsible for terminating the user session store
301      */

302     public void shutdown() {
303         try {
304             timeoutThread.terminte();
305             timeoutThread.join();
306         } catch (Exception JavaDoc ex) {
307             log.error("Failed to wait for the time out thread to terminate " +
308                     "because : " + ex.getMessage(),ex);
309         }
310     }
311 }
312
Popular Tags