package online.filter;

import java.io.IOException;
import java.nio.charset.Charset;
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;

/**
 * エンコード設定フィルタ
 *
 * @author Tadashi Nakayama
 * @version 1.0.0
 */
public final class EncodingFilter implements Filter {

	/** エンコード */
	private String encoding = "UTF-8";

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

	/**
	 * @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 (svRequest.getCharacterEncoding() == null) {
			svRequest.setCharacterEncoding(this.encoding);
		}

		// サーブレット実行
		chain.doFilter(svRequest, svResponse);
	}
}
