views:

122

answers:

2

I need to write a servlet that, when called, gets information about the current instance of jboss it is running in, specifically, a list of the currently opened sessions.

is there a way to do this?

thanks in advance.

+2  A: 

Implement HttpSessionListener, give it a static Set<HttpSession> property, add the session to it during sessionCreated() method, remove the session from it during sessionDestroyed() method, register the listener as <listener> in web.xml. Now you've a class which has all open sessions in the current JBoss instance collected. Here's a basic example:

public HttpSessionCollector implements HttpSessionListener {
    private static final Set<HttpSession> sessions = new HashSet<HttpSession>();

    public void sessionCreated(HttpSessionEvent event) {
        sessions.add(event.getSession());
    }

    public void sessionDestroyed(HttpSessionEvent event) {
        sessions.remove(event.getSession());
    }

    public static Set<HttpSession> getSessions() {
        return sessions;
    }
}

Then in your servlet just do:

Set<HttpSession> sessions = HttpSessionCollector.getSessions();

If you rather want to store/get it in the application scope so that you can make the Set<HttpSession> non-static, then let the HttpSessionCollector implement ServletContextListener as well and add basically the following methods:

public void contextCreated(ServletContextEvent event) {
    event.getServletContext().setAttribute("HttpSessionCollector.instance", this);
}

public static HttpSessionCollector getCurrentInstance(ServletContext context) {
    return (HttpSessionCollector) context.getAttribute("HttpSessionCollector.instance");
}

which you can use in Servlet as follows:

HttpSessionCollector collector = HttpSessionCollector.getCurrentInstance(getServletContext());
Set<HttpSession> sessions = collector.getSessions();
BalusC
+2  A: 

Perhaps using a JMX bean is more elegant and needs no code. Just read the value of

data: jboss.web:type=Manager,path=/myapplication,host=localhost" activeSessions

Plugtree Labs