KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > lutris > appserver > server > sessionContainerAdapter > TomcatContainerAdapterSessionManager


1 package com.lutris.appserver.server.sessionContainerAdapter;
2
3 import java.lang.reflect.Method JavaDoc;
4 import java.util.Date JavaDoc;
5 import java.util.Enumeration JavaDoc;
6 import java.util.Set JavaDoc;
7 import java.util.Vector JavaDoc;
8
9 import javax.management.MBeanServer JavaDoc;
10 import javax.management.MBeanServerFactory JavaDoc;
11 import javax.management.ObjectName JavaDoc;
12
13 import javax.servlet.http.HttpSession JavaDoc;
14
15 import com.lutris.appserver.server.Application;
16 import com.lutris.appserver.server.httpPresentation.HttpPresentationComms;
17 import com.lutris.appserver.server.session.Session;
18 import com.lutris.appserver.server.session.SessionException;
19 import com.lutris.appserver.server.session.SessionManager;
20 import com.lutris.appserver.server.sessionEnhydra.CreateSessionException;
21 import com.lutris.appserver.server.user.User;
22
23 /**
24  * @author Milin Radivoj
25  *
26  * <p>
27  * Description:
28  * </p>
29  * an implementation of ContainerAdapterSessionManager specific to the Tomcat
30  * Servlet container. It uses reflection to obtain data from the Tomcat's
31  * session manager, which really manages the sessions
32  * @version 1.0
33  */

34 public class TomcatContainerAdapterSessionManager extends
35         ContainerAdapterSessionManager {
36
37     private Object JavaDoc manager;
38
39     private Method JavaDoc createSession;
40
41     private Method JavaDoc expireSession;
42
43     private Method JavaDoc findSession;
44
45     private Method JavaDoc findSessions;
46
47     private Method JavaDoc getActiveSessions;
48
49     private Method JavaDoc getMaxActive;
50
51     private Method JavaDoc getExpiredSessions;
52
53     private Application application;
54
55     private boolean saveOnRestart = false;
56
57     private int maxSessions = -1;
58
59     private boolean initialized = false;
60
61     public TomcatContainerAdapterSessionManager(
62             com.lutris.appserver.server.Application application,
63             com.lutris.util.Config config, com.lutris.logging.LogChannel logger)
64             throws com.lutris.appserver.server.session.SessionException {
65         super(application, config, logger);
66         this.application = application;
67
68         try {
69             if (config.containsKey("SessionHome.SaveOnRestart")) {
70                 saveOnRestart = config.getBoolean("SessionHome.SaveOnRestart",false);
71             }
72         } catch (com.lutris.util.ConfigException e) {
73             throw new com.lutris.appserver.server.session.SessionException(e);
74         }
75
76         try {
77             if (config.containsKey("SessionHome.MaxSessions")) {
78                 maxSessions = config.getInt("SessionHome.MaxSessions");
79             }
80         } catch (com.lutris.util.ConfigException e) {
81             throw new com.lutris.appserver.server.session.SessionException(e);
82         }
83     }
84
85     /**
86      * Creates a new session
87      *
88      * @return Seession
89      * @throws SessionException
90      */

91     public Session JavaDoc createSession()
92             throws com.lutris.appserver.server.session.SessionException {
93
94         if (!initialized)
95             initialize();
96
97         HttpSession JavaDoc httpSession;
98
99         try {
100             httpSession = (HttpSession JavaDoc) createSession.invoke(manager,
101                     new Object JavaDoc[] {});
102         } catch (Exception JavaDoc e) {
103             throw new CreateSessionException(
104                     "New session cannot be instantiated " + e.getMessage());
105         }
106         if (httpSession != null) {
107             ContainerAdapterSession enhydraSession = new ContainerAdapterSession(
108                     this, httpSession);
109             httpSession.setAttribute(SESSION, enhydraSession);
110             httpSession.setMaxInactiveInterval(maxSessionIdleTime);
111
112             return enhydraSession;
113         } else {
114             throw new CreateSessionException(
115                     "New session cannot be instantiated");
116         }
117     }
118
119     /**
120      * Not implemented
121      *
122      * @return
123      */

124     public Session JavaDoc createSession(String JavaDoc ipPortToken)
125             throws com.lutris.appserver.server.session.SessionException {
126
127         /** No need to implement this method - used only for Director */
128         throw new java.lang.UnsupportedOperationException JavaDoc(
129                 "Method createSession(String ipPortToken) not implemented.");
130     }
131
132     /**
133      * Creates a new session
134      *
135      * @return Seession
136      * @throws SessionException
137      */

138     public Session JavaDoc createSession(HttpPresentationComms comms)
139             throws com.lutris.appserver.server.session.SessionException {
140
141         if (!initialized)
142             initialize();
143
144         return super.createSession(comms);
145     }
146
147     /**
148      * Delete existing session
149      *
150      * @return
151      * @throws SessionException
152      */

153     public void deleteSession(Session JavaDoc parm1)
154             throws com.lutris.appserver.server.session.SessionException {
155         if (!initialized)
156             initialize();
157         try {
158             expireSession.invoke(manager,
159                     new Object JavaDoc[] { parm1.getSessionKey() });
160         } catch (Exception JavaDoc e) {
161             throw new SessionException("Session cannot be deleteded "
162                     + e.getMessage());
163         }
164
165     }
166
167     /**
168      * Delete existing session
169      *
170      * @return
171      * @throws SessionException
172      */

173     public void deleteSession(String JavaDoc parm1)
174             throws com.lutris.appserver.server.session.SessionException {
175         if (!initialized)
176             initialize();
177         try {
178             expireSession.invoke(manager, new Object JavaDoc[] { parm1 });
179         } catch (Exception JavaDoc e) {
180             throw new SessionException("Session cannot be deleteded "
181                     + e.getMessage());
182         }
183     }
184
185     /**
186      * Lookup the <code>Session</code> object associated with the specified
187      * session key.
188      * <P>
189      *
190      *
191      * @param sessionKey
192      * The String used to reference a <code>Session</code> object.
193      * @return If the key is associated with an active session, then the
194      * corresponding <code>Session</code> object is returned.
195      * Otherwise <code>null</code> is returned.
196      * @exception SessionException
197      * If the session cannot be retrieved.
198      */

199     public Session JavaDoc getSession(String JavaDoc sessionId)
200             throws com.lutris.appserver.server.session.SessionException {
201
202         if (!initialized)
203             initialize();
204         HttpSession JavaDoc httpSession;
205
206         try {
207             httpSession = (HttpSession JavaDoc) findSession.invoke(manager,
208                     new Object JavaDoc[] { sessionId });
209         } catch (Exception JavaDoc e) {
210             throw new SessionException("Problem while lookup for session "
211                     + e.getMessage());
212         }
213
214         Session JavaDoc enhydraSession = null;
215
216         if (httpSession != null) {
217
218             try {
219                 enhydraSession = (Session JavaDoc) httpSession.getAttribute(SESSION);
220             } catch (IllegalStateException JavaDoc ex) {
221                 //it's ok session is expired
222
return null;
223             }
224             if (enhydraSession != null)
225                 chackSessionManager(enhydraSession);
226
227             return enhydraSession;
228         } else {
229             return null;
230         }
231     }
232
233     /**
234      * Lookup the <code>Session</code> object associated with the specified
235      * session key.
236      * <P>
237      *
238      *
239      * @param sessionKey
240      * The String used to reference a <code>Session</code> object.
241      * @return If the key is associated with an active session, then the
242      * corresponding <code>Session</code> object is returned.
243      * Otherwise <code>null</code> is returned.
244      * @exception SessionException
245      * If the session cannot be retrieved.
246      */

247
248     public Session JavaDoc getSession(Thread JavaDoc parm1, String JavaDoc sessionId)
249             throws com.lutris.appserver.server.session.SessionException {
250         return getSession(sessionId);
251     }
252
253     /**
254      * Returns teh session object corresponding to the HttpPresentationComms
255      *
256      * @param parm1
257      * ignored
258      * @param sessionId
259      * ignored
260      * @param comms
261      * HttpPresentationComms object that contains HttpServletRequest
262      * from which the session is extracted
263      * @return the Session object
264      * @throws SessionException
265      */

266     public Session JavaDoc getSession(Thread JavaDoc parm1, String JavaDoc sessionId,
267             HttpPresentationComms comms)
268             throws com.lutris.appserver.server.session.SessionException {
269
270         if (!initialized)
271             initialize();
272
273         return super.getSession(parm1, sessionId, comms);
274     }
275
276     /**
277      * Get all of the active sessions Keys.
278      *
279      * @return An enumeration of the active sessions Keys.
280      * @exception SessionException
281      * If the sessions cannot be retrieved.
282      */

283     public Enumeration JavaDoc getSessionKeys(User parm1)
284             throws com.lutris.appserver.server.session.SessionException {
285
286         if (!initialized)
287             initialize();
288
289         HttpSession JavaDoc[] httpSession;
290         try {
291             httpSession = (HttpSession JavaDoc[]) findSessions.invoke(manager,
292                     new Object JavaDoc[] {});
293
294         } catch (Exception JavaDoc e) {
295             throw new SessionException("Problem while lookup for session Keys "
296                     + e.getMessage());
297         }
298
299         Vector JavaDoc list = new Vector JavaDoc();
300
301         if (httpSession != null) {
302
303             for (int i = 0; i < httpSession.length; i++) {
304                 Session JavaDoc enhydraSession = null;
305
306                 try {
307                     enhydraSession = (Session JavaDoc) httpSession[i]
308                             .getAttribute(SESSION);
309                 } catch (IllegalStateException JavaDoc ex) {
310                     //it's ok session is expired
311
continue;
312                 }
313                 User user = enhydraSession.getUser();
314                 if (user != null && parm1 != null && parm1.getName() != null
315                         && user.getName() != null
316                         && parm1.getName().equals(user.getName()))
317                     list.add(httpSession[i].getId());
318             }
319
320             return list.elements();
321
322         } else {
323             return list.elements();
324         }
325     }
326
327     /**
328      * Gets the number of currently active sessions.
329      *
330      * @return The number of currently active sessions.
331      * @exception SessionException
332      *
333      */

334     public int activeSessionCount()
335             throws com.lutris.appserver.server.session.SessionException {
336
337         if (!initialized)
338             initialize();
339         Integer JavaDoc count;
340
341         try {
342             count = (Integer JavaDoc) getActiveSessions
343                     .invoke(manager, new Object JavaDoc[] {});
344         } catch (Exception JavaDoc e) {
345             throw new SessionException(
346                     "Problem while lookup for active session count "
347                             + e.getMessage());
348         }
349         return count.intValue();
350     }
351
352     /**
353      *
354      * @return the number of expired sessions (not including the sessions forced
355      * to expire), or -1 if it can not be determined
356      * @throws SessionException
357      */

358     public int expiredSessionCount()
359             throws com.lutris.appserver.server.session.SessionException {
360         if (!initialized)
361             initialize();
362         Integer JavaDoc count;
363         try {
364             count = (Integer JavaDoc) getExpiredSessions.invoke(manager,
365                     new Object JavaDoc[] {});
366         } catch (Exception JavaDoc e) {
367             return -1;
368         }
369
370         return count.intValue();
371     }
372
373     /**
374      * Gets the maximum number of concurent sessions that existed at any time
375      *
376      * @return The number of sessions, or -1.
377      */

378     public int maxSessionCount() {
379
380         Integer JavaDoc count;
381         try {
382             if (!initialized)
383                 initialize();
384             count = (Integer JavaDoc) getMaxActive.invoke(manager, new Object JavaDoc[] {});
385         } catch (Exception JavaDoc e) {
386             return -1;
387         }
388         return count.intValue();
389
390     }
391
392     /**
393      * Not implemented
394      *
395      * @return
396      */

397     public Date JavaDoc maxSessionCountDate() {
398
399         /** Not implemented */
400         throw new java.lang.UnsupportedOperationException JavaDoc(
401                 "Method maxSessionCountDate() not implemented.");
402     }
403
404     /**
405      * Reset the maximum session count. See <CODE>maxSessionCount()</CODE>.
406      * The highwater mark should be reset to the current number of sessions.
407      *
408      * @exception SessionException
409      * if the max session count cannot be reset.
410      */

411
412     public void resetMaxSessionCount()
413             throws com.lutris.appserver.server.session.SessionException {
414
415         try {
416
417             Method JavaDoc setMaxActive = manager.getClass().getMethod("setMaxActive",
418                     new Class JavaDoc[] { int.class });
419
420             int current = activeSessionCount();
421
422             setMaxActive.invoke(manager, new Object JavaDoc[] { new Integer JavaDoc(current) });
423
424         } catch (Exception JavaDoc e) {
425             throw new SessionException("Problem while reset Max Session Count "
426                     + e.getMessage());
427         }
428     }
429
430     /**
431      * Get all of the active sessions Keys.
432      *
433      * @return An enumeration of the active sessions Keys.
434      * @exception SessionException
435      * If the sessions cannot be retrieved.
436      */

437     public Enumeration JavaDoc getSessionKeys()
438             throws com.lutris.appserver.server.session.SessionException {
439
440         if (!initialized)
441             initialize();
442         Object JavaDoc[] httpSession;
443
444         try {
445             httpSession = (Object JavaDoc[]) findSessions.invoke(manager,
446                     new Object JavaDoc[] {});
447         } catch (Exception JavaDoc e) {
448             throw new SessionException("Problem while lookup for session Keys "
449                     + e.getMessage());
450         }
451
452         Vector JavaDoc list = new Vector JavaDoc();
453
454         if (httpSession != null) {
455
456             for (int i = 0; i < httpSession.length; i++) {
457                 list.add(((HttpSession JavaDoc) httpSession[i]).getId());
458             }
459             return list.elements();
460         } else {
461             return list.elements();
462         }
463
464     }
465
466     public void initialize()
467             throws com.lutris.appserver.server.session.SessionException {
468         try {
469
470             MBeanServer JavaDoc mBeanServer = findMBeanServer();
471             Object JavaDoc current = application.getClass().getClassLoader();
472
473             ObjectName JavaDoc oname = new ObjectName JavaDoc("*:j2eeType=WebModule,*");
474
475             Set JavaDoc moduls = mBeanServer.queryNames(oname, null);
476             Object JavaDoc[] o = (Object JavaDoc[]) moduls.toArray();
477
478             for (int j = 0; j < o.length; j++) {
479
480                 Object JavaDoc context = (Object JavaDoc) mBeanServer.invoke((ObjectName JavaDoc) o[j],
481                         "findMappingObject", new Object JavaDoc[] {}, new String JavaDoc[] {});
482
483                 Method JavaDoc getLoader = context.getClass().getMethod("getLoader",
484                         new Class JavaDoc[] {});
485
486                 Object JavaDoc webAppLoader = getLoader
487                         .invoke(context, new Object JavaDoc[] {});
488
489                 Method JavaDoc getClassLoader = null;
490                 getClassLoader = webAppLoader.getClass().getMethod(
491                         "getClassLoader", new Class JavaDoc[] {});
492                 Object JavaDoc webAppClassLoader = getClassLoader.invoke(webAppLoader,
493                         new Object JavaDoc[] {});
494
495                 if (webAppClassLoader.equals(current)) {
496
497                     Method JavaDoc getManager = context.getClass().getMethod(
498                             "getManager", new Class JavaDoc[] {});
499
500                     manager = getManager.invoke(context, new Object JavaDoc[] {});
501
502                     createSession = manager.getClass().getMethod(
503                             "createSession", new Class JavaDoc[] {});
504                     expireSession = manager.getClass().getMethod(
505                             "expireSession", new Class JavaDoc[] { String JavaDoc.class });
506                     findSession = manager.getClass().getMethod("findSession",
507                             new Class JavaDoc[] { String JavaDoc.class });
508                     findSessions = manager.getClass().getMethod("findSessions",
509                             new Class JavaDoc[] {});
510                     getActiveSessions = manager.getClass().getMethod(
511                             "getActiveSessions", new Class JavaDoc[] {});
512                     getMaxActive = manager.getClass().getMethod("getMaxActive",
513                             new Class JavaDoc[] {});
514
515                     getExpiredSessions = manager.getClass().getMethod(
516                             "getExpiredSessions", new Class JavaDoc[] {});
517
518                     if (!saveOnRestart) {
519                         try {
520                             Method JavaDoc setPathname = manager.getClass()
521                                     .getMethod("setPathname",
522                                             new Class JavaDoc[] { String JavaDoc.class });
523
524                             setPathname.invoke(manager, new Object JavaDoc[] { null });
525                         } catch (Exception JavaDoc e) {
526                             //it`s OK
527
}
528                     }
529
530                     if (maxSessions > 0) {
531                         try {
532                             Method JavaDoc setMaxActiveSessions = manager.getClass()
533                                     .getMethod("setMaxActiveSessions",
534                                             new Class JavaDoc[] { int.class });
535
536                             setMaxActiveSessions.invoke(manager,
537                                     new Object JavaDoc[] { new Integer JavaDoc(maxSessions) });
538                         } catch (Exception JavaDoc e) {
539                             //it`s OK
540
}
541                     }
542
543                     initialized = true;
544                     return;
545                 }
546             }
547
548         } catch (Exception JavaDoc e) {
549             throw new SessionException(
550                     "Problem in initialization of TomcatContainerAdapterSessionManager : "
551                             + e.getMessage());
552         }
553
554     }
555
556     private MBeanServer JavaDoc findMBeanServer() {
557         MBeanServer JavaDoc mBeanServer;
558         try {
559             java.util.ArrayList JavaDoc server = MBeanServerFactory
560                     .findMBeanServer(null);
561             if (server == null) {
562                 return null;
563             } else {
564                 mBeanServer = (MBeanServer JavaDoc) server.get(0);
565             }
566         } catch (Exception JavaDoc e) {
567             mBeanServer = null;
568         }
569         return mBeanServer;
570     }
571     /**
572      *
573      */

574     public void shutdown() {
575         super.shutdown();
576         initialized = false;
577         application = null;
578         manager = null;
579         createSession = null;
580         expireSession = null;
581         findSession = null;
582         findSessions = null;
583         getActiveSessions = null;
584         getMaxActive = null;
585         getExpiredSessions = null;
586     }
587
588     private void chackSessionManager(Session JavaDoc session) {
589
590         SessionManager sessionManager = session.getSessionManager();
591
592         if (sessionManager == null) {
593             ((ContainerAdapterSession) session).setSessionManager(this);
594         }
595     }
596 }
Popular Tags