KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jboss > web > tomcat > tc6 > session > JBossManager


1 /*
2 * JBoss, Home of Professional Open Source
3 * Copyright 2005, JBoss Inc., and individual contributors as indicated
4 * by the @authors tag. See the copyright.txt in the distribution for a
5 * full listing of individual contributors.
6 *
7 * This is free software; you can redistribute it and/or modify it
8 * under the terms of the GNU Lesser General Public License as
9 * published by the Free Software Foundation; either version 2.1 of
10 * the License, or (at your option) any later version.
11 *
12 * This software is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
16 *
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with this software; if not, write to the Free
19 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
20 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
21 */

22 package org.jboss.web.tomcat.tc6.session;
23
24 import java.beans.PropertyChangeEvent JavaDoc;
25 import java.beans.PropertyChangeListener JavaDoc;
26 import java.beans.PropertyChangeSupport JavaDoc;
27 import java.io.IOException JavaDoc;
28 import java.util.HashMap JavaDoc;
29 import java.util.Iterator JavaDoc;
30 import java.util.Map JavaDoc;
31
32 import javax.management.MBeanServer JavaDoc;
33 import javax.management.ObjectName JavaDoc;
34 import javax.servlet.http.Cookie JavaDoc;
35 import javax.servlet.http.HttpServletResponse JavaDoc;
36
37 import org.apache.catalina.Container;
38 import org.apache.catalina.Context;
39 import org.apache.catalina.Engine;
40 import org.apache.catalina.Globals;
41 import org.apache.catalina.Lifecycle;
42 import org.apache.catalina.LifecycleException;
43 import org.apache.catalina.LifecycleListener;
44 import org.apache.catalina.Session;
45 import org.apache.catalina.connector.Connector;
46 import org.apache.catalina.connector.Response;
47 import org.apache.catalina.util.LifecycleSupport;
48 import org.jboss.logging.Logger;
49 import org.jboss.metadata.WebMetaData;
50 import org.jboss.metadata.web.ReplicationConfig;
51 import org.jboss.mx.util.MBeanServerLocator;
52 import org.jboss.web.tomcat.statistics.ReplicationStatistics;
53
54 import EDU.oswego.cs.dl.util.concurrent.ConcurrentHashMap;
55
56 /**
57  * Base abstract implementation of Tomcat manager without the concept of
58  * session operations, e.g., add, remove, etc.
59  *
60  * @author Ben Wang
61  * @author Hany Mesha
62  * @version $Revision: 58584 $
63  */

64 public abstract class JBossManager
65    implements AbstractJBossManager, Lifecycle,
66       JBossManagerMBean, PropertyChangeListener JavaDoc
67 {
68    // -- Constants ----------------------------------------
69
/**
70     * Informational name for this Catalina component
71     */

72    private static final String JavaDoc info_ = "JBossManager/1.0";
73
74    // -- Class attributes ---------------------------------
75
protected ReplicationStatistics stats_ = new ReplicationStatistics();
76
77    /**
78     * Policy to determine if a session is dirty
79     */

80    protected InvalidateSessionPolicy invalidateSessionPolicy_ = InvalidateSessionPolicy.SET_AND_NON_PRIMITIVE_GET;
81    /**
82     * Replication granulairty.
83     */

84    protected ReplicationGranularity replicationGranularity_ = ReplicationGranularity.SESSION;
85    
86    /**
87     * Session passivation flag set in jboss-web.xml by the user.
88     * If true, then the session passivation is enabled for this web application,
89     * otherwise, it's disabled
90     */

91    protected boolean passivationMode_ = false;
92    
93    /**
94     * Min time (seconds) the session must be idle since lastAccesstime before it's eligable for passivation
95     * This overrides maxActive_, to prevent thrashing if the there are lots of active sessions.
96     * Setting to -1 means it's ignored
97     */

98    protected int passivationMinIdleTime_ = -1;
99    
100    /**
101     * Max time (seconds) the session must be idle since lastAccesstime before it's eligable for passivation
102     * This overrides maxActive_, to prevent thrashing if the there are lots of active sessions.
103     * Setting to -1 means session should not be forced out.
104     */

105    protected int passivationMaxIdleTime_ = -1;
106    
107    /**
108     * The lifecycle_ event support for this component.
109     */

110    protected LifecycleSupport lifecycle_ = new LifecycleSupport(this);
111    /**
112     * Has this component been started_ yet?
113     */

114    protected boolean started_ = false;
115    /**
116     * The objectname this Manager is associated with
117     */

118    protected ObjectName JavaDoc objectName_;
119    /**
120     * The Log-object for this class
121     */

122    protected Logger log_ = Logger.getLogger(this.getClass().getName());
123    /**
124     * The Container with which this Manager is associated.
125     */

126    protected Container container_;
127   /**
128    /**
129     * The distributable flag for Sessions created by this Manager. If this
130     * flag is set to <code>true</code>, any user attributes added to a
131     * session controlled by this Manager must be Serializable.
132     */

133    protected boolean distributable_ = true;
134    /**
135     * The default maximum inactive interval for Sessions created by
136     * this Manager.
137     */

138    protected int maxInactiveInterval_ = 60;
139    /**
140     * The session id length of Sessions created by this Manager.
141     */

142    protected int sessionIdLength_ = 16;
143
144    // Maximum of ative sessions allowed. -1 is unlimited.
145
protected int maxActive_ = -1;
146
147    // Number of sessions created by this manager
148
protected int createdCounter_ = 0;
149
150    // number of rejected sessions because the number active sessions exceeds maxActive
151
protected int rejectedCounter_ = 0;
152
153    // Number of active sessions
154
protected int activeCounter_ = 0;
155
156    // Maximum number of active sessions seen so far
157
protected int maxActiveCounter_ = 0;
158
159    // number of expired session ids. Not sure what exactly does it mean in our clustered case.
160
protected int expiredCounter_ = 0;
161
162    protected long timeSinceLastReset_ = 0;
163
164    // Cumulative time spent in backgroundProcess
165
protected long processingTime_ = 0;
166    
167    /**
168     * Map<String,ClusteredSession>. Store the local sessions.
169     */

170    protected final Map JavaDoc sessions_ = new ConcurrentHashMap();
171
172    /**
173     * If set to true, it will not replicate the access time stamp unless attributes are dirty.
174     */

175    protected boolean useLocalCache_ = false;
176
177    /**
178     * The property change support for this component.
179     */

180    protected PropertyChangeSupport JavaDoc support_ = new PropertyChangeSupport JavaDoc(this);
181
182    protected SessionIDGenerator sessionIDGenerator_;
183
184    protected String JavaDoc jvmRoute_;
185    
186    // TODO Need a string manager to handle exception localization
187

188    public JBossManager()
189    {
190       sessionIDGenerator_ = SessionIDGenerator.getInstance();
191
192    }
193
194    public void init(String JavaDoc name, WebMetaData webMetaData, boolean useJK, boolean useLocalCache)
195            throws ClusteringNotSupportedException
196    {
197       ReplicationConfig rpc = webMetaData.getReplicationConfig();
198       if (rpc != null)
199       {
200          replicationGranularity_ = ReplicationGranularity.fromString(rpc.getGranularity());
201          invalidateSessionPolicy_ = InvalidateSessionPolicy.fromString(rpc.getTrigger());
202       }
203       maxActive_ = webMetaData.getMaxActiveSessionsAllowed();
204       passivationMode_ = webMetaData.getSessionPassivationMode();
205       if (passivationMode_)
206       {
207          passivationMinIdleTime_ = webMetaData.getSessionPassivationMinIdleTime();
208          passivationMaxIdleTime_ = webMetaData.getSessionPassivationMaxIdleTime();
209       }
210       useLocalCache_ = useLocalCache;
211       log_.info("init(): replicationGranularity_ is " + replicationGranularity_ +
212          " and invaldateSessionPolicy is " + invalidateSessionPolicy_ +
213          " and maxActiveSessions allowed is " + maxActive_ +
214          " and passivationMode is " + passivationMode_);
215
216       try
217       {
218          // Give this manager a name
219
objectName_ = new ObjectName JavaDoc("jboss.web:service=ClusterManager,WebModule=" + name);
220       }
221       catch (Throwable JavaDoc e)
222       {
223          log_.error("Could not create ObjectName", e);
224          throw new ClusteringNotSupportedException(e.toString());
225       }
226    }
227
228    public InvalidateSessionPolicy getInvalidateSessionPolicy()
229    {
230       return this.invalidateSessionPolicy_;
231    }
232
233    /**
234     * Retrieve the enclosing Engine for this Manager.
235     *
236     * @return an Engine object (or null).
237     */

238    public Engine getEngine()
239    {
240       Engine e = null;
241       for (Container c = getContainer(); e == null && c != null; c = c.getParent())
242       {
243          if (c != null && c instanceof Engine)
244          {
245             e = (Engine) c;
246          }
247       }
248       return e;
249    }
250
251    /**
252     * Retrieve the JvmRoute for the enclosing Engine.
253     *
254     * @return the JvmRoute or null.
255     */

256    public String JavaDoc getJvmRoute()
257    {
258       if (jvmRoute_ == null)
259       {
260          Engine e = getEngine();
261          jvmRoute_= (e == null ? null : e.getJvmRoute());
262       }
263       return jvmRoute_;
264    }
265
266    /**
267     * Get a new session-id from the distributed store
268     *
269     * @return new session-id
270     */

271    protected String JavaDoc getNextId()
272    {
273       return sessionIDGenerator_.getSessionId();
274    }
275
276    /**
277     * Gets the JMX <code>ObjectName</code> under
278     * which our <code>TreeCache</code> is registered.
279     */

280    public ObjectName JavaDoc getObjectName()
281    {
282       return objectName_;
283    }
284
285    public boolean isUseLocalCache()
286    {
287       return useLocalCache_;
288    }
289
290    /**
291     * Sets a new cookie for the given session id and response
292     *
293     * @param sessionId The session id
294     */

295    public void setSessionCookie(String JavaDoc sessionId)
296    {
297       HttpServletResponse JavaDoc response = SessionReplicationContext.getOriginalResponse();
298       setNewSessionCookie(sessionId, response);
299    }
300
301    public void setNewSessionCookie(String JavaDoc sessionId, HttpServletResponse JavaDoc response)
302    {
303       if (response != null)
304       {
305          Context context = (Context) container_;
306          Connector connector = ((Response JavaDoc)response).getConnector();
307          if (context.getCookies())
308          {
309             // set a new session cookie
310
Cookie JavaDoc newCookie = new Cookie JavaDoc(Globals.SESSION_COOKIE_NAME, sessionId);
311             if (log_.isDebugEnabled())
312             {
313                log_.debug("Setting cookie with session id:" + sessionId + " & name:" + Globals.SESSION_COOKIE_NAME);
314             }
315
316             String JavaDoc contextPath = null;
317             if (!connector.getEmptySessionPath() && (context != null)) {
318                 contextPath = context.getEncodedPath();
319             }
320
321             if ((contextPath != null) && (contextPath.length() > 0)) {
322                 newCookie.setPath(contextPath);
323             } else {
324                 newCookie.setPath("/");
325             }
326
327             if (connector.getSecure()) {
328                 newCookie.setSecure(true);
329             }
330
331             response.addCookie(newCookie);
332          }
333       }
334    }
335
336    // JBossManagerMBean-methods -------------------------------------
337

338    // A better property name for the MBean API
339
public int getMaxActiveAllowed()
340    {
341       return getMaxActive();
342    }
343    
344    // A better property name for the MBean API
345
public void setMaxActiveAllowed(int maxActive)
346    {
347       setMaxActive(maxActive);
348    }
349    
350    public long getMaxActiveSessionCount()
351    {
352       return this.maxActiveCounter_;
353    }
354
355    public ReplicationStatistics getReplicationStatistics()
356    {
357       return stats_;
358    }
359
360    public void resetStats()
361    {
362       stats_.resetStats();
363       activeCounter_ = 0;
364       maxActiveCounter_ = 0;
365       rejectedCounter_ = 0;
366       createdCounter_ = 0;
367       expiredCounter_ = 0;
368       processingTime_ = 0;
369       timeSinceLastReset_ = System.currentTimeMillis();
370    }
371
372    public long timeInSecondsSinceLastReset()
373    {
374       return (System.currentTimeMillis() - timeSinceLastReset_) / (1000L);
375    }
376
377    public long getActiveSessionCount()
378    {
379       return getActiveSessions();
380    }
381
382    public long getCreatedSessionCount()
383    {
384       return createdCounter_;
385    }
386
387    public long getExpiredSessionCount()
388    {
389       return expiredCounter_;
390    }
391
392    public long getRejectedSessionCount()
393    {
394       return rejectedCounter_;
395    }
396
397    public int getSessionMaxAliveTime()
398    {
399        return 0;
400    }
401
402    public void setSessionMaxAliveTime(int sessionMaxAliveTime)
403    {
404    }
405
406    public int getSessionAverageAliveTime()
407    {
408        return 0;
409    }
410
411    public void setSessionAverageAliveTime(int sessionAverageAliveTime)
412    {
413    }
414
415    public String JavaDoc reportReplicationStatistics()
416    {
417       StringBuffer JavaDoc tmp = new StringBuffer JavaDoc();
418       HashMap JavaDoc copy = new HashMap JavaDoc(stats_.getStats());
419       Iterator JavaDoc iter = copy.entrySet().iterator();
420       tmp.append("<table><tr>");
421       tmp.append("<th>sessionID</th>");
422       tmp.append("<th>replicationCount</th>");
423       tmp.append("<th>minPassivationTime</th>");
424       tmp.append("<th>maxPassivationTime</th>");
425       tmp.append("<th>totalPassivationTime</th>");
426       tmp.append("<th>minReplicationTime</th>");
427       tmp.append("<th>maxReplicationTime</th>");
428       tmp.append("<th>totalReplicationlTime</th>");
429       tmp.append("<th>loadCount</th>");
430       tmp.append("<th>minLoadTime</th>");
431       tmp.append("<th>maxLoadTime</th>");
432       tmp.append("<th>totalLoadTime</th>");
433       while (iter.hasNext())
434       {
435          Map.Entry JavaDoc entry = (Map.Entry JavaDoc) iter.next();
436          ReplicationStatistics.TimeStatistic stat = (ReplicationStatistics.TimeStatistic) entry.getValue();
437          if (stat != null)
438          {
439             tmp.append("<tr><td>");
440             tmp.append(entry.getKey());
441             tmp.append("</td><td>");
442             tmp.append(stat.replicationCount);
443             tmp.append("</td><td>");
444             tmp.append(stat.minPassivationTime);
445             tmp.append("</td><td>");
446             tmp.append(stat.maxPassivationTime);
447             tmp.append("</td><td>");
448             tmp.append(stat.totalPassivationTime);
449             tmp.append("</td><td>");
450             tmp.append(stat.minReplicationTime);
451             tmp.append("</td><td>");
452             tmp.append(stat.maxReplicationTime);
453             tmp.append("</td><td>");
454             tmp.append(stat.totalReplicationlTime);
455             tmp.append("</td><td>");
456             tmp.append(stat.loadCount);
457             tmp.append("</td><td>");
458             tmp.append(stat.minLoadTime);
459             tmp.append("</td><td>");
460             tmp.append(stat.maxLoadTime);
461             tmp.append("</td><td>");
462             tmp.append(stat.totalLoadlTime);
463             tmp.append("</td></tr>");
464          }
465       }
466       tmp.append("</table>");
467       copy.clear();
468       return tmp.toString();
469
470    }
471    
472    public String JavaDoc reportReplicationStatisticsCSV()
473    {
474       StringBuffer JavaDoc tmp = createCSVHeader();
475       HashMap JavaDoc copy = new HashMap JavaDoc(stats_.getStats());
476       Iterator JavaDoc iter = copy.entrySet().iterator();
477       while (iter.hasNext())
478       {
479          Map.Entry JavaDoc entry = (Map.Entry JavaDoc) iter.next();
480          ReplicationStatistics.TimeStatistic stat = (ReplicationStatistics.TimeStatistic) entry.getValue();
481          if (stat != null)
482          {
483             tmp.append("\n");
484             tmp.append(entry.getKey());
485             tmp.append(",");
486             tmp.append(stat.replicationCount);
487             tmp.append(",");
488             tmp.append(stat.minPassivationTime);
489             tmp.append(",");
490             tmp.append(stat.maxPassivationTime);
491             tmp.append(",");
492             tmp.append(stat.totalPassivationTime);
493             tmp.append(",");
494             tmp.append(stat.minReplicationTime);
495             tmp.append(",");
496             tmp.append(stat.maxReplicationTime);
497             tmp.append(",");
498             tmp.append(stat.totalReplicationlTime);
499             tmp.append(",");
500             tmp.append(stat.loadCount);
501             tmp.append(",");
502             tmp.append(stat.minLoadTime);
503             tmp.append(",");
504             tmp.append(stat.maxLoadTime);
505             tmp.append(",");
506             tmp.append(stat.totalLoadlTime);
507          }
508       }
509       copy.clear();
510       return tmp.toString();
511
512    }
513    
514    public String JavaDoc reportReplicationStatisticsCSV(String JavaDoc sessionId)
515    {
516       StringBuffer JavaDoc tmp = createCSVHeader();
517       Map JavaDoc stats = stats_.getStats();
518       ReplicationStatistics.TimeStatistic stat =
519          (ReplicationStatistics.TimeStatistic) stats.get(sessionId);
520       if (stat != null)
521       {
522          tmp.append("\n");
523          tmp.append(sessionId);
524          tmp.append(",");
525          tmp.append(stat.replicationCount);
526          tmp.append(",");
527          tmp.append(stat.minPassivationTime);
528          tmp.append(",");
529          tmp.append(stat.maxPassivationTime);
530          tmp.append(",");
531          tmp.append(stat.totalPassivationTime);
532          tmp.append(",");
533          tmp.append(stat.minReplicationTime);
534          tmp.append(",");
535          tmp.append(stat.maxReplicationTime);
536          tmp.append(",");
537          tmp.append(stat.totalReplicationlTime);
538          tmp.append(",");
539          tmp.append(stat.loadCount);
540          tmp.append(",");
541          tmp.append(stat.minLoadTime);
542          tmp.append(",");
543          tmp.append(stat.maxLoadTime);
544          tmp.append(",");
545          tmp.append(stat.totalLoadlTime);
546       }
547       return tmp.toString();
548    }
549    
550    private StringBuffer JavaDoc createCSVHeader()
551    {
552       StringBuffer JavaDoc tmp = new StringBuffer JavaDoc();
553       tmp.append("sessionID,");
554       tmp.append("replicationCount,");
555       tmp.append("minPassivationTime,");
556       tmp.append("maxPassivationTime,");
557       tmp.append("totalPassivationTime,");
558       tmp.append("minReplicationTime,");
559       tmp.append("maxReplicationTime,");
560       tmp.append("totalReplicationlTime,");
561       tmp.append("loadCount,");
562       tmp.append("minLoadTime,");
563       tmp.append("maxLoadTime,");
564       tmp.append("totalLoadTime");
565       
566       return tmp;
567    }
568
569    // Lifecycle-methods -------------------------------------
570

571    public void addLifecycleListener(LifecycleListener listener)
572    {
573       lifecycle_.addLifecycleListener(listener);
574    }
575
576    public LifecycleListener[] findLifecycleListeners()
577    {
578       return lifecycle_.findLifecycleListeners();
579    }
580
581    public void removeLifecycleListener(LifecycleListener listener)
582    {
583       lifecycle_.removeLifecycleListener(listener);
584    }
585
586    /**
587     * Start this Manager
588     *
589     * @throws org.apache.catalina.LifecycleException
590     *
591     */

592    public void start() throws LifecycleException
593    {
594       startManager();
595    }
596
597    /**
598     * Stop this Manager
599     *
600     * @throws org.apache.catalina.LifecycleException
601     *
602     */

603    public void stop() throws LifecycleException
604    {
605       resetStats();
606       stopManager();
607    }
608
609    /**
610     * Prepare for the beginning of active use of the public methods of this
611     * component. This method should be called after <code>configure()</code>,
612     * and before any of the public methods of the component are utilized.
613     *
614     * @throws IllegalStateException if this component has already been
615     * started_
616     * @throws org.apache.catalina.LifecycleException
617     * if this component detects a fatal error
618     * that prevents this component from being used
619     */

620    protected void startManager() throws LifecycleException
621    {
622       log_.info("Starting JBossManager");
623
624       // Validate and update our current component state
625
if (started_)
626          throw new LifecycleException
627             ("JBossManager alreadyStarted");
628       lifecycle_.fireLifecycleEvent(START_EVENT, null);
629       started_ = true;
630
631       // register ClusterManagerMBean to the MBeanServer
632
try
633       {
634          MBeanServer JavaDoc server = MBeanServerLocator.locateJBoss();
635          server.registerMBean(this, objectName_);
636       }
637       catch (Exception JavaDoc e)
638       {
639          log_.error("Could not register ClusterManagerMBean to MBeanServer", e);
640       }
641    }
642
643    /**
644     * Gracefully terminate the active use of the public methods of this
645     * component. This method should be the last one called on a given
646     * instance of this component.
647     *
648     * @throws IllegalStateException if this component has not been started_
649     * @throws org.apache.catalina.LifecycleException
650     * if this component detects a fatal error
651     * that needs to be reported
652     */

653    protected void stopManager() throws LifecycleException
654    {
655       log_.info("Stopping JBossManager");
656
657       // Validate and update our current component state
658
if (!started_)
659          throw new LifecycleException
660             ("JBossManager notStarted");
661       lifecycle_.fireLifecycleEvent(STOP_EVENT, null);
662       started_ = false;
663
664       // unregister ClusterManagerMBean from the MBeanServer
665
try
666       {
667          MBeanServer JavaDoc server = MBeanServerLocator.locateJBoss();
668          server.unregisterMBean(objectName_);
669       }
670       catch (Exception JavaDoc e)
671       {
672          log_.error("Could not unregister ClusterManagerMBean from MBeanServer", e);
673       }
674    }
675
676    // Manager-methods -------------------------------------
677
public Container getContainer()
678    {
679       return container_;
680    }
681
682    public void setContainer(Container container)
683    {
684
685       // De-register from the old Container (if any)
686
if ((this.container_ != null) && (this.container_ instanceof Context))
687          this.container_.removePropertyChangeListener(this);
688
689       // Default processing provided by our superclass
690
this.container_ = container;
691
692       // Register with the new Container (if any)
693
if ((this.container_ != null) && (this.container_ instanceof Context))
694       {
695          setMaxInactiveInterval
696             (((Context) this.container_).getSessionTimeout() * 60);
697          this.container_.addPropertyChangeListener(this);
698       }
699    }
700
701    public boolean getDistributable()
702    {
703       return distributable_;
704    }
705
706    public void setDistributable(boolean distributable)
707    {
708       this.distributable_ = distributable;
709    }
710
711    public String JavaDoc getInfo()
712    {
713       return info_;
714    }
715
716    public int getMaxInactiveInterval()
717    {
718       return maxInactiveInterval_;
719    }
720
721    public void setMaxInactiveInterval(int interval)
722    {
723       this.maxInactiveInterval_ = interval;
724    }
725
726    public int getSessionIdLength()
727    {
728       return sessionIdLength_;
729    }
730
731    public void setSessionIdLength(int idLength)
732    {
733       this.sessionIdLength_ = idLength;
734    }
735
736    public int getSessionCounter()
737    {
738       return createdCounter_;
739    }
740
741    public void setSessionCounter(int sessionCounter)
742    {
743       this.createdCounter_ = sessionCounter;
744    }
745
746    public int getMaxActive()
747    {
748       return maxActive_;
749    }
750
751    public void setMaxActive(int maxActive)
752    {
753       this.maxActive_ = maxActive;
754    }
755
756    public int getExpiredSessions()
757    {
758       return expiredCounter_;
759    }
760
761    public void setExpiredSessions(int expiredSessions)
762    {
763       this.expiredCounter_ = expiredSessions;
764    }
765
766    public int getRejectedSessions()
767    {
768       return rejectedCounter_;
769    }
770
771    public void setRejectedSessions(int rejectedSessions)
772    {
773       this.rejectedCounter_ = rejectedSessions;
774    }
775    
776    public long getProcessingTime()
777    {
778       return this.processingTime_;
779    }
780
781    public void addPropertyChangeListener(PropertyChangeListener JavaDoc listener)
782    {
783       support_.addPropertyChangeListener(listener);
784    }
785
786    /**
787     * Remove the active session locally from the manager without replicating to the cluster. This can be
788     * useful when the session is exipred, for example, where there is not need to propagate the expiration.
789     *
790     * @param session
791     */

792    public abstract void removeLocal(Session session);
793
794    /**
795     * Store the modified session.
796     *
797     * @param session
798     */

799    public abstract boolean storeSession(Session session);
800
801    public int getActiveSessions()
802    {
803       return activeCounter_;
804    }
805
806 /*
807    public void add(Session session)
808    {
809       //To change body of implemented methods use File | Settings | File Templates.
810    }
811
812    public Session createEmptySession()
813    {
814       return null; //To change body of implemented methods use File | Settings | File Templates.
815    }
816
817    public Session createSession()
818    {
819       return null; //To change body of implemented methods use File | Settings | File Templates.
820    }
821
822    public Session findSession(String id) throws IOException
823    {
824       return null; //To change body of implemented methods use File | Settings | File Templates.
825    }
826
827    public Session[] findSessions()
828    {
829       return new Session[0]; //To change body of implemented methods use File | Settings | File Templates.
830    }
831
832    public void remove(Session session)
833    {
834       //To change body of implemented methods use File | Settings | File Templates.
835    }
836 */

837
838    public void load() throws ClassNotFoundException JavaDoc, IOException JavaDoc
839    {
840       // TODO. Implement persistence layer.
841
throw new RuntimeException JavaDoc("JBossManager.load(): Method not implemented.");
842    }
843
844    public void removePropertyChangeListener(PropertyChangeListener JavaDoc listener)
845    {
846       support_.removePropertyChangeListener(listener);
847    }
848
849    public void unload() throws IOException JavaDoc
850    {
851       // TODO. Implement persistence layer.
852
throw new RuntimeException JavaDoc("JBossManager.load(): Method not implemented.");
853    }
854
855
856    public void backgroundProcess()
857    {
858       // Called from Catalina StandardEngine for every 60 seconds.
859

860       long start = System.currentTimeMillis();
861       
862       processExpires();
863       
864       long elapsed = System.currentTimeMillis() - start;
865       
866       processingTime_ += elapsed;
867    }
868
869    /**
870     * Go through all sessions and look if they have expired
871     */

872    protected void processExpires()
873    {
874       // What's the time?
875
// long timeNow = System.currentTimeMillis();
876

877       // Get all sessions
878
Session sessions[] = findSessions();
879       if (log_.isDebugEnabled())
880       {
881          log_.debug("Looking for sessions that have expired ...");
882       }
883
884       for (int i = 0; i < sessions.length; ++i)
885       {
886          ClusteredSession session = (ClusteredSession) sessions[i];
887
888          // We only look at valid sessions. This will remove session if not valid already.
889
if (!session.isValid())
890          {
891             continue;
892          }
893
894          /* I don't think it is right to check idle time based on lastAccessedTime since it may
895          // remove some request that is currently in progress!!!
896          // How long are they allowed to be idle?
897          int maxInactiveInterval = session.getMaxInactiveInterval();
898
899          // Negative values = never expire
900          if( maxInactiveInterval < 0 )
901          {
902             continue;
903          }
904
905          // How long has this session been idle?
906          int timeIdle =
907             (int) ((timeNow - session.getLastAccessedTime()) / 1000L);
908
909          // Too long?
910          if( timeIdle >= maxInactiveInterval )
911          {
912             try
913             {
914                log_.debug("Session with id = " + session.getId() + " has expired on local node");
915                remove(session);
916             }
917             catch(Throwable t)
918             {
919                log_.error("Problems while expiring session with id = " + session.getId(), t);
920             }
921          }
922          */

923       }
924    }
925
926    public void propertyChange(PropertyChangeEvent JavaDoc evt)
927    {
928       // TODO Need to handle it here.
929
}
930
931    /**
932     * Find in-memory sessions, if any.
933     * @return local session found. Sessions of size 0, if not found.
934     */

935    abstract public ClusteredSession[] findLocalSessions();
936
937    /**
938     * Find in-memory sessions, if any.
939     * @param realId the Session id without JvmRoute tag.
940     * @return local session found. Null if not found.
941     */

942    abstract public ClusteredSession findLocalSession(String JavaDoc realId);
943
944 }
945
Popular Tags