package jp.cssj.cti2.examples;

import java.io.IOException;
import java.net.URI;

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;

import jp.cssj.cti2.CTIDriverManager;
import jp.cssj.cti2.CTISession;
import jp.cssj.cti2.helpers.CTIHttpServletResponseWrapper;
import jp.cssj.cti2.helpers.ServletHelper;

public class SampleFilter implements Filter {
	/** 接続先。 */
	private static final URI SERVER_URI = URI.create("ctip://127.0.0.1:8099/");

	/** ユーザー。 */
	private static final String USER = "user";

	/** パスワード。 */
	private static final String PASSWORD = "kappa";

	public void init(FilterConfig config) throws ServletException {
		// ignore
	}

	public void doFilter(ServletRequest req, ServletResponse res,
			FilterChain chain) throws IOException, ServletException {
		CTISession session = CTIDriverManager.getSession(SERVER_URI, USER,
				PASSWORD);
		try {
			ServletHelper.setServletResponse(session, res);
			CTIHttpServletResponseWrapper ctiRes = new CTIHttpServletResponseWrapper(
					(HttpServletResponse) res, session, URI.create("."));
			try {
				chain.doFilter(req, ctiRes);
			} finally {
				ctiRes.close();
			}
		} finally {
			session.close();
		}
	}

	public void destroy() {
		// ignore
	}
}
