/********************************************************************
 * Copyright © 2004 EDS. All rights reserved
 ********************************************************************/
package gov.vha.edb.rules.web;

import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionBindingListener;
import javax.servlet.http.HttpSessionBindingEvent;
import java.io.Serializable;
import java.util.Set;
import java.util.HashSet;
import java.util.Iterator;

import ilog.rules.repository.model.IlrRepository;
import ilog.rules.repository.facility.IlrPersistenceManager;

/**
 * <p>The <code>SessionListener</code> object cleans the repository attached to
 * a session when closed.</p>
 */
public class SessionListener
  implements HttpSessionBindingListener, Serializable {

    private static final long serialVersionUID = -6584825169071198377L;
    private Set repositories = new HashSet();

    private SessionListener() {
    }

  /**
   * <p>Registers a repository in the session listener.</p>
   */
  public void register(IlrRepository rep) {
    synchronized (this) {
      repositories.add(rep);
    }
  }

  public void valueBound(HttpSessionBindingEvent event) {
  }

  public void valueUnbound(HttpSessionBindingEvent event) {
    try {
      // Close all registered repositories.
      synchronized (this) {
        Iterator it = repositories.iterator();
        while (it.hasNext()) {
          IlrRepository rep = (IlrRepository)it.next();
          IlrPersistenceManager mgr = rep.getPersistenceManager();
          if (mgr!=null) {
            mgr.close();
          }
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  /**
   * <p>Attaches a repository to the current HTTP session.</p>
   */
  public static void register(HttpSession session, IlrRepository repository) {
    String name = "gov.vha.edb.rules.web.SessionListener";
    SessionListener l = (SessionListener)session.getAttribute(name);
    if (l==null) {
      l = new SessionListener();
      session.setAttribute(name, l);
    }
    l.register(repository);
  }

}


