package online.filter;

import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
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
 */
public class EncodingFilter implements Filter {

	/** エンコード */
	private String encoding = StandardCharsets.UTF_8.name();

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

	/**
	 * @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);
	}
}
