package isrp.filters;

import isrp.hibernate.model.util.HibernateUtil;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

public class HibernateSessionFilter implements Filter {

    private SessionFactory factory = null;
    private static final Log log = LogFactory.getLog(HibernateSessionFilter.class);
    
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
	throws IOException, ServletException {
        
        Session session = factory.getCurrentSession();     
        try {
            session.beginTransaction();
            log.debug("<< hib begin");            
            chain.doFilter(request, response);
            log.debug(">> hib end");
            session.getTransaction().commit();
            
        } catch (Throwable e) {
            try {
				if (session.getTransaction().isActive()) {
				    session.getTransaction().rollback();
				}
			} catch (HibernateException e1) {
				log.error("Could not rollback after exception!", e1);
				e1.printStackTrace();
			}
            throw new ServletException(e);
        }
    }

    public void destroy() { 
    }

    public void init(FilterConfig filterConfig) throws ServletException{ 
    	factory = HibernateUtil.getSessionFactory();
    	
        if (filterConfig == null) {
            log.error("HibernateSessionFilter: Initializing filter failed");
            throw new ServletException();
        }
    }
}

