/*
 * $Header: /home/cvspublic/jakarta-slide/proposals/wvcm/test/junit/src/org/apache/wvcm/test/PrincipalTest.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.Iterator;
import java.util.List;
import javax.wvcm.AccessControlElement;
import javax.wvcm.AccessControlElement.Privilege;
import javax.wvcm.Folder;
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 junit.framework.Test;
import junit.framework.TestSuite;
import org.apache.wvcm.test.common.AbstractTest;
import org.apache.wvcm.test.common.util.ReasonCodeChecker;

/**
 * Tests javax.wvcm.Principal.
 *
 * @author <a href="mailto:peter.nevermann@softwareag.com">Peter Nevermann</a>
 * @version $Revision: 1.3 $
 */
public class PrincipalTest extends AbstractTest {
    
    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 PrincipalTest(String testName) throws Exception {
        super(testName);
    }
    
    /**
     * Creates a TestSuite corresponding to this class.
     *
     * @return   a Test
     */
    public static Test suite() {
        return new TestSuite(PrincipalTest.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 PrincipalTest(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 {
    }
    
    // TODO: CHECK IF SERVER NEEDS TIME AFTER CREATION OF PRINCIPALS. ADD DELAY IN TESTS.
    
    /**
     * <ul>
     * <li>Creates a Principal (deleting it previously).
     * <li>Creates a Group (deleting it previously).
     * <li>Creates a Role (deleting it previously).
     * <li>Check creation was successful..
     *
     * @throws   Exception
     *
     */
    public void testDoCreateResource() throws Exception {
        createUser(testUserName1, true);
    }
    
    /**
     * <ul>
     * <li>Creates a User + Group + Role.
     * <li>Put testUser inside testGroup.
     * <li>Add testGroup to testRole.
     * <li>
     *
     * @throws   Exception
     *
     */
    public void testGetGroupMemberList() throws Exception {
        List members;
        // TODO: CHECK HOW TO ADD USER TO GROUPS, GROUPS TO ROLES, ETC...
        testUser1 = createUser(testUserName1, true);
        testGroup1 = createGroup(testGroupName1, true);
        testRole1 = createRole(testRoleName1, true);
        
        // make U1 a member of G1
        testGroup1 = (Group)testGroup1.doReadProperties(GROUP_PROPS);
        members = testGroup1.getGroupMemberList();
		int numberOfMembersBefore = members.size();
        members.add(testUser1);
        testGroup1.doWriteProperties();
        
        // TODO: CHECK IF USER HAS BEEN ADDED TO THE GROUP.
		// Check members of group1 again. Or maybe through the user's getGroupMembership
		System.out.println("list before = " + members.hashCode());
		members = testGroup1.getGroupMemberList();
		System.out.println("list after = " + members.hashCode());
		assertEquals("Unexpected number of members of the group.",
					 numberOfMembersBefore + 1,
					 members.size());
		boolean isUserInGroup = false;
		for (int i = 0; i < members.size(); i++) {
			System.out.println(members.get(i).getClass().toString());
		}
		
		// todo: finish implementing check.
			
        
        // make G1 a member of R1
        testRole1 = (Role)testRole1.doReadProperties(GROUP_PROPS);
        members = testRole1.getGroupMemberList();
        members.add(testGroup1);
        testRole1.doWriteProperties();
        
        // TODO: CHECK IF USER HAS BEEN ADDED TO THE ROLE.
    }
	
	/**
	 * <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 testDeleteUserWithUserMapping() throws Exception {
		String testRoleName = "testDeleteRoleWithUserMappingRole";
		String testUserName = "testDRWUMUser";
		String resxName = "testDRWUMResource.xml";
		location = provider.location(rootFolderPath() + "/" + resxName);
		resource = createControllableResource(location);
		testUser1 = createUser(testUserName, 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(testUser1, 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 {
			testUser1.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 {
			testUser1.doUnbind();
			assertFalse(resourceExistsOnServer(testUser1.location().string()));
		}
		catch (WvcmException unexpected) {
			fail("Exception should have not been thrown:\n"
				 + unexpected.getMessage());
		}
	}
    
    /**
     * <ul>
     * <li>Creates some testUsers + Group.
     * <li>Put testUsers inside testGroup.
     * <li>Check that the users belong to the test group.
     * <li>
     * @throws   Exception
     *
     */
    public void testListUsersWithGroupMembership() throws Exception {
        // TODO: ADD CREATION OF TEST GROUP AND TEST USERS.
        // THIS TESTCASE SHOULD NOT DEPEND ON ANY PREVIOUS ONES.
        
        // TODO: TURN THE SYSTEM OUT PRINTLNS INTO ASSERT CHECKS.
        // TODO: CLEAN OUT THIS TEST CASE. IT CONTAINS TOO MUCH IN IT.
        location = provider.location(usersFolderPath);
        Folder uf = location.folder();
        Iterator users = uf.doReadMemberList(PRINCIPAL_PROPS, false);
        System.out.println("\nList of all users with group membership:");
        if (!users.hasNext()) {
            System.out.println("*** no users ***");
        }
        while (users.hasNext()) {
            Principal u = (Principal)users.next();
            System.out.println("- "+u.getDisplayName()+" ["+u.location().string()+"]");
            System.out.println("  Group membership:");
            Iterator m = u.getGroupMembership().iterator();
            if (!m.hasNext()) {
                System.out.println("  *** empty ***");
            }
            while (m.hasNext()) {
                Principal.Group g = (Principal.Group)m.next();
                g = (Group)g.doReadProperties(GROUP_PROPS);
                System.out.println("  + : "+g.getDisplayName()+" ["+g.location().string()+"]");
            }
        }
    }
    
    /**
     * <ul>
     * <li>Create some test users and one test group.
     * <li>Get list of users with group membership.
     * <li>List should be empty.
     *
     * @throws Exception
     */
    public void testListUsersWithNoGroupMembership() throws Exception {
        fail("Not Implemented.");
    }
    
    /**
     * <ul>
     * <li>Create a test user, group and role.
     * <li>Add the user to the group and to the role.
     * <li>Check props of test user (should be member of group and role).
     * <li>Create again the user (overwriting it).
     * <li>Check that the user does not belong any more to the group/role.
     *
     * @throws Exception
     */
    public void testOverwritePrincipal() throws Exception {
        fail("Not Implemented.");
		
		// TODO: CHECK IF IMPLEMENTATION WORKS.
		List members;
		testUser1 = createUser(testUserName1, true);
        testGroup1 = createGroup(testGroupName1, true);
        testRole1 = createRole(testRoleName1, true);
		
		// make U1 a member of G1
        testGroup1 = (Group)testGroup1.doReadProperties(GROUP_PROPS);
        members = testGroup1.getGroupMemberList();
		int numberOfMembersBefore = members.size();
        members.add(testUser1);
        testGroup1.doWriteProperties();
		
		// make U1 a member of R1
        testRole1 = (Role)testRole1.doReadProperties(GROUP_PROPS);
        members = testRole1.getGroupMemberList();
        members.add(testUser1);
        testRole1.doWriteProperties();
		
		// check groupmembership of the user.
		testUser1 = (Principal)testUser1.doReadProperties(GROUP_PROPS);
		members = testUser1.getGroupMembership();
		
		// TODO: ADD CHECK FOR GROUP-MEMBERSHIP.
    }
    
    // TODO: ADD MORE TESTS ACCORDING TO LATEST INFO ON PRINCIPALS.
    // TODO: COPY, BIND...
        
}


