// Collection of code snippets by Arne Vajhøj 
// (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) 
package test;

import java.util.*;

import javax.servlet.*;
import javax.servlet.http.*;

public class TimeoutEnforcer implements HttpSessionAttributeListener {
    private final static int CHECK_MS = 1000;
    private LinkedList itms;
    private Timer t;
    public TimeoutEnforcer() {
        itms = new LinkedList();
        t = new Timer(true);
        t.scheduleAtFixedRate(new Checker(itms), CHECK_MS, CHECK_MS);
    }
    public void attributeAdded(HttpSessionBindingEvent sbe) {
        synchronized(itms) {
            itms.add(new Item(sbe.getSession(), sbe.getName(), System.currentTimeMillis()));
        }
    }
    public void attributeRemoved(HttpSessionBindingEvent sbe) {
        synchronized(itms) {
            itms.remove(new Item(sbe.getSession(), sbe.getName(), 0));
        }
    }
    public void attributeReplaced(HttpSessionBindingEvent sbe) {
        // do nothing
    }
}

class Checker extends TimerTask {
    private final static int TIMEOUT_MS = 10000;
    private LinkedList ll;
    public Checker(LinkedList ll) {
        this.ll =ll;
    }
    public void run() {
        long cut = System.currentTimeMillis() - TIMEOUT_MS;
        synchronized(ll) {
            Item o;
            while((o = (Item)ll.peek()) != null && (o.getTime() < cut)) {
                o.getSession().removeAttribute(o.getAttribute());
            }
        }
    }
}

class Item {
    private HttpSession session;
    private String attribute;
    private long time;
    public Item(HttpSession session, String attribute, long time) {
        this.session = session;
        this.attribute = attribute;
        this.time = time;
    }
    public HttpSession getSession() {
        return session;
    }
    public String getAttribute() {
        return attribute;
    }
    public long getTime() {
        return time;
    }
    public boolean equals(Object o) {
        if(o instanceof Item) {
            Item oitem = (Item)o;
            if(session.equals(oitem.session) && attribute.equals(oitem.attribute)) {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }
    public int hashCode() {
        return (session.hashCode() + attribute.hashCode());
    }
}
