Adding an activity monitor to your wicket application

Sometimes its useful in an application to have a list of users who are currently logged onto an application on a server.

To do this, you first need a SessionAttributeListener which listens for attributes being added to and removed from the session:

public class SessionAttributeListener implements HttpSessionAttributeListener {
	private static List activeUsers = Collections.synchronizedList(new ArrayList()); // listener is being called from multiple threads and ArrayList is unsynchronized

	public static List getActiveUsers() {
		return activeUsers;
	}

	@Override
	public void attributeAdded(HttpSessionBindingEvent event) {
		if (event.getName().equals("wicket:wicket.acpro:user.name"))
			activeUsers.add(event.getValue().toString());
	}

	@Override
	public void attributeRemoved(HttpSessionBindingEvent event) {
		if (event.getName().equals("wicket:wicket.acpro:user.name"))
			activeUsers.remove(event.getValue().toString());
	}

	@Override
	public void attributeReplaced(HttpSessionBindingEvent event) {
	}
}

Then from within your application login, you can set a session attribute when a user logs on

Session.get().setAttribute("user.name", getLoggedOnUser().getName());

You don’t need to remove the attribute on logout, as long as you are invalidating the session – this will automatically remove the attribute and invoke the attributeRemoved method of the listener.
The final step is to add an activity monitor display to your application which calls SessionAttributeListener.getActiveUsers() and displays the list.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.