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

import info.dragonlady.sso.helper.SSOServletConfig;

import java.io.IOException;

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

import info.dragonlady.sso.Responder;
import info.dragonlady.sso.SSOException;

/**
 * SAML応答処理サーブレット。
 * 
 * @author Hiroshi.Ebata(INFOCITY)
 * @version $Revision: 1.0 $ $Date: 2006/10/19 17:40:11 $
 */
public class ResponderServlet extends HttpServlet {

	/**
	 * コンストラクタ。
	 */
	public ResponderServlet() {
		super();
	}

	/**
	 * SAML応答処理。
	 * 
	 * @param request HTTP要求オブジェクト
	 * @param response HTTP応答オブジェクト
	 * @throws ServletException
	 * @throws IOException
	 * @see javax.servlet.http.HttpServlet#service(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
	 */
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			// SAML要求に含まれるアーティファクトに対応するアサーションを取得し、SAML応答に含めて応答する
			Responder responder = new Responder(request, response);
			responder.processRequest();
		} catch(SSOException e) {
			processException(e, response, HttpServletResponse.SC_FORBIDDEN);
		} catch(Exception e) {
			processException(e, response, HttpServletResponse.SC_NOT_FOUND);
		}
	}

	private void processException(Exception e, HttpServletResponse response, int statusCode) throws ServletException {
		try {
			e.printStackTrace();
			if(!response.isCommitted()) {
				String redirectionUrl = SSOServletConfig.getRedirection();
				if(redirectionUrl != null && redirectionUrl.length() > 0) {
					response.sendRedirect(redirectionUrl);
				} else {
					response.sendError(statusCode);
				}
			}
		} catch(Exception ex) {
			throw new ServletException(ex);
		}
	}

}
