/*
 * $Header: /home/cvspublic/jakarta-slide/proposals/wvcm/test/junit/src/org/apache/wvcm/test/RoleTest.java,v 1.3 2004/07/30 06:52:33 ozeigermann Exp $
 * $Revision: 1.3 $
 * $Date: 2004/07/30 06:52:33 $
 *
 * ====================================================================
 *
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 1999-2003 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution, if
 *    any, must include the following acknowlegement:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowlegement may appear in the software itself,
 *    if and wherever such third-party acknowlegements normally appear.
 *
 * 4. The names "The Jakarta Project", "Slide", and "Apache Software
 *    Foundation" must not be used to endorse or promote products derived
 *    from this software without prior written permission. For written
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache"
 *    nor may "Apache" appear in their names without prior written
 *    permission of the Apache Group.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 *
 * [Additional notices, if required by prior licensing conditions]
 *
 */
package org.apache.wvcm.test;

import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.wvcm.AccessControlElement;
import javax.wvcm.AccessControlElement.Privilege;
import javax.wvcm.Principal;
import javax.wvcm.Principal.Group;
import javax.wvcm.Principal.Role;
import javax.wvcm.PropertyNameList;
import javax.wvcm.PropertyNameList.NestedPropertyName;
import javax.wvcm.PropertyNameList.PropertyName;
import javax.wvcm.WvcmException;
import javax.wvcm.WvcmException.ReasonCode;
import junit.framework.Test;
import junit.framework.TestSuite;
import org.apache.wvcm.test.common.AbstractTest;
import org.apache.wvcm.test.common.util.ReasonCodeChecker;

/**
 * Test functionality given by javax.wvcm.Principal.Group
 *
 * @author <a href="mailto:javier.gallego@softwareag.com">Javier Gallego</a>
 * @version $Revision: 1.3 $
 */
public class RoleTest extends AbstractTest {
	
	private static Logger logger = Logger.getLogger("org.apache.wvcm.test.RoleTest");
	
	private static final PropertyNameList PRINCIPAL_PROPS_NAMEONLY = new PropertyNameList(
		new PropertyName[]{
			PropertyName.DISPLAY_NAME
		}
    );
    
    private static final PropertyNameList PRINCIPAL_PROPS = new PropertyNameList(
		new PropertyName[]{
			PropertyName.DISPLAY_NAME,
				PropertyName.GROUP_MEMBERSHIP
		}
    );
	
	private static final PropertyNameList GROUP_PROPS = new PropertyNameList(
		new PropertyName[]{
			PropertyName.DISPLAY_NAME,
				PropertyName.GROUP_MEMBER_LIST,
				PropertyName.GROUP_MEMBERSHIP
		}
    );
	
	private static final PropertyNameList GROUP_MEMBERS_DEEP = new PropertyNameList(
		new PropertyName[]{
			PropertyName.DISPLAY_NAME,
				new NestedPropertyName(
				PropertyName.GROUP_MEMBER_LIST, PRINCIPAL_PROPS_NAMEONLY)
		}
    );
	
	private String testUserName1 = "testU1";
	private String testGroupName1 = "testG1";
	private String testRoleName1 = "testR1";
	
	private Principal testUser1;
	private Group testGroup1;
	private Role testRole1;
    
	/**
	 * Default constructor. Initializes paths to user/group/roles folders.
	 *
	 * @param    testName            Name of the test.
	 *
	 * @throws   Exception
	 *
	 */
    public RoleTest(String testName) throws Exception {
		super(testName);
    }
    
    /**
	 * Creates a TestSuite corresponding to this class.
	 *
	 * @return   a Test
	 */
    public static Test suite() {
		return new TestSuite(RoleTest.class);
    }
    
    /**
	 * Start test suite contained in this class using the text interface. If a
	 * parameter is passed, it will use it as a test name and run only that test
	 * case.
	 *
	 * @param args   commandline options (first argument = test method name to run)
	 *
	 * @throws   Exception
	 */
    public static void main( String[] args ) throws Exception{
		if (args.length == 1) {
			TestSuite testSuite = new TestSuite();
			testSuite.addTest(new RoleTest(args[0]));
			junit.textui.TestRunner.run(testSuite);
		}
		else {
			junit.textui.TestRunner.run( suite() );
		}
    }
    
    /**
	 * Common test setup.
	 *
	 * @throws   Exception
	 */
    protected void setUp() throws Exception {
		super.setUp ();
    }
    
    /**
	 * Tears down the fixture, for example, close a network connection.
	 * This method is called after a test is executed.
	 *
	 * @throws   Exception
	 */
    protected void tearDown() throws Exception {
    }
	
	/**
	 * <ul>
	 * <li>Create a Principal.Role.
	 * <li>Check if creation has been successful.
	 *
	 * @throws Exception
	 */
	public void testDoCreateResource() throws Exception {
		testRole1 = createRole(testRoleName1, true);
	}
	
	/**
	 * <ul>
	 * <li>Create a Principal.Role.
	 * <li>Check that the role is empty.
	 *
	 * @throws Exception
	 */
	public void testGetGroupMemberListEmpty() throws Exception {
		// Create a Role.
		testRole1 = createRole(testRoleName1, true);
		
		// Get the GROUP_MEMBER_LIST property and check it is 0.
		testRole1 = (Role)testRole1.doReadProperties(GROUP_PROPS);
		
		List members = testRole1.getGroupMemberList();
		
		assertEquals("Unexpected members in the newly created role.",
					 0,
					 members.size());
	}
	
	/**
	 * <ul>
	 * <li>Create a Principal.Role.
	 * <li>Delete the location of the role.
	 * <li>Try to get or set the role member list.
	 *
	 * @throws Exception
	 */
	public void testUseRoleDeleted() throws Exception {
		testRole1 = createRole(testRoleName1, true);
		
		testRole1.doUnbind();
		
		try {
			testRole1 = (Role)testRole1.doReadProperties(GROUP_PROPS);
			fail("WvcmException should have been thrown when trying to work with"
				 + " a deleted resource.");
		}
		catch (WvcmException expected) {
			if(logger.isLoggable(Level.CONFIG))
				logger.config("Exception Message:\n" + expected.getMessage());
			assertEquals("Unexpected Exception thrown.",
						 ReasonCode.NOT_FOUND,
						 expected.getReasonCode());
		}
	}
	
	/**
	 * <ul>
	 * <li>Create a Principal.Role.
	 * <li>Create some users and add them to it.
	 * <li>Get the role member list.
	 * <li>Check list for correctness.
	 * <li>Create one group and add it to the role.
	 * <li>Get the role member list again.
	 * <li>Check list once more.
	 * <li>Create another role and add it to the initial role.
	 * <li>Get and check the member list one last time.
	 *
	 * @throws Exception
	 */
	public void testSetGetRoleMemberListNotEmpty() throws Exception {
		List members;
		int numberOfUsers = 5;
		// create users and initialize.
		Principal testUser[] = new Principal[numberOfUsers];
		for (int i = 0; i < numberOfUsers; i++) {
			testUser[i] = createUser(testUserName1.concat("_").
									 concat(String.valueOf(i)), true);
		}
		testRole1 = createRole(testRoleName1, true);
		testRole1 = (Role)testRole1.doReadProperties(GROUP_PROPS);
		members = testRole1.getGroupMemberList();
		assertEquals("Unexpected members in the newly created role.",
					 0,
					 members.size());
		
		
		for (int i = 0; i < numberOfUsers; i++) {
			members.add(testUser[i]);
		}
		testRole1.setGroupMemberList(members);
		testRole1.doWriteProperties();
		
		// Check that the role member list contains the new users.
		testRole1 = (Role)testRole1.doReadProperties(GROUP_PROPS);
		members = testRole1.getGroupMemberList();
		assertEquals("Unexpected number of members in role.",
					 numberOfUsers,
					 members.size());
		
		Role secondRole = createRole(testRoleName1 + "Second", true);
		members.add(secondRole);
		testRole1.setGroupMemberList(members);
		testRole1.doWriteProperties();
		
		// Check that the role member list contains the new users.
		testRole1 = (Role)testRole1.doReadProperties(GROUP_PROPS);
		members = testRole1.getGroupMemberList();
		assertEquals("Second Role has not been added to the role.",
					 numberOfUsers + 1,
					 members.size());
		
		// TODO: CHECK IF GROUP HAS BEEN ADDED TO THE ROLE.
		
		fail("Missing implementation of group part.");
		//
		//		// Create group.
		//		testGroup1 = createGroup(testGroupName1, true);
		//
		//		// make G1 a member of R1
		//        testRole1 = (Role)testRole1.doReadProperties(GROUP_PROPS);
		//        members = testRole1.getGroupMemberList();
		//        members.add(testGroup1);
		//        testRole1.doWriteProperties();
	}
	
	/**
	 * <ul>
	 * <li>Create a Principal.Role.
	 * <li>Try to set the role as a member of itself.
	 * <li>Exception should be thrown.
	 *
	 * @throws Exception
	 */
	public void testSetRoleMemberListItself() throws Exception {
		testRole1 = createRole(testRoleName1, true);
		
		testRole1 = (Role)testRole1.doReadProperties(GROUP_PROPS);
		List members = testRole1.getGroupMemberList();
		assertEquals("Unexpected number of members in role.",
					 0,
					 members.size());
		
		members.add(testRole1);
		testRole1.setGroupMemberList(members);
		
		try {
			testRole1.doWriteProperties();
			fail("Expected WvcmException (FORBIDDEN) not thrown.");
		}
		catch (WvcmException expected) {
			if(logger.isLoggable(Level.CONFIG))
				logger.config("Exception Message:\n"
							  + expected.getMessage());
			System.out.println(ReasonCodeChecker.getReasonCodeAsString(expected));
			assertEquals("Unexpected ReasonCode received.",
						 ReasonCode.FORBIDDEN,
						 expected.getReasonCode());
		}
	}
	
	/**
	 * <ul>
	 * <li>Create a Principal and a Role.
	 * <li>Add the role to the principal.
	 * <li>Try to delete the role.
	 * <li>Check result.
	 *
	 * @throws Exception
	 */
	public void testDeleteRoleWithUserMapping() throws Exception {
		String testRoleName = "testDeleteRoleWithUserMappingRole";
		String resxName = "testDRWUMResource.xml";
		location = provider.location(rootFolderPath() + "/" + resxName);
		resource = createControllableResource(location);
		testRole1 = createRole(testRoleName, true);
		
		// Create privilege for the user.
		String privilegeWritePath = contextPath()
			.concat("/").concat(privilegesFolderName)
			.concat("/").concat("testDRWUMAction");
		location = provider.location(privilegeWritePath);
		Privilege testWritePriv = createPrivilege(location);
		List listWritePriv = new ArrayList();
		listWritePriv.add(testWritePriv);
		
		AccessControlElement testACE = new AccessControlElement(testRole1, listWritePriv, true);
		List testACL = new ArrayList();
		testACL.add(testACE);
		// add the ACL to the resource.
		resource.doWriteAccessControlList(testACL);
		
		// Delete the user should create an exception.
		try {
			testRole1.doUnbind();
			fail("Expecting a CANNOT_UNBIND_RESOURCE exception.");
		}
		catch (WvcmException expected) {
			assertEquals("Unexpected reason for the thrown exception.",
						 "CANNOT_UNBIND_RESOURCE",
						 ReasonCodeChecker.getReasonCodeAsString(expected));
		}
		
		testACL = new ArrayList();
		resource.doWriteAccessControlList(testACL);
		
		try {
			testRole1.doUnbind();
			assertFalse(resourceExistsOnServer(testRole1.location().string()));
		}
		catch (WvcmException unexpected) {
			fail("Exception should have not been thrown:\n"
				 + unexpected.getMessage());
		}
	}
	
	/**
	 * <ul>
	 * <li>Create a Principal.Role.
	 * <li>Create a user and add it to the role.
	 * <li>Create an empty list and set it as member list.
	 * <li>Get the member list and check it.
	 *
	 * @throws Exception
	 */
	// TODO: CHECK HOW THIS SHOULD WORK. MEMBERS BEFORE ARE DELETED OR ADDED...
	public void testSetEmptyMemberList() throws Exception {
		fail("Not Implemented.");
	}
	
	/**
	 * <ul>
	 * <li>Create a test group and a test role.
	 * <li>Add group to the role.
	 * <li>Check that the group belongs to the role and that the role contains
	 * the group.
	 * <li>Create again (overwriting) the role.
	 * <li>Check if group props still contain the role.
	 * <li>Check if role properties contain the group.
	 *
	 * @throws Exception
	 */
	public void testOverwriteRole() throws Exception {
		fail("Not Implemented.");
	}
	
	/**
	 * <ul>
	 * <li>Create a Role.
	 * <li>Create one user and one group, add the user to the group and the role,
	 * and add the user to the group too.
	 * <li>Copy it to a valid location.
	 * <li>Check role contents.
	 *
	 * @throws Exception
	 */
	public void testDoCopyValid() throws Exception {
		fail("Not Implemented.");
	}
	
	/**
	 * <ul>
	 * <li>Create a role.
	 * <li>Try to copy the role to an invalid location.
	 * <li>Exception should appear.
	 *
	 * @throws Exception
	 */
	public void testDoCopyInvalid() throws Exception {
		fail("Not Implemented.");
	}
}

