Session Tracking In Swing Applications
Session handling is pretty common in web applications. Java Servlet technology provides an API for managing sessions and allows several mechanisms for implementing sessions. But if you have swing application and want to track the session how to do that?
Here is the scenario – Suppose you have a swing based kiosk application. User logs in to the application and does some operations. Now for some reason he doesn’t perform any operation for 3-4 minutes then for security reasons we need to somehow log out from the swing application.
This can be achieved with the help of Swing timers and AWT default toolkit.
Here are the steps
- When user logs in start the swing timer by passing SESSION_TIMEOUT value and ActionListener (to handle timeout event).
- Add AWTEventListener to AWT toolkit with AWTEvent.MOUSE_EVENT_MASK and AWTEvent.KEY_EVENT_MASK. This will track only mouse events and key events.
- Whenever AWT event occurs (that means user performed some action) restart the timer.
- When the system is idle for SESSION_TIMEOUT time, timer will call actionPerformed method of its ActionListener.It means session timeout occured and you need to logout.
import java.awt.AWTEvent;
import java.awt.Toolkit;
import java.awt.event.AWTEventListener;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Timer;
/**
* @author airaj
*
*/
public class SystemTimeoutClient implements AWTEventListener, ActionListener
{
private int SESSION_TIMEOUT = 240000; // 4 minutes
private static SystemTimeoutClient client = null;
private Timer timer;
private SystemTimeoutClient()
{
}
public static SystemTimeoutClient getSystemTimeoutClient()
{
if (client == null)
{
client = new SystemTimeoutClient();
}
return client;
}
public void trackSessionTimeout()
{
timer = new Timer(SESSION_TIMEOUT, this);
timer.setInitialDelay(SESSION_TIMEOUT);
timer.setRepeats(false);
timer.start();
trackSystemEvents();
}
public void stopSessionTracking()
{
if (timer.isRunning())
{
timer.stop();
}
}
private void trackSystemEvents()
{
Toolkit.getDefaultToolkit().addAWTEventListener(this, AWTEvent.MOUSE_EVENT_MASK + AWTEvent.KEY_EVENT_MASK);
}
@Override
public void eventDispatched(AWTEvent event)
{
// User action detected. Restart the timer
if (timer.isRunning())
{
timer.restart();
}
}
@Override
public void actionPerformed(ActionEvent e)
{
// Session Timeout occured. Close resources and log out from system.
}
}


