/*
 * @(#)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.message.SSOMessageResource;

import java.io.IOException;

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

import org.apache.log4j.Logger;
import org.opensaml.SAMLAssertion;
import org.opensaml.SAMLAuthenticationStatement;
import org.opensaml.SAMLSubject;
import org.opensaml.artifact.Artifact;

import info.dragonlady.sso.AssertionManager;
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 SSOBaseServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 7145203547625681108L;

	private String paramAuthClass = "auth-class"; 

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

	/**
	 * アーティファクト応答処理。
	 * 
	 * @param request HTTP要求オブジェクト
	 * @param response HTTP応答オブジェクト
	 * @see info.dragonlady.sso.servlet.SSOBaseServlet#process(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
	 */
	protected void process(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			Authenticator authenticator = (Authenticator)Class.forName(getInitParameter(paramAuthClass)).newInstance();
			String id = request.getParameter("id");
			if(authenticator.authenticate((HttpServletRequest)request)) {
				SAMLAssertion assertion = AssertionGenerator.generateAuthenticationAssertion(id, SAMLSubject.CONF_ARTIFACT, SAMLAuthenticationStatement.AuthenticationMethod_Unspecified);
				Artifact artifact = AssertionGenerator.generateArtifact(AssertionManager.getInstance().add(assertion));
				String artStr = artifact.encode();
				response.setContentType("text/plain");
				response.setContentLength(artStr.length());
				response.getWriter().write(artStr);
			} else {
				Logger.getRootLogger().info(SSOMessageResource.getMessage("5401", new Object[]{id}));
			}
		} catch(Exception e) {
			Logger.getRootLogger().error(SSOMessageResource.getMessage("5402"), e);
			if(e instanceof IOException) {
				throw (IOException)e;
			} else if(e instanceof ServletException) {
				throw (ServletException)e;
			} else {
				throw new ServletException(e);
			}
		}
	}

}
