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

import info.dragonlady.sso.AssertionManager;
import info.dragonlady.sso.ReceiverResource;
import info.dragonlady.sso.SSOConfig;
import info.dragonlady.sso.SSOConstants;
import info.dragonlady.sso.SiteTransfer;
import info.dragonlady.sso.util.AssertionGenerator;
import info.dragonlady.sso.util.ResourceParseException;

import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


import org.apache.cactus.ServletTestCase;
import org.apache.cactus.WebRequest;
import org.apache.cactus.WebResponse;
import org.opensaml.SAMLAssertion;
import org.opensaml.SAMLAuthenticationStatement;
import org.opensaml.SAMLSubject;
import org.opensaml.artifact.Artifact;

/**
 * SiteTransferクラスのテストケース
 * 
 * @author Hiroshi.Ebata(INFOCITY)
 * @version $Revision: 1.2 $ $Date: 2005/11/25 06:52:41 $
 */
public class SiteTransferTest extends ServletTestCase {

	/**
	 * Constructor for SiteTransferTest.
	 * @param arg0
	 */
	public SiteTransferTest(String arg0) {
		super(arg0);
	}

	/*
	 * @see TestCase#setUp()
	 */
	protected void setUp() throws Exception {
		super.setUp();
	}

	/*
	 * @see TestCase#tearDown()
	 */
	protected void tearDown() throws Exception {
		super.tearDown();
	}

	public final void beginForward(WebRequest theRequest) {
		// ターゲットサイトを指定（ダミーURL）
		theRequest.addParameter(SSOConstants.NAME_TARGET, "http://172.16.3.74:8080/sso_test/target.html", WebRequest.GET_METHOD);
	}

	/**
	 * レシーバへリダイレクション成功
	 * 
	 * Test method for 'info.dragonlady.sso.SiteTransfer.forward(List<SAMLArtifact>, Map<String, String>)'
	 */
	public final void testForward() {
		try {
			String userId = "dummyUserId";
			SAMLAssertion assertion1 = AssertionGenerator.generateAuthenticationAssertion(userId, SAMLSubject.CONF_ARTIFACT, SAMLAuthenticationStatement.AuthenticationMethod_Unspecified);
			Artifact artifact1 = AssertionGenerator.generateArtifact(AssertionManager.getInstance().add(assertion1));
			SAMLAssertion assertion2 = AssertionGenerator.generateAttributeAssertion(userId, getAttributes());
			Artifact artifact2 = AssertionGenerator.generateArtifact(AssertionManager.getInstance().add(assertion2));

			SiteTransfer st = new SiteTransfer(request, response);
			st.forward(Arrays.asList(new Artifact[]{artifact1, artifact2}), null);

			// アサーションが存在することを確認
			assertNotNull(AssertionManager.getInstance().get(ArtifactManager.getInstance().getHandle(artifact1.encode())));
			assertNotNull(AssertionManager.getInstance().get(ArtifactManager.getInstance().getHandle(artifact2.encode())));
		} catch(Exception e) {
			assertTrue(e.toString(), false);
		}
	}

	private final Map<String, List<String>> getAttributes() throws ResourceParseException {
		Map<String, List<String>> attributes = new HashMap<String, List<String>>();
		List keyList = SSOConfig.getSAMLAttributeList();
		for(int i = 0; i < keyList.size(); i++) {
			String key = keyList.get(i).toString();
			List<String> list = new ArrayList<String>();
			list.add("val_" + key);
			attributes.put(key, list);
		}
		return attributes;
	}

	public final void endForward(WebResponse theResponse) {
		try {
			// URL確認
			String expectedReceiver = ReceiverResource.getReceiver("172.16.3.74", "sso_test");
			String receiver = theResponse.getConnection().getHeaderField("Location");
			String[] str = receiver.split("\\?");
			assertTrue(expectedReceiver.equals(str[0]));
			String[] query = str[1].split("&");
			// TARGET,SAMLartの２パラメータ
			assertTrue(query.length == 3);
			for(int i = 0; i < query.length; i++) {
				String[] s = query[i].split("=");
				if(s[0].equals(SSOConstants.NAME_TARGET)) {
					// ターゲット確認
					String expectedTarget = "http://172.16.3.74:8080/sso_test/target.html";
					String target = URLDecoder.decode(s[1], "UTF-8");
					assertTrue(expectedTarget.equals(target));
				} else if(s[0].equals(SSOConstants.NAME_SAMLART)) {
					// artifact文字列存在確認
					assertTrue(s[1] != null && s[1].length() > 0);
				} else {
					assertTrue("param:"+s[0], false);
				}
			}
		} catch(Exception e) {
			assertTrue(e.toString(), false);
		}
	}

}
