I need to get all active sessions from servlet.
But I believe this API is obsolated…
That is why, I tried to implement using existing API.
package jp.develop.tool.servlet;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionActivationListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
/**
* Session list providing Listener.
*/
public class SessionListListener implements HttpSessionListener, HttpSessionActivationListener, Serializable {
private static final boolean DEBUG = true;
private static final long serialVersionUID = 7490899888824580726L;
private static final String SESSION_LISTENER_KEY = "_sessionListListener";
private static Object lock = new Object();
private static List sessions = new ArrayList();
private static List sessionsForOutput = Collections.unmodifiableList(sessions);
/**
* Get all sessions.
* @return All sessions list.
*/
public static List getSessions() {
return sessionsForOutput;
}
/**
* Default Constructor.
*/
public SessionListListener() {
log(String.format("Session List Listener is initialized."));
}
/**
* @see HttpSessionListener#sessionCreated(HttpSessionEvent)
*/
public void sessionCreated(HttpSessionEvent event) {
synchronized (lock) {
HttpSession session = event.getSession();
session.setAttribute(SESSION_LISTENER_KEY, this);
sessions.add(session);
log(String.format("Session Added: %s", session.getId()));
}
}
/**
* @see HttpSessionListener#sessionDestroyed(HttpSessionEvent)
*/
public void sessionDestroyed(HttpSessionEvent event) {
synchronized (lock) {
HttpSession session = event.getSession();
session.removeAttribute(SESSION_LISTENER_KEY);
sessions.remove(session); // XXX May not good implementation for performance.
log(String.format("Session Removed: %s", session.getId()));
}
}
/**
* @see HttpSessionActivationListener#sessionDidActivate(HttpSessionEvent)
*/
public void sessionDidActivate(HttpSessionEvent event) {
synchronized (lock) {
HttpSession session = event.getSession();
sessions.add(session);
log(String.format("Session Activate: %s", session.getId()));
}
}
/**
* @see HttpSessionActivationListener#sessionWillPassivate(HttpSessionEvent)
*/
public void sessionWillPassivate(HttpSessionEvent event) {
synchronized (lock) {
HttpSession session = event.getSession();
sessions.remove(session); // XXX May not good implementation for performance.
log(String.format("Session Passivate: %s", session.getId()));
}
}
private static void log(String message) {
if (DEBUG) {
System.out.println(message);
}
}
}
If anybody find a problem, please let me know…

Recent Comments