package jp.sf.amateras.mirage.filter;

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.slf4j.Logger;
import org.slf4j.LoggerFactory;

import jp.sf.amateras.mirage.session.Session;
import jp.sf.amateras.mirage.session.SessionFactory;

public class OpenSessionInViewFilter implements Filter {

	private static final Logger logger = LoggerFactory.getLogger(OpenSessionInViewFilter.class);

	@Override
	public void destroy() {
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {

		Session session = SessionFactory.getSession();

		try {
			session.begin();
		} catch(Exception ex){
			logger.error("Failed to begin Session.", ex);
			throw new RuntimeException(ex);
		}

		try {
			chain.doFilter(request, response);

			try {
				session.commit();
			} catch(Exception ex){
				logger.error("Failed to commit Session.", ex);
				throw new RuntimeException(ex);
			}
		} catch(Exception ex){
			try {
				session.rollback();
			} catch(Exception e){
				logger.error("Failed to rollback Session.", e);
				throw new RuntimeException(e);
			}
		} finally {
			try {
				session.release();
			} catch(Exception ex){
				logger.error("Failed to release Session.", ex);
				throw new RuntimeException(ex);
			}
		}
	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
	}

}
