/*
 * @(#)SSOBaseServlet.java
 *
 * Copyright (C) 2007 Infocity Inc. All Rights Reserved.
 */
package info.dragonlady.sso.servlet;

import info.dragonlady.sso.SSOConfig;
import info.dragonlady.sso.SSOContext;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

/**
 * SSOフレームワークの基本抽象サーブレットクラス。
 * 
 * @author Hiroshi.Ebata(INFOCITY)
 * @version $Revision: 1.0 $ $Date: 2007/04/19 12:03:33 $
 */
public abstract class SSOBaseServlet extends HttpServlet {

	/* (non-Javadoc)
	 * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
	 */
	@Override
	protected final void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		process(request, response);
	}

	/* (non-Javadoc)
	 * @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
	 */
	@Override
	protected final void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		process(request, response);
	}

	/* (non-Javadoc)
	 * @see javax.servlet.http.HttpServlet#service(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
	 */
	@Override
	protected final void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		SSOContext.getInstance().setCurrentRequest(request);
		super.service(request, response);
	}

	/**
	 * SSOサーブレット処理。
	 * 
	 * @param request HTTP要求オブジェクト
	 * @param response HTTP応答オブジェクト
	 * @throws ServletException
	 * @throws IOException
	 */
	protected abstract void process(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException;

	/**
	 * 例外処理。
	 * 
	 * @param message ログ出力メッセージ
	 * @param e 例外オブジェクト
	 * @param response HTTP応答オブジェクト
	 * @param statusCode HTTPステータスコード
	 * @throws ServletException
	 */
	protected void processException(String message, Exception e, HttpServletResponse response, int statusCode) throws ServletException {
		try {
			Logger.getRootLogger().error(message, e);
			if(!response.isCommitted()) {
				String redirectionUrl = SSOConfig.getRedirection();
				if(redirectionUrl != null && redirectionUrl.length() > 0) {
					response.sendRedirect(redirectionUrl);
				} else {
					response.sendError(statusCode);
				}
			}
		} catch(Exception ex) {
			throw new ServletException(ex);
		}
	}

}
