package online.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 javax.servlet.http.HttpServletRequest;

/**
 * URI保存フィルタ
 *
 * @author Tadashi Nakayama
 * @version 1.0.0
 */
public class RecordURIFilter implements Filter {

	/** キー */
	private static final String CLAZZ = RecordURIFilter.class.getName();

	/**
	 * @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
	 */
	@Override
	public void init(final FilterConfig filterConfig) throws ServletException {
		return;
	}

	/**
	 * @see javax.servlet.Filter#destroy()
	 */
	@Override
	public void destroy() {
		return;
	}

	/**
	 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest,
	 * javax.servlet.ServletResponse, javax.servlet.FilterChain)
	 */
	@Override
	public void doFilter(final ServletRequest svRequest, final ServletResponse svResponse,
			final FilterChain chain) throws IOException, ServletException {
		if (HttpServletRequest.class.isInstance(svRequest)) {
			final HttpServletRequest request = HttpServletRequest.class.cast(svRequest);

			if (request.getAttribute(CLAZZ) == null) {
				request.setAttribute(CLAZZ, CLAZZ);

				FilterUtil.setRequest(request);
				FilterUtil.setContext(request);
				FilterUtil.setResponse(request);
			} else if (!FilterUtil.isView(request)) {
				FilterUtil.setResponse(request);
			}
		}

		chain.doFilter(svRequest, svResponse);
	}
}
