How to get all sessions in Vaadin
[Retraction]
Here is a wrong Answer. I mistakenly thought the cited method answers the Question, but it does not. Consider this a retraction; rather than delete this Answer I'll leave it so that others avoid making my mistake.
VaadinSession.getAllSessions()
With Vaadin 7.2 came the addition of a static method, VaadinSession.getAllSessions
. For history, see Ticket # 13053.
That method returns a Collection
of VaadinSession
objects attached to a single HttpSession
.
This method tells you how many VaadinSession objects are running for a single user’s HttpSession, but does not tell you how many overall users are on your Vaadin app server.
Best solution i found so far is to count the sessions when they are created and destroyed.
public class VaadinSessionListener{
private static volatile int activeSessions = 0;
public static class VaadinSessionInitListener implements SessionInitListener{
@Override
public void sessionInit(SessionInitEvent event) throws ServiceException {
incSessionCounter();
}
}
public static class VaadinSessionDestroyListener implements SessionDestroyListener{
@Override
public void sessionDestroy(SessionDestroyEvent event) {
/*
* check if HTTP Session is closing
*/
if(event.getSession() != null && event.getSession().getSession() != null){
decSessionCounter();
}
}
}
public static Integer getActiveSessions() {
return activeSessions;
}
private synchronized static void decSessionCounter(){
if(activeSessions > 0){
activeSessions--;
}
}
private synchronized static void incSessionCounter(){
activeSessions++;
}
}
then add the SessionListeners in the VaadinServlet init() method
@WebServlet(urlPatterns = "/*", asyncSupported = true)
@VaadinServletConfiguration(productionMode = true, ui = MyUI.class)
public static class Servlet extends VaadinServlet {
@Override
public void init(ServletConfig servletConfig) throws ServletException {
super.init(servletConfig);
/*
* Vaadin SessionListener
*/
getService().addSessionInitListener(new VaadinSessionListener.VaadinSessionInitListener());
getService().addSessionDestroyListener(new VaadinSessionListener.VaadinSessionDestroyListener());
}
}