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

import info.dragonlady.sso.AssertionManager;
import info.dragonlady.sso.SSOConfig;
import info.dragonlady.sso.SSOException;
import info.dragonlady.sso.SiteTransfer;
import info.dragonlady.sso.util.AssertionGenerator;

import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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

import org.opensaml.SAMLAssertion;
import org.opensaml.SAMLAuthenticationStatement;
import org.opensaml.SAMLSubject;
import org.opensaml.artifact.Artifact;


/**
 * サイト転送処理サーブレット。
 * 
 * @author Hiroshi.Ebata(INFOCITY)
 * @version $Revision: 1.0 $ $Date: 2006/10/19 17:38:54 $
 */
public class SiteTransferServlet extends HttpServlet {

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

	/* (非 Javadoc)
	 * @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 {
			// TODO id, authId, attributes は、ユーザ管理方法に合わせて取得・実装すること
			List<Artifact> artifacts = Collections.emptyList();
			// ユーザの認証ID
			String authId = (String)request.getSession().getAttribute("user_id"); // セッション内から認証IDを取得（ダミー）
			SAMLAssertion authAssertion = AssertionGenerator.generateAuthenticationAssertion(authId, SAMLSubject.CONF_ARTIFACT, SAMLAuthenticationStatement.AuthenticationMethod_Unspecified);
			artifacts.add(AssertionGenerator.generateArtifact(AssertionManager.getInstance().add(authAssertion)));

			// ユーザの属性情報
			List attributeNames = SSOConfig.getSAMLAttributeList(); // アサーションに必要な属性名を取得
			Map<String, List<String>> attributes = new HashMap<String, List<String>>();
			for(int i = 0; i < attributeNames.size(); i++) {
				String key = attributeNames.get(i).toString();
				attributes.put(key, Arrays.asList("val_" + key)); // 属性値はダミー
			}
			SAMLAssertion attrAssertion = AssertionGenerator.generateAttributeAssertion(authId, attributes);
			artifacts.add(AssertionGenerator.generateArtifact(AssertionManager.getInstance().add(attrAssertion)));

			// 認証アサーション作成及び目的サイトへのリダイレクト
			SiteTransfer st = new SiteTransfer(request, response);
			st.forward(artifacts, null);
		} catch(SSOException e) {
			throw new ServletException(e);
		} catch(Exception e) {
			throw new ServletException(e);
		}
	}

}
