package de.spieleck.servlets; import java.util.TreeSet; import java.util.Iterator; import java.util.Comparator; import javax.servlet.http.*; /** * Watch all Sessions in the current Application: * Setup in the web.xml of a Servlet 2.3 conforming container via *
      /lt;listener>
        /lt;listener-class>de.spieleck.servlets.SessionAccountingListener/lt;/listener-class>
      /lt;/listener>
 * 
* then use the API's like *
 * ..
 * SessionAccountingListener salt = SessionAccountingListener.getInstance();
 * int sessionsCount = salt.getSessionCount();
 * Iterator sessions = salt.getSessions();
 * ...
 * 
* */ public class SessionAccountingListener implements HttpSessionListener { protected static SessionAccountingListener instance = null; protected TreeSet sessions; protected int totalSessions = 0; public SessionAccountingListener() { if ( instance != null ) System.err.println("Overwrite previous listener: "+this); instance = this; sessions = new TreeSet(SessionAccessComparator); } public static SessionAccountingListener getInstance() { return instance; } public void sessionCreated(HttpSessionEvent ev) { synchronized ( sessions ) { sessions.add(ev.getSession()); } totalSessions++; } public void sessionDestroyed(HttpSessionEvent ev) { synchronized ( sessions ) { sessions.remove(ev.getSession()); } } public int getTotalSessions() { return totalSessions; } public int getSessionCount() { return sessions.size(); } public Iterator getSessions() { synchronized ( sessions ) { // Copy sessions, to make iterator failsafe! return ((TreeSet)sessions.clone()).iterator(); } } public static Comparator SessionAccessComparator = new Comparator() { public int compare(Object o1, Object o2) { if ( o1 instanceof HttpSession && o2 instanceof HttpSession ) return (int)( ((HttpSession)o2).getLastAccessedTime() -((HttpSession)o1).getLastAccessedTime() ); return 0; } public boolean equals(Object o1, Object o2) { return o1 == o2; } } ; }