package jp.sourceforge.shovel.filter;

import static jp.sourceforge.shovel.CommonConst.*;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.RequestDispatcher;
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.seasar.framework.container.S2Container;
import org.seasar.framework.container.factory.SingletonS2ContainerFactory;

import jp.sourceforge.shovel.exception.ErrorPage;

public class TransactionFilter implements Filter {
    static Log errorLog = LogFactory.getLog(ERROR_LOG);

    public void init( FilterConfig filterConfig ) throws ServletException {
    }
    public void destroy() {
    }

    public void doErrorLog(ErrorPage e) {
        errorLog.error("", e);
    }
    public void doFilter( ServletRequest request, ServletResponse response, FilterChain chain ) throws IOException, ServletException {
        //すでにトランザクションが開始しているならスルー
        if (request.getAttribute("transaction") != null) {
            chain.doFilter( request, response );
            return;
        }

        request.setAttribute("transaction", true);

        S2Container container = SingletonS2ContainerFactory.getContainer();
        TransactionFilterDelegete filter = (TransactionFilterDelegete)container.getComponent( TransactionFilterDelegete.class );
        try {
            filter.doFilter( request, response, chain );
        } catch( ErrorPage e ) {
            this.doErrorLog(e);
            RequestDispatcher rd = request.getRequestDispatcher(e.getErrorPage());
            rd.forward(request, response);
        }
    }
}
