/*
 * $Header: /home/cvspublic/jakarta-slide/proposals/tamino/testsuite/junit/urm/org/apache/slide/urm/test/roleadmin/TestURMRoleAdministrator.java,v 1.3 2004/07/30 06:52:22 ozeigermann Exp $
 * $Revision: 1.3 $
 * $Date: 2004/07/30 06:52:22 $
 *
 * ====================================================================
 *
 * Copyright 1999-2004 The Apache Software Foundation.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.apache.slide.urm.test.roleadmin;

import java.io.FileInputStream;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.apache.slide.urm.URMForbiddenException;
import org.apache.slide.urm.authenticator.URMAdministrator;
import org.apache.slide.urm.authenticator.URMAuthenticator;
import org.apache.slide.urm.authenticator.rolemanager.URMRole;
import org.apache.slide.urm.authenticator.userdb.URMUser;
import org.apache.slide.urm.common.URMConfigurator;
import org.apache.slide.urm.common.URMConstants;
import org.apache.slide.urm.common.URMInsertException;
import org.apache.slide.urm.common.URMPrincipal;
import org.apache.slide.urm.common.impl.URMConfiguratorXML;

/**
 * @author dk
 *
 * To change the template for this generated type comment go to
 * Window>Preferences>Java>Code Generation>Code and Comments
 */
public class TestURMRoleAdministrator extends TestCase {

    private static final String FACTORY_CLASS_ATTRIBUTE_NAME = "Class";

    public TestURMRoleAdministrator(String name) {
        super(name);
    }

    public static Test suite() {
        return new TestSuite(TestURMRoleAdministrator.class);
    }

    public void test_create() throws Exception {
        FileInputStream fis =
            new FileInputStream("testsuite/junit/ConfigurationLdap.xml");
        URMConfigurator conf = new URMConfiguratorXML(fis);
        fis.close();
        conf = (URMConfigurator) (conf.getSubConfigurators().get("Authenticator"));
        //System.out.println(conf.toString());

        URMAuthenticator authenticator = URMAuthenticator.newInstance(conf);
        URMPrincipal princ =
            authenticator.authenticateUser(
                "testuser01",
                "testuser01".toCharArray());
        princ.setActiveRole(URMConstants.URM_ADMIN_ROLE);

        System.out.println("\n" + princ.getProperties());

        URMAdministrator mAdministrator = princ.getURMAdministrator();

        try {
            /*
            // TESTTEST retrieve all nested roles
            URMRole r1 = mAdministrator.getRole("Role1");
            Set s1 = r1.getAllAncestors();
            Iterator i1 = s1.iterator();
            while (i1 != null && i1.hasNext()) {
                System.out.println("Role1 has Ancestor: " + i1.next().toString());
            }
            
            URMRole r2 = mAdministrator.getRole("Role34");
            Set s2 = r2.getAllAncestors();
            Iterator i2 = s2.iterator();
            while (i2 != null && i2.hasNext()) {
                System.out.println("Role34 has Ancestor: " + i2.next().toString());
            }
            
            URMRole r3 = mAdministrator.getRole("Role1234");
            Set s3 = r3.getAllAncestors();
            Iterator i3 = s3.iterator();
            while (i3 != null && i3.hasNext()) {
                System.out.println("Role1234 has Ancestor: " + i3.next().toString());
            }
            
            URMRole r4 = mAdministrator.getRole("Role15");
            Set s4 = r4.getAllAncestors();
            Iterator i4 = s4.iterator();
            while (i4 != null && i4.hasNext()) {
                System.out.println("Role15 has Ancestor: " + i4.next().toString());
            }
            */
            // Create roles
            URMRole role1 = mAdministrator.createRole("TestRole1");
            URMRole role2 = mAdministrator.createRole("TestRole2");
            URMRole role3 = mAdministrator.createRole("TestRole3");
            
            // the following should fail
            try {
                URMRole roleX = mAdministrator.createRole("TestRole3");
            } catch (URMForbiddenException ue) {
                System.out.println("Exception caught correctly (createUser)");
            }

            role3.addAncestor("TestRole1");
            // the following should fail:
            try {
                role3.addAncestor("XXXX");
            } catch (URMForbiddenException ue) {
                System.out.println("Exception caught correctly (addAncestor)");
            }

            // Create User/Role Mappings
            role1.addUserLink("TestUser1", null);
            role2.addUserLink("TestUser2", "MyDomain");
            role3.addUserLink("TestUser3", "TestDomain");
            // the following should fail, because he's already in the list
            try {
                role3.addUserLink("TestUser3", "TestDomain");
            } catch (URMInsertException ue) {
                System.out.println("Exception caught correctly (addUserLink)");
            }

            // Create User Properties
            Properties props1 = new Properties();
            Properties props2 = new Properties();
            Properties props3 = new Properties();
            props1.setProperty("TestKey1", "TestValue1");
            props1.setProperty("TestKey2", "TestValue2");
            props1.setProperty("TestKey3", "TestValue3");
            props2.setProperty("Test222Key", "Test222Value");
            props3.setProperty("Test333Key", "Test333Value");

            role1.setProperties(props1);
            role2.setProperties(props2);
            role3.setProperties(props3);

            role1.setPredefinedAction("Action1", Boolean.TRUE);
            role1.setPredefinedAction("Action2", Boolean.TRUE);
            role1.setPredefinedAction("ActionForbid", Boolean.FALSE);

            // the following should fail
            try {
                role1.setPredefinedAction("Action2", Boolean.TRUE);
            } catch (URMInsertException e) {
                System.out.println(
                    "Exception caught correctly (setPredefinedAction)");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("createRole returned");

    }

    public void test_query() throws Exception {

        FileInputStream fis =
            new FileInputStream("testsuite/junit/ConfigurationLdap.xml");
        URMConfigurator conf = new URMConfiguratorXML(fis);
        fis.close();
        conf = (URMConfigurator) (conf.getSubConfigurators().get("Authenticator"));
        //System.out.println(conf.toString());

        URMAuthenticator authenticator = URMAuthenticator.newInstance(conf);
        URMPrincipal princ =
            authenticator.authenticateUser(
                "testuser01",
                "testuser01".toCharArray());
        princ.setActiveRole(URMConstants.URM_ADMIN_ROLE);

        System.out.println("\n" + princ.getProperties());

        URMAdministrator mAdministrator = princ.getURMAdministrator();

        URMRole role1 = mAdministrator.getRole("TestRole1");
        URMRole role2 = mAdministrator.getRole("TestRole2");
        URMRole role3 = mAdministrator.getRole("TestRole3");

        Set enum3 = role3.getAncestors();
        Iterator iter3 = enum3.iterator();
        while (iter3.hasNext()) {
            System.out.println(
                "Ancestors of TestRole3: " + ((URMRole)iter3.next()).getName().toString());
        }

        Set enum2 = role2.getUserMapping();
        Iterator iter2 = enum2.iterator();
        while (iter2.hasNext()) {
            System.out.println(
                "User mapping of TestRole2: " + ((URMUser)iter2.next()).getName().toString());
        }

        Set enum1 = role1.getRolesOfAncestor();
        Iterator iter1 = enum1.iterator();
        while (iter1.hasNext()) {
            System.out.println(
                "Ancestors of TestRole1: " + ((URMRole)iter1.next()).getName().toString());
        }

        Map enum4 = role1.getPredefinedActions();
        Iterator iter4 = enum4.entrySet().iterator();
        while (iter4.hasNext()) {
            System.out.println(
                "Predefined actions of TestRole1: " + iter4.next().toString());
        }

        System.out.println("queryRole returned");

    }

    public void test_roleProfile() throws Exception {
        FileInputStream fis =
            new FileInputStream("testsuite/junit/ConfigurationLdap.xml");
        URMConfigurator conf = new URMConfiguratorXML(fis);
        fis.close();
        conf = (URMConfigurator) (conf.getSubConfigurators().get("Authenticator"));
        //System.out.println(conf.toString());

        URMAuthenticator authenticator = URMAuthenticator.newInstance(conf);
        URMPrincipal princ =
            authenticator.authenticateUser(
                "testuser01",
                "testuser01".toCharArray());
        princ.setActiveRole(URMConstants.URM_ADMIN_ROLE);

        System.out.println("\n" + princ.getProperties());

        // URMAclValidator mAclValidator = URMAclValidator.newInstance();

        //int ret = mAclValidator.accessCheck(princ, "UniqueId001", 4711);

        System.out.println("roleProfile returned: " /* + ret */
        );

    }

    public void test_delete() throws Exception {
        FileInputStream fis =
            new FileInputStream("testsuite/junit/ConfigurationLdap.xml");
        URMConfigurator conf = new URMConfiguratorXML(fis);
        fis.close();
        conf = (URMConfigurator) (conf.getSubConfigurators().get("Authenticator"));
        //System.out.println(conf.toString());

        URMAuthenticator authenticator = URMAuthenticator.newInstance(conf);
        URMPrincipal princ =
            authenticator.authenticateUser(
                "testuser01",
                "testuser01".toCharArray(),
                null);
        princ.setActiveRole(URMConstants.URM_ADMIN_ROLE);

        System.out.println("\n" + princ.getProperties());

        try {

            URMAdministrator mAdministrator = princ.getURMAdministrator();

            URMRole role1 = mAdministrator.getRole("TestRole1");
            URMRole role2 = mAdministrator.getRole("TestRole2");
            URMRole role3 = mAdministrator.getRole("TestRole3");
            // this should fail
            try {
                mAdministrator.deleteRole("TestRole1");
            } catch (URMForbiddenException e) {
                System.out.println("Exception caught correcty (deleteRole)");
            }

            role1.deleteUserLink("TestUser1", null);
            role3.deleteAncestor("TestRole1");
            // now it should work
            mAdministrator.deleteRole("TestRole1");
            role2.deleteUserLink("TestUser2", "MyDomain");
            try {
                mAdministrator.deleteRole("TestRole3");
            } catch (URMForbiddenException e) {
                System.out.println("Exception caught correctly: delete role");
            }
            mAdministrator.deleteRole("TestRole2");
            role3.deleteUserLink("TestUser3", "TestDomain");
            mAdministrator.deleteRole("TestRole3");
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("deleteRole returned");

    }

    public static void main(String[] args) throws Exception {
        String[] testCaseName =
            { "-noloading", TestURMRoleAdministrator.class.getName()};

        junit.textui.TestRunner.main(testCaseName);
    }
}
