package online.filter;

import java.io.IOException;
import java.util.Objects;

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.HttpServletResponse;

/**
 * Expire設定フィルタ
 *
 * @author Tadashi Nakayama
 * @version 1.0.0
 */
public final class ExpireFilter implements Filter {

	/** 期限 */
	private long expire = 1;

	/**
	 * @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
	 */
	@Override
	public void init(final FilterConfig filterConfig) throws ServletException {
		String exp = filterConfig.getInitParameter("expire");
		if (!Objects.toString(exp, "").isEmpty()) {
			this.expire = Long.parseLong(exp);
		}
	}

	/**
	 * @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 (HttpServletResponse.class.isInstance(svResponse)) {
			HttpServletResponse response = HttpServletResponse.class.cast(svResponse);

			if (!response.containsHeader("Expires")) {
				response.setDateHeader("Expires", this.expire);
			}
		}

		chain.doFilter(svRequest, svResponse);
	}
}
