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

import info.dragonlady.sso.SSOConfig;
import info.dragonlady.sso.helper.CooperationAuthenticator;
import info.dragonlady.sso.helper.LoginManager;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;


import org.apache.cactus.ServletTestCase;
import org.apache.cactus.WebRequest;

/**
 * CooperationAuthenticator クラステストケース。
 * 
 * @author Hiroshi.Ebata(INFOCITY)
 * @version $Revision: 1.0 $ $Date: 2006/12/12 2:44:19 $
 */
public class CooperationAuthenticatorTest extends ServletTestCase {

	private String id = "00000000000e";

	/**
	 * @param arg0
	 */
	public CooperationAuthenticatorTest(String arg0) {
		super(arg0);
	}

	/* (non-Javadoc)
	 * @see junit.framework.TestCase#setUp()
	 */
	protected void setUp() throws Exception {
		super.setUp();
	}

	/* (non-Javadoc)
	 * @see junit.framework.TestCase#tearDown()
	 */
	protected void tearDown() throws Exception {
		super.tearDown();
	}

	/**
	 * {@link info.dragonlady.sso.helper.CooperationAuthenticator#CooperationAuthenticator()} のためのテスト・メソッド。
	 */
	public final void testCooperationAuthenticator() {
		try {
			new CooperationAuthenticator();
		} catch(Exception e) {
			assertTrue(e.toString(), false);
		}
	}

	/**
	 * @param theRequest
	 */
	public final void beginAuthenticate(WebRequest theRequest) {
		try {
			theRequest.addParameter(SSOConfig.getLoginKey(), id, WebRequest.GET_METHOD);
		} catch(Exception e) {
			assertTrue(e.toString(), false);
		}
	}

	/**
	 * {@link info.dragonlady.sso.helper.CooperationAuthenticator#authenticate(javax.servlet.http.HttpServletRequest)} のためのテスト・メソッド。
	 */
	public final void testAuthenticate() {
		try {
//			login();
//			LoginManager.getInstance().remove(id);
//			assertTrue(!LoginManager.getInstance().isLoggedIn(id));
			LoginManager.getInstance().add(id, request.getSession().getId());
			request.getSession().setAttribute(SSOConfig.getLoginKey(), id);

			CooperationAuthenticator authenticator = new CooperationAuthenticator();
			assertTrue(authenticator.authenticate(request));

			assertTrue(LoginManager.getInstance().isLoggedIn(id));
			LoginManager.getInstance().remove(id);
			session.invalidate();
		} catch(Exception e) {
			assertTrue(e.toString(), false);
		}
	}

	private void login() throws IOException {
		String urlStr = "http://localhost:8080/auth/SiteTransfer?TARGET=http%3A%2F%2Flocalhost%3A8080%2Fportal%2Ftop.html&termid=1&parent=parentAttribute&accountid=" + id;
		InputStream is = null;
		try {
			URL url = new URL(urlStr);
			HttpURLConnection con = (HttpURLConnection)url.openConnection();
			is = con.getInputStream();
			byte[] b = new byte[is.available()];
			is.read(b);
		} finally {
			if(is != null) {
				try {
					is.close();
				} catch(Exception e) {
				}
			}
		}
	}

}
