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

import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

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

import info.dragonlady.cluster.UserServiceWrapper;
import info.dragonlady.sso.AssertionConsumer;
import info.dragonlady.sso.SSOConfig;
import info.dragonlady.sso.authority.EnforcementException;
import info.dragonlady.sso.helper.LoginManager;
import info.dragonlady.sso.message.SSOMessageResource;

/**
 * アサーション消費者サーブレット。
 * 
 * @author Hiroshi.Ebata(INFOCITY)
 * @version $Revision: 1.0 $ $Date: 2007/06/25 22:26:32 $
 */
public class AssertionConsumerServlet extends SSOBaseServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = -453213517162787294L;

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

	/* (non-Javadoc)
	 * @see info.dragonlady.sso.SSOBaseServlet#process(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
	 */
	@Override
	protected void process(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		try {
			AssertionConsumer consumer = new AssertionConsumer(request, response);

			if(consumer.isEnforceable()) {
				consumer.enforce();
				// 取得した認証ID、その他の属性情報をログインセッションに格納
				String authId = consumer.getAuthId();
				Map<String, List<String>> attributes = consumer.getAttributes();
				HttpSession session = request.getSession();
				session.setAttribute(SSOConfig.getLoginKey(), authId);
				if(attributes != null) {
					Iterator itr = attributes.keySet().iterator();
					while(itr.hasNext()) {
						Object key = itr.next();
						session.setAttribute((String)key, attributes.get(key));
					}
				}
				// ログイン管理情報に認証IDを追加
				LoginManager.getInstance().add(authId, session.getId());
				// 分散環境時のログイン情報共有
				if(!SSOConfig.isClusterStandalone()) {
					UserServiceWrapper.add(authId, session.getId());
				}
			} else {
				throw new EnforcementException(SSOMessageResource.getMessage("5301"));
			}
		} catch(EnforcementException e) {
			processException(SSOMessageResource.getMessage("5302"), e, response, HttpServletResponse.SC_FORBIDDEN);
		} catch(Exception e) {
			processException(SSOMessageResource.getMessage("5303"), e, response, HttpServletResponse.SC_NOT_FOUND);
		}
	}

}
