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

import info.dragonlady.sso.helper.Authenticator;
import info.dragonlady.sso.helper.LoginManager;

import java.io.IOException;
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.artifact.Artifact;

import info.dragonlady.sso.SSOConfig;
import info.dragonlady.sso.util.AssertionGenerator;

/**
 * 要求パラメータで送られた認証IDがログオンしていれば、アサーションを作成しアーティファクトを応答するサーブレット。
 * 
 * @author Hiroshi.Ebata(INFOCITY)
 * @version $Revision: 1.0 $ $Date: 2006/12/01 13:19:50 $
 */
public class ArtifactResponderServlet extends HttpServlet {

	private String paramAuthClass = "auth-class"; 

	/**
	 * コンストラクタ。
	 */
	public ArtifactResponderServlet() {
	}

	/**
	 * サービス処理。
	 * 
	 * @param request HTTP要求オブジェクト
	 * @param response HTTP応答オブジェクト
	 * @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 {
			Authenticator authenticator = (Authenticator)Class.forName(getInitParameter(paramAuthClass)).newInstance();
			if(authenticator.authenticate((HttpServletRequest)request)) {
				// 値がからの属性情報を作成
				Map attributes = new HashMap();
				List list = SSOConfig.getSAMLAttributeList();
				for(int i = 0; i < list.size(); i++) {
					attributes.put(list.get(i), "");
				}
				String id = request.getParameter("id");
				Artifact artifact = AssertionGenerator.generateAssertion(request.getSession().getId(), id, attributes);
				String artStr = artifact.encode();
				response.setContentLength(artStr.length());
				response.getWriter().write(artStr);
			}
		} catch(Exception e) {
			e.printStackTrace();
			if(e instanceof IOException) {
				throw (IOException)e;
			} else if(e instanceof ServletException) {
				throw (ServletException)e;
			} else {
				throw new ServletException(e);
			}
		}
	}

}
