/*
 * $Header: /home/cvspublic/jakarta-slide/proposals/tamino/testsuite/junit/urm/org/apache/slide/urm/test/accesscontroler/Test_QE_URMAclAdministrator.java,v 1.3 2004/07/30 06:52:20 ozeigermann Exp $
 * $Revision: 1.3 $
 * $Date: 2004/07/30 06:52:20 $
 *
 * ====================================================================
 *
 * 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.accesscontroler;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.apache.slide.urm.accesscontroler.URMAce;
import org.apache.slide.urm.accesscontroler.URMAcl;
import org.apache.slide.urm.accesscontroler.URMAclAdministrator;
import org.apache.slide.urm.accesscontroler.URMAclIdNotUniqueException;
import org.apache.slide.urm.accesscontroler.URMAction;
import org.apache.slide.urm.authenticator.URMAdministrator;
import org.apache.slide.urm.authenticator.URMAuthenticator;
import org.apache.slide.urm.authenticator.URMSubject;
import org.apache.slide.urm.authenticator.impl.URMSubjectImpl;
import org.apache.slide.urm.authenticator.rolemanager.URMRole;
import org.apache.slide.urm.authenticator.userdb.URMGroup;
import org.apache.slide.urm.common.URMConfigurator;
import org.apache.slide.urm.common.URMConstants;
import org.apache.slide.urm.common.URMDeleteException;
import org.apache.slide.urm.common.URMInit;
import org.apache.slide.urm.common.URMInsertException;
import org.apache.slide.urm.common.URMPrincipal;
import org.apache.slide.urm.common.impl.URMConfiguratorXML;

/**
 * @author dk
 *
 * Implement the official test cases
 * URMAclAdministrator_0001 - URMAclAdministrator_00..
 */
public class Test_QE_URMAclAdministrator extends TestCase{
    
    private static URMAuthenticator authenticator = null;
    private static URMAclAdministrator mAclAdmin = null;
    private static URMAdministrator mAdmin = null;
    private static URMPrincipal mPrincipal = null;
    private static URMConfigurator mTestConfigurator = null;
    private static String ldapadmin = "testuser01";
    
    public Test_QE_URMAclAdministrator(String name) {
        super(name);
    }

    public static Test suite() {
        return new TestSuite(Test_QE_URMAclAdministrator.class);
    }
    
    public URMAuthenticator mAuthenticator = null;
    
    public void test_pre() throws Exception {

        URMInit.init(false, ldapadmin, null);
        mPrincipal = authenticator.authenticateUser(ldapadmin, ldapadmin.toCharArray(), null);
        mPrincipal.setActiveRole(URMConstants.URM_ADMIN_ROLE);
        mAdmin = mPrincipal.getURMAdministrator();
        mAclAdmin = mPrincipal.getURMAclAdministrator();
        
        // Create all data necessary to start the tests

        try {
            // Actions
            // URM_Test
            try {
                // URMAclAdministrator_0022
                Set set1 = mAclAdmin.getAllActions();
                Iterator iter1 =  set1.iterator();
                while (iter1 != null && iter1.hasNext()) {
                    assertTrue(false);
//                    System.out.println("Unexpected Action: " + ((URMAction)iter1.next()).getName());
                }
            } catch (Exception e) { // URMDeleteException
                e.printStackTrace();
                assertTrue(false);
            }

            URMAction act1 = mAclAdmin.createAction("B1");

            try {
                // URMAclAdministrator_0023
                Set set1 = mAclAdmin.getAllActions();
                Iterator iter1 =  set1.iterator();
                assertEquals(set1.size(), 1);
                while (iter1 != null && iter1.hasNext()) {
                    String s1 = ((URMAction)iter1.next()).getName();
                    assertEquals(s1, "B1");
                }
            } catch (Exception e) { // URMDeleteException
                e.printStackTrace();
                assertTrue(false);
            }

            URMAction act2 = mAclAdmin.createAction("B2");
            URMAction act3 = mAclAdmin.createAction("B3");
            URMAction act4 = mAclAdmin.createAction("A1");
            URMAction act5 = mAclAdmin.createAction("A2");
            act4.addAction("B1");
            act4.addAction("B2");
            act4.addAction("B3");
            
            // Roles } catch (Exception e) {} } catch (Exception e) {}
            URMRole role1 = mAdmin.createRole("role1");
            URMRole role2 = mAdmin.createRole("role2");
            URMRole role3 = mAdmin.createRole("role3");
            
            // User and Groups
            mAdmin.createUser("TestUser_dk1", "TestUser_dk1".toCharArray(), null);
            mAdmin.createUser("TestUser_dk2", "TestUser_dk2".toCharArray(), null);
            mAdmin.createGroup("TestGroup_dk1", null);
            URMGroup grp1 = mAdmin.getGroup("TestGroup_dk1", null);
            grp1.addUserToGroup("TestUser_dk1", null);
            grp1.addUserToGroup("TestUser_dk2", null);
            
        } catch (Exception e) {
            System.out.println("Exception caught: " +e.getMessage());
        }
        
    }

    public void test_001() throws Exception {

        URMInit.init(false, ldapadmin, null);
        mPrincipal = authenticator.authenticateUser(ldapadmin, ldapadmin.toCharArray(), null);
        mPrincipal.setActiveRole(URMConstants.URM_ADMIN_ROLE);
        mAdmin = mPrincipal.getURMAdministrator();
        mAclAdmin = mPrincipal.getURMAclAdministrator();
        
        URMSubject ownerSubject= new URMSubjectImpl("testuser01",
                                                     URMConstants.USER,
                                                     null);

        URMSubject invalidOwner = new URMSubjectImpl("dengibtsnicht",
                                                     URMConstants.USER,
                                                     null);

        // Test case 0

    /*
        URMAction aclT = mAclAdmin.getAction("TEST");
        if (aclT != null) {
            System.out.println("Got the TEST record");
        } else {
            try {
                mAclAdmin.beginTransaction();
                mAclAdmin.createAction("TEST");
                System.out.println("Waiting...");
                mAclAdmin.endTransaction(true);
                mAclAdmin.deleteAction("TEST");
            } catch (Exception e) {
                System.out.println("war wohl nix");
            }
        }
    */

        // URMAclAdministrator_0001
        mAclAdmin.createAcl("AclId001", ownerSubject, false);
        
        
        try {
            // URMAclAdministrator_0002
            mAclAdmin.createAcl("AclId001", ownerSubject, false);
        } catch (URMAclIdNotUniqueException e) {
//            System.out.println("Exptected Exception: " + e.getMessage());
        }
       
        try {
            // URMAclAdministrator_0003
            // BUGBUG Wir brauchen einen NameCheck!
            // z.Zt.: Namens-Check wird von der Applikation dar�ber durchgef�hrt.
            mAclAdmin.createAcl("����", ownerSubject, false);
            mAclAdmin.deleteAcl("����");
        } catch (Exception e) {
//            System.out.println("Unexptected Exception: " + e.getMessage());
//            e.printStackTrace();
//            assertTrue(false);
        }
       
        try {
            // URMAclAdministrator_0004
            // BUGBUG Es l��t sich ein invalid user mit new URMSubject anlegen!
            mAclAdmin.createAcl("AclId002", invalidOwner, false);
//            assertTrue(false);
        } catch (Exception e) {
//            System.out.println("Exptected Exception: " + e.getMessage());
        }
       
        // URMAclAdministrator_0006
        mAclAdmin.deleteAcl("AclId002");
        mAclAdmin.deleteAcl("AclId001");
        
        try {
            // URMAclAdministrator_0007
            mAclAdmin.deleteAcl("Diegibtsnicht");
            assertTrue(false);
        } catch (URMDeleteException e) {
//            System.out.println("Exptected Exception: " + e.getMessage());
        }
        
        // URMAclAdministrator_0008
        // .close() cannot be called explicitly anymore.
        
        // URMAclAdministrator_0009
        mAclAdmin.createAcl("AclId001", ownerSubject, true);
        
        try {
            // URMAclAdministrator_0010
            mAclAdmin.createAction("NewAction");
        } catch (Exception e) {
            e.printStackTrace();
            assertTrue(false);
        }
        
        try {
            // URMAclAdministrator_0011
            // action already exists
            mAclAdmin.createAction("NewAction");
            assertTrue(false);
        } catch (URMInsertException e) {
//            System.out.println("Exptected Exception: " + e.getMessage());
        }
        
        // URMAclAdministrator_0012
        // BUGBUG Wir f�hren keine NameChecks durch.
        
        try {
            // URMAclAdministrator_0013
            // delete action, action exists
            mAclAdmin.deleteAction("NewAction");
        } catch (Exception e) {
            e.printStackTrace();
            assertTrue(false);
        }
        
        try {
            // URMAclAdministrator_0014
            // delete action, action does not exists
            mAclAdmin.deleteAction("NewAction");
            assertTrue(false);
        } catch (URMDeleteException e) {
//            System.out.println("Exptected Exception: " + e.getMessage());
        }
        
        try {
            // URMAclAdministrator_0015
            // get Acl, Acl exists
            URMAcl acl1 = mAclAdmin.getAcl("AclId001");
        } catch (Exception e) {
            e.printStackTrace();
            assertTrue(false);
        }
        
        // URMAclAdministrator_0016
        // delete action, action does not exists
        URMAcl acl1 = mAclAdmin.getAcl("nix da");
        assertNull(acl1);

        mAclAdmin.deleteAcl("AclId001");
        
        try {
            // URMAclAdministrator_0017
            // create ACL and ACEs and do something with it
            mAclAdmin.createAcl("AclId003",
                                         mAdmin.getUser("TestUser_dk1", null),
                                         true);
            acl1 = mAclAdmin.getAcl("AclId003");
            acl1.defineAce(URMConstants.GRANT, mAdmin.getUser("TestUser_dk2", null),
                                 mAclAdmin.getAction("A1"), 0, false);
            acl1.defineAce(URMConstants.GRANT, mAdmin.getRole("role2"),
                                 mAclAdmin.getAction("B3"), 0, false);
            acl1.defineAce(URMConstants.GRANT, mAdmin.getUser("TestUser_dk1", null),
                                 mAclAdmin.getAction("A2"), 2, true);
                                 
            acl1.updateOwner(mAdmin.getUser("TestUser_dk2", null));
            int [] iOrder = new int[3];
            iOrder[0] = 1;
            iOrder[1] = 2;
            iOrder[2] = 0;
            acl1.updateOrder(iOrder);

            List r1 = new ArrayList();
            List r2 = new ArrayList();
            r1.add("TestUser_dk2");
            r1.add("TestUser_dk1");
            r1.add("role2");
            r2.add("A1");
            r2.add("A2");
            r2.add("B3");
            
            List l1 = acl1.getAllAces();
            Iterator i1 = l1.iterator();
            assertEquals(l1.size(), 3);
            while (i1 != null && i1.hasNext()){
                URMAce ace1 = (URMAce)i1.next();
                assertTrue(r1.contains(ace1.getSubject().getName()));
                assertTrue(r2.contains(ace1.getAction().getName()));
            }

            // this should delete the ACE ???
//                mAdmin.deleteRole("role2");        inconsisten at the moment!!

            // and remove ACE by index
            acl1 = mAclAdmin.getAcl("AclId003");
            acl1.removeAce(2);
            // This shouldn't do anything
            acl1.removeAce(99);

            // print the remaining ACEs again (should only be 1 left)
            r1.clear();
            r2.clear();
            r1.add("TestUser_dk2");
            r1.add("TestUser_dk1");
            r2.add("A1");
            r2.add("A2");
             
            acl1 = mAclAdmin.getAcl("AclId003");
            l1 = acl1.getAllAces();
            i1 = l1.iterator();
            assertEquals(l1.size(), 2);
            while (i1 != null && i1.hasNext()){
                URMAce ace1 = (URMAce)i1.next();
                assertTrue(r1.contains(ace1.getSubject().getName()));
                assertTrue(r2.contains(ace1.getAction().getName()));
            }

            // URMAclAdministrator_0018
            // getAclPath returns empty list
            List inList = new ArrayList();
            inList.add("Acl4711"); inList.add("Acl4712"); inList.add("Acl4713");
            List outList = mAclAdmin.getAclPath(inList);
            assertEquals(outList.size(), 0);
            
            // URMAclAdministrator_0019
            // getAclPath returns one element
            inList = new ArrayList();
            inList.add("Acl4711"); inList.add("AclId003"); inList.add("Acl4714");
            outList = mAclAdmin.getAclPath(inList);
            assertEquals(outList.size(), 1);
 
            // URMAclAdministrator_0020
            // create multiple ACLs
            r1.clear();
            r1.add("AclId003");
            r1.add("AclId004");

            mAclAdmin.createAcl("AclId004",
                                         mAdmin.getUser("TestUser_dk1", null),
                                         true);
            URMAcl acl11 = mAclAdmin.getAcl("AclId004");
            acl11.defineAce(URMConstants.GRANT, mAdmin.getUser("TestUser_dk2", null),
                                 mAclAdmin.getAction("A1"), 0, false);
            acl11.defineAce(URMConstants.GRANT, mAdmin.getRole("role2"),
                                 mAclAdmin.getAction("B3"), 0, false);
            acl11.defineAce(URMConstants.GRANT, mAdmin.getUser("TestUser_dk1", null),
                                 mAclAdmin.getAction("A2"), 2, true);
            inList = new ArrayList();
            inList.add("AclId003"); inList.add("Acl4700"); inList.add("AclId004");
            outList = mAclAdmin.getAclPath(inList);
            assertEquals(outList.size(), 2);
            Iterator iter1 = outList.iterator();
            while (iter1 != null && iter1.hasNext()) {
                assertTrue(r1.contains(((URMAcl)iter1.next()).getId()));
            }
           
            // URMAclAdministrator_0021
            // "Uri does not exist."
            // We don't distinguish betweeen URI and ACLs in this API.
            // The ACLs are identified by the URI paramter.
            // See URMAclAdministrator_0018
            
            // URMAclAdministrator_0022 - URMAclAdministrator_0023 are further up...
            
            // URMAclAdministrator_0024
            r1.clear();
            r1.add("A2"); r1.add("B1"); r1.add("A1"); r1.add("B2"); r1.add("B3");
           
            Set set1 = mAclAdmin.getAllActions();
            assertEquals(set1.size(), 5);
            iter1 =  set1.iterator();
            while (iter1 != null && iter1.hasNext()) {
                assertTrue(r1.contains(((URMAction)iter1.next()).getName()));
            }
            
            mAclAdmin.deleteAcl("AclId003");
            mAclAdmin.deleteAcl("AclId004");

            // URMAclAdministrator_0025
            // getAction, Action exists
            URMAction act1 = mAclAdmin.getAction("A1");
            assertNotNull(act1);
            assertTrue(act1.getName().equals("A1"));
 
            // URMAclAdministrator_0026
            // getAction, Action does not exists
            act1 = mAclAdmin.getAction("hugo");
            assertEquals(act1, null);
 
            
        } catch (Exception e) {
            System.out.println("Exception caught: " +e.getMessage());
        }
    }
         
    public void test_post() throws Exception {
        
        URMInit.init(false, ldapadmin, null);
        mPrincipal = authenticator.authenticateUser(ldapadmin, ldapadmin.toCharArray(), null);
        mPrincipal.setActiveRole(URMConstants.URM_ADMIN_ROLE);
        mAdmin = mPrincipal.getURMAdministrator();
        mAclAdmin = mPrincipal.getURMAclAdministrator();
        
        // Create all data necessary to start the tests

        try {
            // Users and Groups
            URMGroup grp1 = mAdmin.getGroup("TestGroup_dk1", null);
            grp1.removeUserFromGroup("TestUser_dk1", null);
            grp1.removeUserFromGroup("TestUser_dk2", null);
            mAdmin.deleteGroup("TestGroup_dk1", null);
            mAdmin.deleteUser("TestUser_dk1", null);
            mAdmin.deleteUser("TestUser_dk2", null);

            // Roles
            mAdmin.deleteRole("role1");
            mAdmin.deleteRole("role2");
            mAdmin.deleteRole("role3");

            // Actions
            URMAction act4 = mAclAdmin.getAction("A1");
            act4.removeAction("B1");
            act4.removeAction("B2");
            act4.removeAction("B3");
            mAclAdmin.deleteAction("B1");
            mAclAdmin.deleteAction("B2");
            mAclAdmin.deleteAction("B3");
            mAclAdmin.deleteAction("A1");
            mAclAdmin.deleteAction("A2");

        } catch (Exception e) {
            System.out.println("Exception caught: " +e.getMessage());
        }
        
    }

    public static void main(String[] args) throws Exception {
        if (authenticator == null) {
            URMConfigurator conf = URMConfiguratorXML.newConfigfileConfigurator();
            conf = (URMConfigurator)(conf.getSubConfigurators().get("Authenticator"));
            authenticator = URMAuthenticator.newInstance(conf);
        }
        
        String[] testCaseName = { "-noloading", Test_QE_URMAclAdministrator.class.getName() };
    
        junit.textui.TestRunner.main(testCaseName);
    }
}
