portals-jetspeed-dev mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From dlest...@apache.org
Subject cvs commit: jakarta-jetspeed-2/portal/src/test/org/apache/jetspeed/security TestRoleManagerService.java TestRdbmsPolicy.java TestLoginModule.java TestUserManagerService.java TestPermissionManagerService.java TestGroupManagerService.java TestSecurityHelper.java
Date Thu, 12 Feb 2004 16:31:36 GMT
dlestrat    2004/02/12 08:31:36

  Modified:    portal/src/test/org/apache/jetspeed/security
                        TestSecurityHelper.java
  Added:       portal/src/test/org/apache/jetspeed/security
                        TestRoleManagerService.java TestRdbmsPolicy.java
                        TestLoginModule.java TestUserManagerService.java
                        TestPermissionManagerService.java
                        TestGroupManagerService.java
  Log:
  Security service tests.
  
  Revision  Changes    Path
  1.3       +0 -0      jakarta-jetspeed-2/portal/src/test/org/apache/jetspeed/security/TestSecurityHelper.java
  
  Index: TestSecurityHelper.java
  ===================================================================
  RCS file: /home/cvs/jakarta-jetspeed-2/portal/src/test/org/apache/jetspeed/security/TestSecurityHelper.java,v
  retrieving revision 1.2
  retrieving revision 1.3
  diff -u -r1.2 -r1.3
  
  
  
  1.1                  jakarta-jetspeed-2/portal/src/test/org/apache/jetspeed/security/TestRoleManagerService.java
  
  Index: TestRoleManagerService.java
  ===================================================================
  /* ====================================================================
   * The Apache Software License, Version 1.1
   *
   * Copyright (c) 2000-2004 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 acknowledgment:
   *       "This product includes software developed by the
   *        Apache Software Foundation (http://www.apache.org/)."
   *    Alternately, this acknowledgment may appear in the software itself,
   *    if and wherever such third-party acknowledgments normally appear.
   *
   * 4. The names "Apache" and "Apache Software Foundation" and
   *    "Apache Jetspeed" 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",
   *    "Apache Jetspeed", nor may "Apache" appear in their name, without
   *    prior written permission of the Apache Software Foundation.
   *
   * 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/>.
   */
  package org.apache.jetspeed.security;
  
  import java.security.Principal;
  import java.util.ArrayList;
  import java.util.Collection;
  import java.util.HashSet;
  import java.util.Iterator;
  import java.util.Map;
  import java.util.prefs.BackingStoreException;
  import java.util.prefs.Preferences;
  
  import javax.security.auth.Subject;
  
  import junit.framework.Test;
  import junit.framework.TestSuite;
  
  import org.apache.jetspeed.cps.CommonPortletServices;
  import org.apache.jetspeed.security.impl.RolePrincipalImpl;
  import org.apache.jetspeed.test.JetspeedTest;
  import org.apache.jetspeed.test.JetspeedTestSuite;
  
  /**
   * <p>Unit testing for {@link RoleManagerService}.</p>
   *
   * @author <a href="mailto:david@sensova.com">David Le Strat</a>
   */
  public class TestRoleManagerService extends JetspeedTest
  {
  
      private GroupManagerService gms = null;
      private RoleManagerService rms = null;
      private UserManagerService ums = null;
  
      /**
       * <p>Defines the test case name for junit.</p>
       * @param testName The test case name.
       */
      public TestRoleManagerService(String testName)
      {
          super(testName);
      }
  
      /**
       * <p>Start the tests.</p>
       * @param args the arguments. Not used
       */
      public static void main(String args[])
      {
          junit.awtui.TestRunner.main(new String[] { TestRoleManagerService.class.getName()});
      }
  
      /**
       * @see junit.framework.TestCase#setUp()
       */
      public void setUp() throws Exception
      {
          super.setUp();
      }
  
      /**
       * @see junit.framework.TestCase#tearDown()
       */
      public void tearDown() throws Exception
      {
          super.tearDown();
          destroyRoles();
      }
  
      /**
       * <p>Creates the test suite.</p>
       * @return A test suite (<code>TestSuite</code>) that includes all methods
       *         starting with "test"
       */
      public static Test suite()
      {
          return new JetspeedTestSuite(TestRoleManagerService.class);
      }
  
      /**
       * <p>Returns the {@link RoleManagerService}.</p>
       * @return The RoleManagerService.
       */
      protected RoleManagerService getRoleManagerService()
      {
          if (rms == null)
          {
              rms = (RoleManagerService) CommonPortletServices.getPortalService(RoleManagerService.SERVICE_NAME);
          }
          return rms;
      }
  
      /**
       * <p>Returns the {@link GroupManagerService}.</p>
       * @return The GroupManagerService.
       */
      protected GroupManagerService getGroupManagerService()
      {
          if (gms == null)
          {
              gms = (GroupManagerService) CommonPortletServices.getPortalService(GroupManagerService.SERVICE_NAME);
          }
          return gms;
      }
  
      /**
       * <p>Returns the {@link UserManagerService}.</p>
       * @return The UserManagerService.
       */
      protected UserManagerService getUserManagerService()
      {
          if (ums == null)
          {
              ums = (UserManagerService) CommonPortletServices.getPortalService(UserManagerService.SERVICE_NAME);
          }
          return ums;
      }
  
      /**
       * <p>Test that a {@link UserManagerService} was returned.</p>
       */
      public void testService()
      {
          assertNotNull(getRoleManagerService());
      }
  
      /**
       * <p>Test add role.</p>
       */
      public void testAddRole()
      {
          RoleManagerService rms = getRoleManagerService();
          // Add role with path beginning with '/'.
          try
          {
              rms.addRole("/testrole");
          }
          catch (SecurityException sex)
          {
              assertTrue("role should not already exists. exception caught: " + sex, false);
          }
          // Add role without path beginning with '/'.
          try
          {
              rms.addRole("testrole/newrole0");
          }
          catch (SecurityException sex)
          {
              assertTrue("role should not already exists. exception caught: " + sex, false);
          }
          // Add existing role.
          try
          {
              rms.addRole("/testrole/newrole0");
              assertTrue("role should already exists. exception not thrown.", false);
          }
          catch (SecurityException sex)
          {
          }
          // Remove role.
          rms.removeRole("/testrole");
      }
  
      /**
       * <p>Test add user to role.</p>
       */
      public void testAddRoleToUser()
      {
          // Init test.
          RoleManagerService rms = getRoleManagerService();
          UserManagerService ums = getUserManagerService();
          try
          {
              ums.addUser("anonuser1", "password");
              rms.addRole("/testusertorole1");
              rms.addRole("/testusertorole1/role1");
              rms.addRole("/testusertorole1/role2");
          }
          catch (SecurityException sex)
          {
              assertTrue("failed to init testAddRoleToUser(), " + sex, false);
          }
          // Add role with no prior roles.
          try
          {
              rms.addRoleToUser("anonuser1", "/testusertorole1/role1");
              Collection principals = ums.getUser("anonuser1").getSubject().getPrincipals();
              Principal found =
                  SecurityHelper.getPrincipal(
                      new Subject(false, new HashSet(principals), new HashSet(), new HashSet()),
                      RolePrincipal.class);
              assertNotNull("found principal is null", found);
              assertTrue(
                  "found principal should be /testusertorole1/role1, " + found.getName(),
                  found.getName().equals((new RolePrincipalImpl("/testusertorole1/role1")).getName()));
          }
          catch (SecurityException sex)
          {
              assertTrue("should add user to role. exception caught: " + sex, false);
          }
          // Add role with existing roles.
          try
          {
              rms.addRoleToUser("anonuser1", "/testusertorole1/role2");
              Collection principals = ums.getUser("anonuser1").getSubject().getPrincipals();
              assertTrue(
                  "anonuser1 should contain /testusertorole1/role2",
                  principals.contains(new RolePrincipalImpl("/testusertorole1/role2")));
          }
          catch (SecurityException sex)
          {
              assertTrue("should add user to role. exception caught: " + sex, false);
          }
          // Add role when user does not exist.
          try
          {
              rms.addRoleToUser("anonuser123", "/testusertorole1/role2");
              assertTrue("should catch exception: user does not exist.", false);
          }
          catch (SecurityException sex)
          {
          }
          // Add role when role does not exist.
          try
          {
              rms.addRoleToUser("anonuser1", "/testusertorole1/role123");
              assertTrue("should catch exception: role does not exist.", false);
          }
          catch (SecurityException sex)
          {
          }
  
          // Cleanup.
          ums.removeUser("anonuser1");
          rms.removeRole("/testusertorole1");
      }
  
      /**
       * <p>Test remove role.</p>
       */
      public void testRemoveRole()
      {
          // Init test.
          RoleManagerService rms = getRoleManagerService();
          UserManagerService ums = getUserManagerService();
          try
          {
              ums.addUser("anonuser2", "password");
              rms.addRole("/testrole1");
              rms.addRole("/testrole1/role1");
              rms.addRole("/testrole1/role2");
              rms.addRole("/testrole2");
              rms.addRole("/testrole2/role1");
              rms.addRole("/testrole2/role2");
              rms.addRoleToUser("anonuser2", "/testrole1/role1");
              rms.addRoleToUser("anonuser2", "/testrole1/role2");
              rms.addRoleToUser("anonuser2", "/testrole2/role1");
          }
          catch (SecurityException sex)
          {
              assertTrue("failed to init testRemoveRole(), " + sex, false);
          }
  
          rms.removeRole("/testrole1/role1");
          try
          {
              Collection principals = ums.getUser("anonuser2").getSubject().getPrincipals();
              assertEquals(
                  "principal size should be == 3 after removing /testrole1/role1, for principals: " + principals.toString(),
                  3,
                  principals.size());
              assertFalse(
                  "anonuser2 should not contain /testrole1/role1",
                  principals.contains(new RolePrincipalImpl(RolePrincipalImpl.getFullPathFromPrincipalName("/testrole1/role1"))));
          }
          catch (SecurityException sex)
          {
              assertTrue("should remove role. exception caught: " + sex, false);
          }
  
          // Cleanup test.
          ums.removeUser("anonuser2");
          rms.removeRole("/testrole1");
          rms.removeRole("/testrole2");
      }
  
      /**
       * <p>Test get role.</p>
       */
      public void testGetRole()
      {
          RoleManagerService rms = getRoleManagerService();
          // Test when the role does not exist.
          try
          {
              Role role = rms.getRole("/testroledoesnotexist");
              assertTrue("role does not exist. should have thrown an exception.", false);
          }
          catch (SecurityException sex)
          {
          }
          // Test when the role exists.
          Role role = null;
          try
          {
              rms.addRole("/testgetrole");
              role = rms.getRole("/testgetrole");
          }
          catch (SecurityException sex)
          {
              assertTrue("role exists. should not have thrown an exception.", false);
          }
          assertNotNull("role is null", role);
          // Test the RolePrincipal.
          RolePrincipal rolePrincipal = role.getPrincipal();
          assertNotNull("role principal is null", rolePrincipal);
          assertEquals(
              "expected role principal full path == /role/testgetrole",
              "/role/testgetrole",
              SecurityHelper.getPrincipalFullPath(rolePrincipal));
  
          // Test the Role Preferences.
          Preferences preferences = role.getPreferences();
          assertEquals("expected role node == /role/testgetrole", "/role/testgetrole", preferences.absolutePath());
  
          // Cleanup test.
          rms.removeRole("/testgetrole");
      }
  
      /**
       * <p>Test get roles for user.</p>
       */
      public void testGetRolesForUser()
      {
          // Init test.
          RoleManagerService rms = getRoleManagerService();
          UserManagerService ums = getUserManagerService();
          try
          {
              ums.addUser("anonuser3", "password");
              rms.addRole("/testuserrolemapping");
              rms.addRole("/testuserrolemapping/role1");
              rms.addRole("/testuserrolemapping/role2");
              rms.addRoleToUser("anonuser3", "/testuserrolemapping");
              rms.addRoleToUser("anonuser3", "/testuserrolemapping/role1");
              rms.addRoleToUser("anonuser3", "/testuserrolemapping/role2");
          }
          catch (SecurityException sex)
          {
              assertTrue("failed to init testGetRolesForUser(), " + sex, false);
          }
  
          try
          {
              Collection roles = rms.getRolesForUser("anonuser3");
              assertEquals("roles size should be == 3", 3, roles.size());
          }
          catch (SecurityException sex)
          {
              assertTrue("user exists. should not have thrown an exception: " + sex, false);
          }
  
          // Cleanup test.
          ums.removeUser("anonuser3");
          rms.removeRole("/testuserrolemapping");
      }
  
      /**
       * <p>Test get users in role.</p>
       */
      public void testGetUsersInRole()
      {
          // Init test.
          RoleManagerService rms = getRoleManagerService();
          UserManagerService ums = getUserManagerService();
          try
          {
              ums.addUser("anonuser3", "password");
              ums.addUser("anonuser4", "password");
              rms.addRole("/testuserrolemapping");
              rms.addRole("/testuserrolemapping/role1");
              rms.addRole("/testuserrolemapping/role2");
              rms.addRoleToUser("anonuser3", "/testuserrolemapping");
              rms.addRoleToUser("anonuser3", "/testuserrolemapping/role1");
              rms.addRoleToUser("anonuser3", "/testuserrolemapping/role2");
              rms.addRoleToUser("anonuser4", "/testuserrolemapping");
          }
          catch (SecurityException sex)
          {
              assertTrue("failed to init testGetUsersInRole(), " + sex, false);
          }
  
          try
          {
              Collection users = rms.getUsersInRole("/testuserrolemapping");
              assertEquals("users size should be == 2", 2, users.size());
          }
          catch (SecurityException sex)
          {
              assertTrue("role exists. should not have thrown an exception: " + sex, false);
          }
  
          // Cleanup test.
          ums.removeUser("anonuser3");
          ums.removeUser("anonuser4");
          rms.removeRole("/testuserrolemapping");
      }
  
      /**
       * <p>Test get roles for group.</p>
       */
      public void testGetRolesForGroup()
      {
          // Init test.
          RoleManagerService rms = getRoleManagerService();
          GroupManagerService gms = getGroupManagerService();
          try
          {
              rms.addRole("/testuserrolemapping");
              rms.addRole("/testuserrolemapping/role1");
              rms.addRole("/testuserrolemapping/role3");
              gms.addGroup("/testrolegroupmapping");
              rms.addRoleToGroup("/testuserrolemapping", "/testrolegroupmapping");
              rms.addRoleToGroup("/testuserrolemapping/role1", "/testrolegroupmapping");
              rms.addRoleToGroup("/testuserrolemapping/role3", "/testrolegroupmapping");
          }
          catch (SecurityException sex)
          {
              assertTrue("failed to init testGetRolesForGroup(), " + sex, false);
          }
  
          try
          {
              Collection roles = rms.getRolesForGroup("/testrolegroupmapping");
              assertEquals("roles size should be == 3", 3, roles.size());
          }
          catch (SecurityException sex)
          {
              assertTrue("group exists. should not have thrown an exception: " + sex, false);
          }
  
          // Cleanup test.
          rms.removeRole("/testuserrolemapping");
          gms.removeGroup("/testrolegroupmapping");
      }
  
      /**
       * <p>Test get groups in role.</p>
       */
      public void testGetGroupsInRole()
      {
          // Init test.
          RoleManagerService rms = getRoleManagerService();
          GroupManagerService gms = getGroupManagerService();
          try
          {
              rms.addRole("/testuserrolemapping");
              gms.addGroup("/testrolegroupmapping");
              gms.addGroup("/testrolegroupmapping/group1");
              gms.addGroup("/testrolegroupmapping/group2");
              rms.addRoleToGroup("/testuserrolemapping", "/testrolegroupmapping");
              rms.addRoleToGroup("/testuserrolemapping", "/testrolegroupmapping/group1");
              rms.addRoleToGroup("/testuserrolemapping", "/testrolegroupmapping/group2");
          }
          catch (SecurityException sex)
          {
              assertTrue("failed to init testGetRolesForGroup(), " + sex, false);
          }
  
          try
          {
              Collection groups = rms.getGroupsInRole("/testuserrolemapping");
              assertEquals("groups size should be == 3", 3, groups.size());
          }
          catch (SecurityException sex)
          {
              assertTrue("role exists. should not have thrown an exception: " + sex, false);
          }
  
          // Cleanup test.
          rms.removeRole("/testuserrolemapping");
          gms.removeGroup("/testrolegroupmapping");
      }
  
      /**
       * <p>Test remove role from user.</p>
       */
      public void testRemoveRoleFromUser()
      {
          // Init test.
          RoleManagerService rms = getRoleManagerService();
          UserManagerService ums = getUserManagerService();
          try
          {
              ums.addUser("anonuser5", "password");
              rms.addRole("/testrole3");
              rms.addRoleToUser("anonuser5", "/testrole3");
          }
          catch (SecurityException sex)
          {
              assertTrue("failed to init testRemoveRoleFromUser(), " + sex, false);
          }
  
          rms.removeRoleFromUser("anonuser5", "/testrole3");
          try
          {
              Collection roles = rms.getRolesForUser("anonuser5");
              assertEquals("roles size should be == 0", 0, roles.size());
          }
          catch (SecurityException sex)
          {
              assertTrue("user exists. should not have thrown an exception: " + sex, false);
          }
  
          // Cleanup test.
          ums.removeUser("anonuser5");
          rms.removeRole("/testrole3");
      }
  
      /**
       * <p>Test is user in role.</p>
       */
      public void testIsUserInRole()
      {
          // Init test.
          RoleManagerService rms = getRoleManagerService();
          UserManagerService ums = getUserManagerService();
          try
          {
              ums.addUser("anonuser4", "password");
              rms.addRole("/testuserrolemapping");
              rms.addRoleToUser("anonuser4", "/testuserrolemapping");
          }
          catch (SecurityException sex)
          {
              assertTrue("failed to init testIsUserInRole(), " + sex, false);
          }
  
          try
          {
              boolean isUserInRole = rms.isUserInRole("anonuser4", "/testuserrolemapping");
              assertTrue("anonuser4 should be in role /testuserrolemapping", isUserInRole);
          }
          catch (SecurityException sex)
          {
              assertTrue("user and role exist. should not have thrown an exception: " + sex, false);
          }
  
          // Cleanup test.
          ums.removeUser("anonuser4");
          rms.removeRole("/testuserrolemapping");
      }
  
      /**
       * <p>Test remove role from group.</p>
       */
      public void testRemoveRoleFromGroup()
      {
          // Init test.
          RoleManagerService rms = getRoleManagerService();
          GroupManagerService gms = getGroupManagerService();
          try
          {
              rms.addRole("/testuserrolemapping");
              rms.addRole("/testuserrolemapping/role1");
              rms.addRole("/testuserrolemapping/role3");
              gms.addGroup("/testrolegroupmapping");
              rms.addRoleToGroup("/testuserrolemapping", "/testrolegroupmapping");
              rms.addRoleToGroup("/testuserrolemapping/role1", "/testrolegroupmapping");
              rms.addRoleToGroup("/testuserrolemapping/role3", "/testrolegroupmapping");
          }
          catch (SecurityException sex)
          {
              assertTrue("failed to init testRemoveRoleFromGroup(), " + sex, false);
          }
  
          rms.removeRoleFromGroup("/testuserrolemapping/role3", "/testrolegroupmapping");
          try
          {
              Collection roles = rms.getRolesForGroup("/testrolegroupmapping");
              assertEquals("roles size should be == 2", 2, roles.size());
          }
          catch (SecurityException sex)
          {
              assertTrue("group exists. should not have thrown an exception: " + sex, false);
          }
  
          // Cleanup test.
          rms.removeRole("/testuserrolemapping");
          gms.removeGroup("/testrolegroupmapping");
      }
  
      /**
       * <p>Test is user in role.</p>
       */
      public void testIsGroupInRole()
      {
          // Init test.
          RoleManagerService rms = getRoleManagerService();
          GroupManagerService gms = getGroupManagerService();
          try
          {
              rms.addRole("/testuserrolemapping");
              gms.addGroup("/testrolegroupmapping");
              rms.addRoleToGroup("/testuserrolemapping", "/testrolegroupmapping");
          }
          catch (SecurityException sex)
          {
              assertTrue("failed to init testIsGroupInRole(), " + sex, false);
          }
          try
          {
              boolean isGroupInRole = rms.isGroupInRole("/testrolegroupmapping", "/testuserrolemapping");
              assertTrue("/testrolegroupmapping should be in role /testuserrolemapping", isGroupInRole);
          }
          catch (SecurityException sex)
          {
              assertTrue("group and role exist. should not have thrown an exception: " + sex, false);
          }
  
          // Cleanup test.
          rms.removeRole("/testuserrolemapping");
          gms.removeGroup("/testrolegroupmapping");
      }
  
      /**
       * <p>Destroy role test objects.</p>
       */
      protected void destroyRoles()
      {
          UserManagerService ums = getUserManagerService();
          RoleManagerService rms = getRoleManagerService();
          GroupManagerService gms = getGroupManagerService();
          ums.removeUser("anonuser1");
          ums.removeUser("anonuser2");
          ums.removeUser("anonuser3");
          ums.removeUser("anonuser4");
          ums.removeUser("anonuser5");
          rms.removeRole("/testrole1");
          rms.removeRole("/testrole2");
          rms.removeRole("/testrole3");
          rms.removeRole("/testgetrole");
          rms.removeRole("/testuserrolemapping");
          gms.removeGroup("/testrolegroupmapping");
      }
  
  }
  
  
  
  1.1                  jakarta-jetspeed-2/portal/src/test/org/apache/jetspeed/security/TestRdbmsPolicy.java
  
  Index: TestRdbmsPolicy.java
  ===================================================================
  /* ====================================================================
   * The Apache Software License, Version 1.1
   *
   * Copyright (c) 2000-2004 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 acknowledgment:
   *       "This product includes software developed by the
   *        Apache Software Foundation (http://www.apache.org/)."
   *    Alternately, this acknowledgment may appear in the software itself,
   *    if and wherever such third-party acknowledgments normally appear.
   *
   * 4. The names "Apache" and "Apache Software Foundation" and
   *    "Apache Jetspeed" 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",
   *    "Apache Jetspeed", nor may "Apache" appear in their name, without
   *    prior written permission of the Apache Software Foundation.
   *
   * 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/>.
   */
  package org.apache.jetspeed.security;
  
  import java.security.AccessController;
  import java.security.AccessControlException;
  import java.security.Principal;
  import java.security.PrivilegedAction;
  import java.security.Policy;
  import java.util.HashSet;
  import java.util.Set;
  
  import javax.security.auth.Subject;
  import javax.security.auth.login.LoginContext;
  import javax.security.auth.login.LoginException;
  
  import junit.framework.Test;
  import junit.framework.TestSuite;
  
  import org.apache.jetspeed.cps.CommonPortletServices;
  import org.apache.jetspeed.security.SecurityHelper;
  import org.apache.jetspeed.security.UserPrincipal;
  import org.apache.jetspeed.security.impl.PassiveCallbackHandler;
  import org.apache.jetspeed.security.impl.RdbmsPolicy;
  import org.apache.jetspeed.security.impl.UserPrincipalImpl;
  import org.apache.jetspeed.test.JetspeedTest;
  import org.apache.jetspeed.test.JetspeedTestSuite;
  
  /**
   * @author <a href="mailto:david@sensova.com">David Le Strat</a>
   */
  public class TestRdbmsPolicy extends JetspeedTest
  {
      /** <p>The JAAS login context.</p> */
      private LoginContext loginContext = null;
  
      /** <p>The user manager service.</p> */
      private UserManagerService ums = null;
  
      /** <p>The permission manager service.</p> */
      private PermissionManagerService pms = null;
  
      /**
       * <p>Defines the test case name for junit.</p>
       * @param testName The test case name.
       */
      public TestRdbmsPolicy(String testName)
      {
          super(testName);
      }
  
      /**
       * <p>Returns the {@link UserManagerService}.</p>
       * @return The UserManagerService.
       */
      protected UserManagerService getUserManagerService()
      {
          if (ums == null)
          {
              ums = (UserManagerService) CommonPortletServices.getPortalService(UserManagerService.SERVICE_NAME);
          }
          return ums;
      }
  
      /**
       * <p>Returns the {@link PermissionManagerService}.</p>
       * @return The PermissionManagerService.
       */
      protected PermissionManagerService getPermissionManagerService()
      {
          if (pms == null)
          {
              pms = (PermissionManagerService) CommonPortletServices.getPortalService(PermissionManagerService.SERVICE_NAME);
          }
          return pms;
      }
  
      /**
       * <p>Start the tests.</p>
       * @param args the arguments. Not used
       */
      public static void main(String args[])
      {
          junit.awtui.TestRunner.main(new String[] { TestRdbmsPolicy.class.getName()});
      }
  
      /**
       * @see junit.framework.TestCase#setUp()
       */
      public void setUp() throws Exception
      {
          super.setUp();
  
          // Insert custom provider here.
          Policy.setPolicy(new RdbmsPolicy());
          Policy.getPolicy().refresh();
  
          initUser();
  
          // Let's login in.
          try
          {
              System.out.println("\t\t[TestRdbmsPolicy] Creating login context.");
              PassiveCallbackHandler pch = new PassiveCallbackHandler("anon", "password");
              loginContext = new LoginContext("Jetspeed", pch);
              loginContext.login();
          }
          catch (LoginException le)
          {
              le.printStackTrace();
              assertTrue("\t\t[TestRdbmsPolicy] Failed to setup test.", false);
          }
  
      }
  
      /**
       * @see junit.framework.TestCase#tearDown()
       */
      public void tearDown() throws Exception
      {
          super.tearDown();
  
          // Logout.
          try
          {
              loginContext.logout();
          }
          catch (LoginException le)
          {
              le.printStackTrace();
              assertTrue("\t\t[TestRdbmsPolicy] Failed to tear down test.", false);
          }
          destroyUser();
      }
  
      /**
       * <p>Creates the test suite.</p>
       * @return A test suite (<code>TestSuite</code>) that includes all methods
       *         starting with "test"
       */
      public static Test suite()
      {
          return new JetspeedTestSuite(TestRdbmsPolicy.class);
      }
  
      /**
       * <p>Executing this test requires adding an entry to java.policy.</p>
       * <p>A possible entry would be to grant for all principals:</p>
       * <pre><code>
       * grant
       * {
       *     permission org.apache.jetspeed.security.auth.PortletPermission "myportlet", "view";
       * }
       * </code></pre>
       * <p>Such an entry would also test the Rdbms defaulting behavior if no
       * entry is provided in the database for the tested Subject JetspeedUserPrincipal.</p>
       */
      /*
      public void testPermissionWithSubjectInContructor()
      {
          // JetspeedPermission should be granted.
          PortletPermission perm1 = new PortletPermission("myportlet", "view", loginContext.getSubject());
          try
          {
              AccessController.checkPermission(perm1);
          }
          catch (AccessControlException ace)
          {
              assertTrue("did not authorize view permission on the portlet.", false);
          }
      
          // JetspeedPermission should be denied.
          PortletPermission perm2 = new PortletPermission("myportlet", "edit", loginContext.getSubject());
          try
          {
              AccessController.checkPermission(perm2);
              assertTrue("did not deny edit permission on the portlet.", false);
          }
          catch (AccessControlException ace)
          {
          }
      
          // Subject is omitted. JetspeedPermission should be denied.
          PortletPermission perm3 = new PortletPermission("myportlet", "view");
          try
          {
              AccessController.checkPermission(perm3);
              //assertTrue("did not deny permission with no subject passed.", false);
          }
          catch (AccessControlException ace)
          {
          }
      }
      */
  
      public void testPermissionWithSubjectInAccessControlContext()
      {
          // JetspeedPermission should be granted.
          try
          {
              Subject.doAs(loginContext.getSubject(), new PrivilegedAction()
              {
                  public Object run()
                  {
                      PortletPermission perm1 = new PortletPermission("myportlet", "view");
                      AccessController.checkPermission(perm1);
                      return null;
                  }
              });
          }
          catch (AccessControlException ace)
          {
              assertTrue("did not authorize view permission on the portlet.", false);
          }
  
          // Should be denied.
          try
          {
              Subject.doAs(loginContext.getSubject(), new PrivilegedAction()
              {
                  public Object run()
                  {
                      PortletPermission perm2 = new PortletPermission("myportlet", "delete");
                      AccessController.checkPermission(perm2);
                      return null;
                  }
              });
              assertTrue("did not deny delete permission on the portlet.", false);
          }
          catch (AccessControlException ace)
          {
          }
      }
  
      /**
       * <p>Initialize user test object.</p>
       */
      protected void initUser()
      {
          UserManagerService ums = getUserManagerService();
          try
          {
              ums.addUser("anon", "password");
          }
          catch (SecurityException sex)
          {
          }
          PermissionManagerService pms = getPermissionManagerService();
          UserPrincipal user = new UserPrincipalImpl("anon");
          PortletPermission perm1 = new PortletPermission("myportlet", "view");
          PortletPermission perm2 = new PortletPermission("myportlet", "view, edit");
          try
          {
              pms.grantPermission(user, perm1);
              pms.grantPermission(user, perm2);
          }
          catch (SecurityException sex)
          {
              sex.printStackTrace();
          }      
      }
  
      /**
       * <p>Destroy user test object.</p>
       */
      protected void destroyUser()
      {
          UserManagerService ums = getUserManagerService();
          PermissionManagerService pms = getPermissionManagerService();
  
          ums.removeUser("anon");
          // Remove permissions.
          PortletPermission perm1 = new PortletPermission("myportlet", "view");
          PortletPermission perm2 = new PortletPermission("myportlet", "view, edit");
          pms.removePermission(perm1);
          pms.removePermission(perm2);
      }
  
  }
  
  
  
  1.1                  jakarta-jetspeed-2/portal/src/test/org/apache/jetspeed/security/TestLoginModule.java
  
  Index: TestLoginModule.java
  ===================================================================
  /* ====================================================================
   * The Apache Software License, Version 1.1
   *
   * Copyright (c) 2000-2004 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 acknowledgment:
   *       "This product includes software developed by the
   *        Apache Software Foundation (http://www.apache.org/)."
   *    Alternately, this acknowledgment may appear in the software itself,
   *    if and wherever such third-party acknowledgments normally appear.
   *
   * 4. The names "Apache" and "Apache Software Foundation" and
   *    "Apache Jetspeed" 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",
   *    "Apache Jetspeed", nor may "Apache" appear in their name, without
   *    prior written permission of the Apache Software Foundation.
   *
   * 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/>.
   */
  package org.apache.jetspeed.security;
  
  import java.security.Principal;
  import java.util.HashSet;
  import java.util.Set;
  
  import javax.security.auth.login.LoginContext;
  import javax.security.auth.login.LoginException;
  
  import junit.framework.Test;
  import junit.framework.TestSuite;
  
  import org.apache.jetspeed.cps.CommonPortletServices;
  import org.apache.jetspeed.security.SecurityHelper;
  import org.apache.jetspeed.security.impl.UserPrincipalImpl;
  import org.apache.jetspeed.security.impl.PassiveCallbackHandler;
  import org.apache.jetspeed.test.JetspeedTest;
  import org.apache.jetspeed.test.JetspeedTestSuite;
  
  /**
   * @author <a href="mailto:david@sensova.com">David Le Strat</a>
   */
  public class TestLoginModule extends JetspeedTest
  {
      /** <p>The JAAS login context.</p> */
      private LoginContext loginContext = null;
  
      /** <p>The user manager service.</p> */
      private UserManagerService ums = null;
  
      /**
       * <p>Defines the test case name for junit.</p>
       * @param testName The test case name.
       */
      public TestLoginModule(String testName)
      {
          super(testName);
      }
  
      /**
       * <p>Returns the {@link UserManagerService}.</p>
       * @return The UserManagerService.
       */
      protected UserManagerService getService()
      {
          if (ums == null)
          {
              ums = (UserManagerService) CommonPortletServices.getPortalService(UserManagerService.SERVICE_NAME);
          }
          return ums;
      }
  
      /**
       * <p>Start the tests.</p>
       * @param args the arguments. Not used
       */
      public static void main(String args[])
      {
          junit.awtui.TestRunner.main(new String[] { TestLoginModule.class.getName()});
      }
  
      /**
       * @see junit.framework.TestCase#setUp()
       */
      public void setUp() throws Exception
      {
          super.setUp();
          initUserObject();
  
          // Set up login context.
          try {
              PassiveCallbackHandler pch = new PassiveCallbackHandler("anonlogin", "password");
              loginContext = new LoginContext("Jetspeed", pch);
          }
          catch (LoginException le)
          {
              le.printStackTrace();
              assertTrue("\t\t[TestLoginModule] Failed to setup test.", false);
          }
      }
  
      /**
       * @see junit.framework.TestCase#tearDown()
       */
      public void tearDown() throws Exception
      {
          super.tearDown();
          destroyUserObject();
      }
  
      /**
       * <p>Creates the test suite.</p>
       * @return A test suite (<code>TestSuite</code>) that includes all methods
       *         starting with "test"
       */
      public static Test suite()
      {
          return new JetspeedTestSuite(TestLoginModule.class);
      }
  
      public void testLogin() throws LoginException
      {
          loginContext.login();
          Principal found = SecurityHelper.getPrincipal(loginContext.getSubject(), UserPrincipal.class);
          assertNotNull("found principal is null", found);
          assertTrue("found principal should be anonlogin, " + found.getName(), found.getName().equals((new UserPrincipalImpl("anonlogin")).getName()));      
      }
      
      public void testLogout() throws LoginException
      {
          loginContext.login();
          loginContext.logout();
          Principal found = SecurityHelper.getBestPrincipal(loginContext.getSubject(), UserPrincipal.class);
          assertNull("found principal is not null", found);
      }
  
      /**
       * <p>Initialize user test object.</p>
       */
      protected void initUserObject()
      {
          UserManagerService ums = getService();
          try
          {
              ums.addUser("anonlogin", "password");
          }
          catch (SecurityException sex)
          {
          }
      }
  
      /**
       * <p>Destroy user test object.</p>
       */
      protected void destroyUserObject()
      {
          UserManagerService ums = getService();
          ums.removeUser("anonlogin");
      }
  
  }
  
  
  
  1.1                  jakarta-jetspeed-2/portal/src/test/org/apache/jetspeed/security/TestUserManagerService.java
  
  Index: TestUserManagerService.java
  ===================================================================
  /* ====================================================================
   * The Apache Software License, Version 1.1
   *
   * Copyright (c) 2000-2004 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 acknowledgment:
   *       "This product includes software developed by the
   *        Apache Software Foundation (http://www.apache.org/)."
   *    Alternately, this acknowledgment may appear in the software itself,
   *    if and wherever such third-party acknowledgments normally appear.
   *
   * 4. The names "Apache" and "Apache Software Foundation" and
   *    "Apache Jetspeed" 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",
   *    "Apache Jetspeed", nor may "Apache" appear in their name, without
   *    prior written permission of the Apache Software Foundation.
   *
   * 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/>.
   */
  package org.apache.jetspeed.security;
  
  import java.security.Principal;
  import java.util.Collection;
  import java.util.HashMap;
  import java.util.Iterator;
  import java.util.Map;
  import java.util.ArrayList;
  import java.util.prefs.BackingStoreException;
  import java.util.prefs.Preferences;
  
  import javax.security.auth.Subject;
  import javax.security.auth.login.LoginContext;
  import javax.security.auth.login.LoginException;
  
  import junit.framework.Test;
  import junit.framework.TestSuite;
  
  import org.apache.jetspeed.cps.CommonPortletServices;
  import org.apache.jetspeed.security.impl.PassiveCallbackHandler;
  import org.apache.jetspeed.test.JetspeedTest;
  import org.apache.jetspeed.test.JetspeedTestSuite;
  
  /**
   * <p>Unit testing for {@link UserManagerService}.</p>
   *
   * @author <a href="mailto:david@sensova.com">David Le Strat</a>
   */
  public class TestUserManagerService extends JetspeedTest
  {
  
      private UserManagerService service = null;
  
      /**
       * <p>Defines the test case name for junit.</p>
       * @param testName The test case name.
       */
      public TestUserManagerService(String testName)
      {
          super(testName);
      }
  
      /**
       * <p>Start the tests.</p>
       * @param args the arguments. Not used
       */
      public static void main(String args[])
      {
          junit.awtui.TestRunner.main(new String[] { TestUserManagerService.class.getName()});
      }
  
      /**
       * @see junit.framework.TestCase#setUp()
       */
      public void setUp() throws Exception
      {
          super.setUp();
          destroyUserObject();
      }
  
      /**
       * @see junit.framework.TestCase#tearDown()
       */
      public void tearDown() throws Exception
      {
          super.tearDown();
          destroyUserObject();
      }
  
      /**
       * <p>Creates the test suite.</p>
       * @return A test suite (<code>TestSuite</code>) that includes all methods
       *         starting with "test"
       */
      public static Test suite()
      {
          return new JetspeedTestSuite(TestUserManagerService.class);
      }
  
      /**
       * <p>Returns the {@link UserManagerService}.</p>
       * @return The UserManagerService.
       */
      protected UserManagerService getService()
      {
          if (service == null)
          {
              service = (UserManagerService) CommonPortletServices.getPortalService(UserManagerService.SERVICE_NAME);
          }
          return service;
      }
  
      /**
       * <p>Test that a {@link UserManagerService} was returned.</p>
       */
      public void testService()
      {
          assertNotNull(getService());
      }
  
      /**
       * <p>Test add user.</p>
       */
      public void testAddUser()
      {
          UserManagerService ums = getService();
          try
          {
              ums.addUser("anon", "password");
          }
          catch (SecurityException sex)
          {
              assertTrue("user already exists. exception caught: " + sex, false);
          }
  
          try
          {
              ums.addUser("anon", "password");
              assertTrue("user should already exists. exception not thrown.", false);
          }
          catch (SecurityException sex)
          {
          }
  
      }
  
      /**
       * <p>Test remove user.</p>
       */
      public void testRemoveUser()
      {
          UserManagerService ums = getService();
          ums.removeUser("anon");
          if (ums.userExists("anon"))
          {
              assertTrue("user should have been removed: ", false);
          }
      }
  
      /**
       * <p>Test get user.</p>
       */
      public void testGetUser()
      {
          UserManagerService ums = getService();
          // Test when the user does not exist.
          try
          {
              User user = ums.getUser("test");
              assertTrue("user does not exist. should have thrown an exception.", false);
          }
          catch (SecurityException sex)
          {
          }
          // Test when the user exists.
          User user = null;
          try
          {
              ums.addUser("test", "password");
              user = ums.getUser("test");
          }
          catch (SecurityException sex)
          {
              assertTrue("user exists. should not have thrown an exception.", false);
          }
          assertNotNull("user is null", user);
          // Test the User Subject.
          Subject subject = user.getSubject();
          assertNotNull("subject is null", subject);
          // Asset user principal.
          Principal userPrincipal = SecurityHelper.getPrincipal(subject, UserPrincipal.class);
          assertNotNull("user principal is null", userPrincipal);
          assertEquals(
              "expected user principal full path == /user/test",
              "/user/test",
              SecurityHelper.getPrincipalFullPath(userPrincipal));
          assertEquals(
              "expected user principal name == test",
               "test",
               userPrincipal.getName());
  
          // Test the User Preferences.
          Preferences preferences = user.getPreferences();
          assertEquals("expected user node == /user/test", "/user/test", preferences.absolutePath());
      }
  
      /**
       * <p>Test set password.</p>
       */
      public void testSetPassword()
      {
          UserManagerService ums = getService();
          try
          {
              ums.addUser("anon", "password");
              ums.setPassword("anon", "newpassword");
  
              LoginContext loginContext = null;
              // Test that the user can log in with the new password.
              try
              {
                  PassiveCallbackHandler pch = new PassiveCallbackHandler("anon", "newpassword");
                  loginContext = new LoginContext("Jetspeed", pch);
                  loginContext.login();
                  loginContext.logout();
              }
              catch (LoginException le)
              {
                  le.printStackTrace();
                  assertTrue("failed to login user with new password.", false);
              }
          }
          catch (SecurityException sex)
          {
          }
      }
  
      /**
       * <p>Destroy user test object.</p>
       */
      protected void destroyUserObject()
      {
          UserManagerService ums = getService();
          ums.removeUser("anon");
          ums.removeUser("test");
      }
  
  }
  
  
  
  1.1                  jakarta-jetspeed-2/portal/src/test/org/apache/jetspeed/security/TestPermissionManagerService.java
  
  Index: TestPermissionManagerService.java
  ===================================================================
  /* ====================================================================
   * The Apache Software License, Version 1.1
   *
   * Copyright (c) 2000-2004 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 acknowledgment:
   *       "This product includes software developed by the
   *        Apache Software Foundation (http://www.apache.org/)."
   *    Alternately, this acknowledgment may appear in the software itself,
   *    if and wherever such third-party acknowledgments normally appear.
   *
   * 4. The names "Apache" and "Apache Software Foundation" and
   *    "Apache Jetspeed" 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",
   *    "Apache Jetspeed", nor may "Apache" appear in their name, without
   *    prior written permission of the Apache Software Foundation.
   *
   * 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/>.
   */
  package org.apache.jetspeed.security;
  
  import java.util.ArrayList;
  import java.util.Collections;
  import java.util.Enumeration;
  import java.security.Permission;
  import java.security.Permissions;
  
  import junit.framework.Test;
  import junit.framework.TestSuite;
  
  import org.apache.jetspeed.cps.CommonPortletServices;
  import org.apache.jetspeed.security.impl.GroupPrincipalImpl;
  import org.apache.jetspeed.security.impl.RolePrincipalImpl;
  import org.apache.jetspeed.security.impl.UserPrincipalImpl;
  import org.apache.jetspeed.test.JetspeedTest;
  import org.apache.jetspeed.test.JetspeedTestSuite;
  
  /**
   * <p>Unit testing for {@link PermissionManagerService}.</p>
   *
   * @author <a href="mailto:david@sensova.com">David Le Strat</a>
   */
  public class TestPermissionManagerService extends JetspeedTest
  {
  
      private PermissionManagerService pms = null;
      private RoleManagerService rms = null;
      private GroupManagerService gms = null;
      private UserManagerService ums = null;
  
      /**
       * <p>Defines the test case name for junit.</p>
       * @param testName The test case name.
       */
      public TestPermissionManagerService(String testName)
      {
          super(testName);
      }
  
      /**
       * <p>Start the tests.</p>
       * @param args the arguments. Not used
       */
      public static void main(String args[])
      {
          junit.awtui.TestRunner.main(new String[] { TestPermissionManagerService.class.getName()});
      }
  
      /**
       * @see junit.framework.TestCase#setUp()
       */
      public void setUp() throws Exception
      {
          super.setUp();
      }
  
      /**
       * @see junit.framework.TestCase#tearDown()
       */
      public void tearDown() throws Exception
      {
          super.tearDown();
          destroyPermissions();
      }
  
      /**
       * <p>Creates the test suite.</p>
       * @return A test suite (<code>TestSuite</code>) that includes all methods
       *         starting with "test"
       */
      public static Test suite()
      {
          return new JetspeedTestSuite(TestPermissionManagerService.class);
      }
  
      /**
       * <p>Returns the {@link PermissionManagerService}.</p>
       * @return The PermissionManagerService.
       */
      protected PermissionManagerService getPermissionManagerService()
      {
          if (pms == null)
          {
              pms = (PermissionManagerService) CommonPortletServices.getPortalService(PermissionManagerService.SERVICE_NAME);
          }
          return pms;
      }
  
      /**
       * <p>Returns the {@link RoleManagerService}.</p>
       * @return The RoleManagerService.
       */
      protected RoleManagerService getRoleManagerService()
      {
          if (rms == null)
          {
              rms = (RoleManagerService) CommonPortletServices.getPortalService(RoleManagerService.SERVICE_NAME);
          }
          return rms;
      }
  
      /**
       * <p>Returns the {@link GroupManagerService}.</p>
       * @return The GroupManagerService.
       */
      protected GroupManagerService getGroupManagerService()
      {
          if (gms == null)
          {
              gms = (GroupManagerService) CommonPortletServices.getPortalService(GroupManagerService.SERVICE_NAME);
          }
          return gms;
      }
  
      /**
       * <p>Returns the {@link UserManagerService}.</p>
       * @return The UserManagerService.
       */
      protected UserManagerService getUserManagerService()
      {
          if (ums == null)
          {
              ums = (UserManagerService) CommonPortletServices.getPortalService(UserManagerService.SERVICE_NAME);
          }
          return ums;
      }
  
      /**
       * <p>Test that a {@link PermissionManagerService} was returned.</p>
       */
      public void testService()
      {
          assertNotNull(getPermissionManagerService());
      }
  
      /**
       * <p>Test remove principal and associated permissions.</p>
       */
      public void testRemovePrincipalPermissions()
      {
          // Init test.
          PermissionManagerService pms = getPermissionManagerService();
          UserManagerService ums = getUserManagerService();
          UserPrincipal user = new UserPrincipalImpl("test");
          PortletPermission perm = new PortletPermission("anontestportlet", "view, edit");
          try
          {
              ums.addUser(user.getName(), "password");
              pms.grantPermission(user, perm);
          }
          catch (SecurityException sex)
          {
              assertTrue("failed to init testRemovePrincipalPermissions(), " + sex, false);
          }
  
          pms.removePermissions(user);
          Permissions permissions = pms.getPermissions(user);
          assertEquals(
              "permissions should be empty for user " + user.getName(),
              0,
              (Collections.list(permissions.elements())).size());
  
          // Cleanup test.
          ums.removeUser(user.getName());
          pms.removePermission(perm);
      }
  
      /**
       * <p>Test remove permission.</p>
       */
      public void testRemovePermission()
      {
          // Init test.
          PermissionManagerService pms = getPermissionManagerService();
          UserManagerService ums = getUserManagerService();
          RoleManagerService rms = getRoleManagerService();
          UserPrincipal user = new UserPrincipalImpl("removepermission");
          RolePrincipal role = new RolePrincipalImpl("removepermissionrole");
          PortletPermission perm1 = new PortletPermission("removepermission1", "view, edit, delete, minimize, maximize");
          PortletPermission perm2 = new PortletPermission("removepermission2", "view, edit, minimize, maximize");
          try
          {
              ums.addUser(user.getName(), "password");
              rms.addRole(role.getName());
              pms.grantPermission(user, perm1);
              pms.grantPermission(user, perm2);
              pms.grantPermission(role, perm1);
              pms.grantPermission(role, perm2);
          }
          catch (SecurityException sex)
          {
              assertTrue("failed to init testRemovePermission(), " + sex, false);
          }
  
          pms.removePermission(perm1);
          Permissions permCol1 = pms.getPermissions(new UserPrincipalImpl("removepermission"));
          assertTrue(
              "should only contain permission == {name = "
                  + perm2.getName()
                  + "}, {action = "
                  + perm2.getActions()
                  + "}, in collection of size == 1, actual size: "
                  + (Collections.list(permCol1.elements())).size(),
              validatePermissions(permCol1, perm2, 1));
          Permissions permCol2 = pms.getPermissions(new RolePrincipalImpl("removepermissionrole"));
          assertTrue(
              "should only contain permission == {name = "
                  + perm2.getName()
                  + "}, {action = "
                  + perm2.getActions()
                  + "}, in collection of size == 1, actual size: "
                  + (Collections.list(permCol2.elements())).size(),
              validatePermissions(permCol2, perm2, 1));
  
          // Cleanup test.
          ums.removeUser(user.getName());
          pms.removePermission(perm1);
          pms.removePermission(perm2);
      }
  
      /**
       * <p>Test grant permission to principal.</p>
       */
      public void testGrantPermission()
      {
          // Init test.
          PermissionManagerService pms = getPermissionManagerService();
          UserManagerService ums = getUserManagerService();
          UserPrincipal user1 = new UserPrincipalImpl("testgrantpermission1");
          UserPrincipal user2 = new UserPrincipalImpl("testgrantpermission2");
          PortletPermission perm1 = new PortletPermission("testportlet", "view, minimize, delete");
          PortletPermission perm2 = new PortletPermission("testportlet", "view, minimize, maximize, delete");
          try
          {
              ums.addUser(user2.getName(), "password");
          }
          catch (SecurityException sex)
          {
              assertTrue("failed to init testGrantPermission(), " + sex, false);
          }
  
          // Test permission for new permission and new principal (does not exist).      
          try
          {
              pms.grantPermission(user1, perm1);
              assertTrue("principal does not exist. should have caught exception.", false);
          }
          catch (SecurityException sex)
          {
          }
          // Test insert new permission and existing principal.
          try
          {
              pms.grantPermission(user2, perm2);
          }
          catch (SecurityException sex)
          {
              assertTrue("principal does not exist. caught exception, " + sex, false);
          }
          Permissions permCol1 = pms.getPermissions(user2);
          assertTrue(
              "should contain permission == {name = "
                  + perm2.getName()
                  + "}, {action = "
                  + perm2.getActions()
                  + "}, in collection of size == 1, actual size: "
                  + (Collections.list(permCol1.elements())).size(),
              validatePermissions(permCol1, perm2, 1));
          // Test insert duplicate permission for same principal
          try
          {
              pms.grantPermission(user2, perm2);
          }
          catch (SecurityException sex)
          {
              assertTrue("principal does not exist. caught exception, " + sex, false);
          }
          Permissions permCol2 = pms.getPermissions(user2);
          assertTrue(
              "should contain permission == {name = "
                  + perm2.getName()
                  + "}, {action = "
                  + perm2.getActions()
                  + "}, in collection of size == 1, actual size: "
                  + (Collections.list(permCol2.elements())).size(),
              validatePermissions(permCol2, perm2, 1));
  
          // Cleanup test.
          ums.removeUser(user2.getName());
          pms.removePermission(perm1);
          pms.removePermission(perm2);
      }
  
      /**
       * <p>Test get permissions from a principal.</p>
       */
      public void testGetPrincipalPermissions()
      {
          // Init test.
          PermissionManagerService pms = getPermissionManagerService();
          UserManagerService ums = getUserManagerService();
          UserPrincipal user = new UserPrincipalImpl("anon");
          PortletPermission perm1 = new PortletPermission("anontestportlet", "view");
          PortletPermission perm2 = new PortletPermission("anontestportlet", "view, edit");
          try
          {
              ums.addUser(user.getName(), "password");
              pms.grantPermission(user, perm1);
              pms.grantPermission(user, perm2);
          }
          catch (SecurityException sex)
          {
              assertTrue("failed to init testGetPrincipalPermissions(), " + sex, false);
          }
  
          Permissions permissions = pms.getPermissions(user);
          assertTrue(
              "should contain permission == {name = "
                  + perm1.getName()
                  + "}, {action = "
                  + perm1.getActions()
                  + "}, in collection of size == 2, actual size: "
                  + (Collections.list(permissions.elements())).size(),
              validatePermissions(permissions, perm1, 2));
          assertTrue(
              "should contain permission == {name = "
                  + perm2.getName()
                  + "}, {action = "
                  + perm2.getActions()
                  + "}, in collection of size == 2, actual size: "
                  + (Collections.list(permissions.elements())).size(),
              validatePermissions(permissions, perm2, 2));
  
          // Cleanup test.
          ums.removeUser(user.getName());
          pms.removePermission(perm1);
          pms.removePermission(perm2);
      }
  
      /**
       * <p>Test get permissions from a collection of principals.</p>
       */
      public void testGetPermissions()
      {
          // Init test.
          PermissionManagerService pms = getPermissionManagerService();
          UserManagerService ums = getUserManagerService();
          RoleManagerService rms = getRoleManagerService();
          GroupManagerService gms = getGroupManagerService();
          UserPrincipal user = new UserPrincipalImpl("anon");
          RolePrincipal role1 = new RolePrincipalImpl("anonrole1");
          RolePrincipal role2 = new RolePrincipalImpl("anonrole2");
          GroupPrincipal group1 = new GroupPrincipalImpl("anongroup1");
          GroupPrincipal group2 = new GroupPrincipalImpl("anongroup2");
          PortletPermission perm1 = new PortletPermission("anontestportlet", "view");
          PortletPermission perm2 = new PortletPermission("anontestportlet", "view, edit");
          PortletPermission perm3 = new PortletPermission("anontestportlet", "view, edit, delete");
          PortletPermission perm4 = new PortletPermission("anontestportlet", "view, edit, delete, minimize");
          try
          {
              ums.addUser(user.getName(), "password");
              rms.addRole(role1.getName());
              rms.addRole(role2.getName());
              gms.addGroup(group1.getName());
              gms.addGroup(group2.getName());
              pms.grantPermission(role1, perm1);
              pms.grantPermission(role2, perm1);
              pms.grantPermission(role2, perm2);
              pms.grantPermission(role2, perm3);
              pms.grantPermission(role2, perm4);
              pms.grantPermission(group1, perm1);
              pms.grantPermission(group2, perm1);
              pms.grantPermission(group2, perm2);
              pms.grantPermission(group2, perm3);
              pms.grantPermission(group2, perm4);
          }
          catch (SecurityException sex)
          {
              assertTrue("failed to init testGetPrincipalPermissions(), " + sex, false);
          }
  
          ArrayList principals = new ArrayList();
          principals.add(user);
          principals.add(role1);
          principals.add(role2);
          principals.add(group1);
          principals.add(group2);
          Permissions permissions = pms.getPermissions(principals);
          assertTrue(
              "should contain permission == {name = "
                  + perm1.getName()
                  + "}, {action = "
                  + perm1.getActions()
                  + "}, in collection of size == 4, actual size: "
                  + (Collections.list(permissions.elements())).size(),
              validatePermissions(permissions, perm1, 4));
          assertTrue(
              "should contain permission == {name = "
                  + perm2.getName()
                  + "}, {action = "
                  + perm2.getActions()
                  + "}, in collection of size == 4, actual size: "
                  + (Collections.list(permissions.elements())).size(),
              validatePermissions(permissions, perm2, 4));
          assertTrue(
              "should contain permission == {name = "
                  + perm3.getName()
                  + "}, {action = "
                  + perm3.getActions()
                  + "}, in collection of size == 4, actual size: "
                  + (Collections.list(permissions.elements())).size(),
              validatePermissions(permissions, perm3, 4));
          assertTrue(
              "should contain permission == {name = "
                  + perm4.getName()
                  + "}, {action = "
                  + perm4.getActions()
                  + "}, in collection of size == 4, actual size: "
                  + (Collections.list(permissions.elements())).size(),
              validatePermissions(permissions, perm4, 4));
  
          // Cleanup test.
          ums.removeUser(user.getName());
          pms.removePermission(perm1);
          pms.removePermission(perm2);
          pms.removePermission(perm3);
          pms.removePermission(perm4);
      }
  
      /**
       * <p>Test revoke permission.</p>
       */
      public void testRevokePermission()
      {
          // Init test.
          PermissionManagerService pms = getPermissionManagerService();
          UserManagerService ums = getUserManagerService();
          UserPrincipal user = new UserPrincipalImpl("revokepermission");
          PortletPermission perm1 = new PortletPermission("revokepermission1", "view, edit, minimize, maximize");
          PortletPermission perm2 = new PortletPermission("revokepermission2", "view, edit, minimize, maximize");
          try
          {
              ums.addUser(user.getName(), "password");
              pms.grantPermission(user, perm1);
              pms.grantPermission(user, perm2);
          }
          catch (SecurityException sex)
          {
              assertTrue("failed to init testRevokePermission(), " + sex, false);
          }
          pms.revokePermission(user, perm2);
          Permissions permCol = pms.getPermissions(user);
          assertTrue(
              "should only contain permission == {name = "
                  + perm1.getName()
                  + "}, {action = "
                  + perm1.getActions()
                  + "}, in collection of size == 1, actual size: "
                  + (Collections.list(permCol.elements())).size(),
              validatePermissions(permCol, perm1, 1));
  
          // Cleanup test.
          ums.removeUser(user.getName());
          pms.removePermission(perm1);
          pms.removePermission(perm2);
      }
  
      /**
       * <p>Validate whether permission belongs to permissions and whether the permissions
       * size equals the size provided.</p>
       * @param permissions The permissions.
       * @param permission The permission to validate.
       * @param size The permissions expected size.
       * @return
       */
      private boolean validatePermissions(Permissions permissions, Permission permission, int size)
      {
          Enumeration enum = permissions.elements();
          boolean hasPermission = false;
          int count = 0;
          while (enum.hasMoreElements())
          {
              count++;
              Permission enumPerm = (Permission) enum.nextElement();
              if (enumPerm.equals(permission))
              {
                  hasPermission = true;
              }
          }
          boolean validated = ((hasPermission) && (count == size));
          return validated;
      }
  
      /**
       * <p>Destroy permission test objects.</p>
       */
      protected void destroyPermissions()
      {
          PermissionManagerService pms = getPermissionManagerService();
          UserManagerService ums = getUserManagerService();
          RoleManagerService rms = getRoleManagerService();
          GroupManagerService gms = getGroupManagerService();
  
          // Remove users.
          ums.removeUser("anon");
          ums.removeUser("test");
          ums.removeUser("removepermission");
          ums.removeUser("revokepermission");
          ums.removeUser("testgrantpermission2");
          // Remove roles.
          rms.removeRole("anonrole1");
          rms.removeRole("anonrole2");
          rms.removeRole("removepermissionrole");
          // Remove groups.
          gms.removeGroup("anongroup1");
          gms.removeGroup("anongroup2");
          // Remove permissions.
          PortletPermission perm1 = new PortletPermission("anontestportlet", "view");
          PortletPermission perm2 = new PortletPermission("anontestportlet", "view, edit");
          PortletPermission perm3 = new PortletPermission("anontestportlet", "view, edit, delete");
          PortletPermission perm4 = new PortletPermission("anontestportlet", "view, edit, delete, minimize");
          PortletPermission perm5 = new PortletPermission("removepermission1", "view, edit, delete, minimize, maximize");
          PortletPermission perm6 = new PortletPermission("removepermission2", "view, edit, minimize, maximize");
          PortletPermission perm7 = new PortletPermission("revokepermission1", "view, edit, minimize, maximize");
          PortletPermission perm8 = new PortletPermission("revokepermission2", "view, edit, minimize, maximize");
          PortletPermission perm9 = new PortletPermission("testportlet", "view, minimize, delete");
          pms.removePermission(perm1);
          pms.removePermission(perm2);
          pms.removePermission(perm3);
          pms.removePermission(perm4);
          pms.removePermission(perm5);
          pms.removePermission(perm6);
          pms.removePermission(perm7);
          pms.removePermission(perm8);
          pms.removePermission(perm9);
      }
  }
  
  
  
  1.1                  jakarta-jetspeed-2/portal/src/test/org/apache/jetspeed/security/TestGroupManagerService.java
  
  Index: TestGroupManagerService.java
  ===================================================================
  /* ====================================================================
   * The Apache Software License, Version 1.1
   *
   * Copyright (c) 2000-2004 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 acknowledgment:
   *       "This product includes software developed by the
   *        Apache Software Foundation (http://www.apache.org/)."
   *    Alternately, this acknowledgment may appear in the software itself,
   *    if and wherever such third-party acknowledgments normally appear.
   *
   * 4. The names "Apache" and "Apache Software Foundation" and
   *    "Apache Jetspeed" 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",
   *    "Apache Jetspeed", nor may "Apache" appear in their name, without
   *    prior written permission of the Apache Software Foundation.
   *
   * 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/>.
   */
  package org.apache.jetspeed.security;
  
  import java.security.Principal;
  import java.util.ArrayList;
  import java.util.Collection;
  import java.util.HashSet;
  import java.util.Iterator;
  import java.util.Map;
  import java.util.prefs.BackingStoreException;
  import java.util.prefs.Preferences;
  
  import javax.security.auth.Subject;
  
  import junit.framework.Test;
  import junit.framework.TestSuite;
  
  import org.apache.jetspeed.cps.CommonPortletServices;
  import org.apache.jetspeed.security.impl.GroupPrincipalImpl;
  import org.apache.jetspeed.test.JetspeedTest;
  import org.apache.jetspeed.test.JetspeedTestSuite;
  
  /**
   * <p>Unit testing for {@link GroupManagerService}.</p>
   *
   * @author <a href="mailto:david@sensova.com">David Le Strat</a>
   */
  public class TestGroupManagerService extends JetspeedTest
  {
  
      private GroupManagerService gms = null;
      private UserManagerService ums = null;
  
      /**
       * <p>Defines the test case name for junit.</p>
       * @param testName The test case name.
       */
      public TestGroupManagerService(String testName)
      {
          super(testName);
      }
  
      /**
       * <p>Start the tests.</p>
       * @param args the arguments. Not used
       */
      public static void main(String args[])
      {
          junit.awtui.TestRunner.main(new String[] { TestGroupManagerService.class.getName()});
      }
  
      /**
       * @see junit.framework.TestCase#setUp()
       */
      public void setUp() throws Exception
      {
          super.setUp();
      }
  
      /**
       * @see junit.framework.TestCase#tearDown()
       */
      public void tearDown() throws Exception
      {
          super.tearDown();
          destroyGroups();
      }
  
      /**
       * <p>Creates the test suite.</p>
       * @return A test suite (<code>TestSuite</code>) that includes all methods
       *         starting with "test"
       */
      public static Test suite()
      {
          return new JetspeedTestSuite(TestGroupManagerService.class);
      }
  
      /**
       * <p>Returns the {@link GroupManagerService}.</p>
       * @return The GroupManagerService.
       */
      protected GroupManagerService getGroupManagerService()
      {
          if (gms == null)
          {
              gms = (GroupManagerService) CommonPortletServices.getPortalService(GroupManagerService.SERVICE_NAME);
          }
          return gms;
      }
  
      /**
       * <p>Returns the {@link UserManagerService}.</p>
       * @return The UserManagerService.
       */
      protected UserManagerService getUserManagerService()
      {
          if (ums == null)
          {
              ums = (UserManagerService) CommonPortletServices.getPortalService(UserManagerService.SERVICE_NAME);
          }
          return ums;
      }
  
      /**
       * <p>Test that a {@link UserManagerService} was returned.</p>
       */
      public void testService()
      {
          assertNotNull(getGroupManagerService());
      }
  
      /**
       * <p>Test add group.</p>
       */
      public void testAddGroup()
      {
          GroupManagerService gms = getGroupManagerService();
          // Add group with path beginning with '/'.
          try
          {
              gms.addGroup("/testgroup");
          }
          catch (SecurityException sex)
          {
              assertTrue("group should not already exists. exception caught: " + sex, false);
          }
          // Add group without path beginning with '/'.
          try
          {
              gms.addGroup("testgroup/newgroup0");
          }
          catch (SecurityException sex)
          {
              assertTrue("group should not already exists. exception caught: " + sex, false);
          }
          // Add existing group.
          try
          {
              gms.addGroup("/testgroup/newgroup0");
              assertTrue("group should already exists. exception not thrown.", false);
          }
          catch (SecurityException sex)
          {
          }
  
          // Cleanup test.
          gms.removeGroup("/testgroup");
      }
  
      /**
       * <p>Test add user to group.</p>
       */
      public void testAddUserToGroup()
      {
          // Init test.
          GroupManagerService gms = getGroupManagerService();
          UserManagerService ums = getUserManagerService();
          try
          {
              ums.addUser("anonuser1", "password");
              gms.addGroup("/testusertogroup1");
              gms.addGroup("/testusertogroup1/group1");
              gms.addGroup("/testusertogroup1/group2");
          }
          catch (SecurityException sex)
          {
              assertTrue("failed to init testAddUserToGroup(), " + sex, false);
          }
          // Add group with no prior groups.
          try
          {
              gms.addUserToGroup("anonuser1", "/testusertogroup1/group1");
              Collection principals = ums.getUser("anonuser1").getSubject().getPrincipals();
              Principal found =
                  SecurityHelper.getPrincipal(
                      new Subject(false, new HashSet(principals), new HashSet(), new HashSet()),
                      GroupPrincipal.class);
              assertNotNull("found principal is null", found);
              assertTrue(
                  "found principal should be /testusertogroup1/group1, " + found.getName(),
                  found.getName().equals((new GroupPrincipalImpl("/testusertogroup1/group1")).getName()));
          }
          catch (SecurityException sex)
          {
              assertTrue("should add user to group. exception caught: " + sex, false);
          }
          // Add group with existing groups.
          try
          {
              gms.addUserToGroup("anonuser1", "/testusertogroup1/group2");
              Collection principals = ums.getUser("anonuser1").getSubject().getPrincipals();
              assertTrue(
                  "anonuser1 should contain /testusertogroup1/group2",
                  principals.contains(new GroupPrincipalImpl("/testusertogroup1/group2")));
          }
          catch (SecurityException sex)
          {
              assertTrue("should add user to group. exception caught: " + sex, false);
          }
          // Add group when user does not exist.
          try
          {
              gms.addUserToGroup("anonuser123", "/testusertogroup1/group2");
              assertTrue("should catch exception: user does not exist.", false);
          }
          catch (SecurityException sex)
          {
          }
          // Add group when group does not exist.
          try
          {
              gms.addUserToGroup("anonuser1", "/testusertogroup1/group123");
              assertTrue("should catch exception: group does not exist.", false);
          }
          catch (SecurityException sex)
          {
          }
  
          // Cleanup test.
          ums.removeUser("anonuser1");
          gms.removeGroup("/testusertogroup1");
      }
  
      /**
       * <p>Test remove group.</p>
       */
      public void testRemoveGroup()
      {
          // Init test.
          GroupManagerService gms = getGroupManagerService();
          UserManagerService ums = getUserManagerService();
          try
          {
              ums.addUser("anonuser2", "password");
              gms.addGroup("/testgroup1");
              gms.addGroup("/testgroup1/group1");
              gms.addGroup("/testgroup1/group2");
              gms.addGroup("/testgroup2");
              gms.addGroup("/testgroup2/group1");
              gms.addUserToGroup("anonuser2", "/testgroup1/group1");
              gms.addUserToGroup("anonuser2", "/testgroup1/group2");
              gms.addUserToGroup("anonuser2", "/testgroup2/group1");
          }
          catch (SecurityException sex)
          {
              assertTrue("failed to init testRemoveGroup(), " + sex, false);
          }
  
          gms.removeGroup("/testgroup1/group1");
          try
          {
              Collection principals = ums.getUser("anonuser2").getSubject().getPrincipals();
              assertEquals(
                  "principal size should be == 3 after removing /testgroup1/group1, for principals: " + principals.toString(),
                  3,
                  principals.size());
              assertFalse(
                  "anonuser2 should not contain /testgroup1/group1",
                  principals.contains(new GroupPrincipalImpl(GroupPrincipalImpl.getFullPathFromPrincipalName("/testgroup1/group1"))));
          }
          catch (SecurityException sex)
          {
              assertTrue("should remove group. exception caught: " + sex, false);
          }
  
          // Cleanup test.
          ums.removeUser("anonuser2");
          gms.removeGroup("/testgroup1");
          gms.removeGroup("/testgroup2");
      }
  
      /**
       * <p>Test get group.</p>
       */
      public void testGetGroup()
      {
          GroupManagerService gms = getGroupManagerService();
          // Test when the group does not exist.
          try
          {
              Group group = gms.getGroup("/testgroupdoesnotexist");
              assertTrue("group does not exist. should have thrown an exception.", false);
          }
          catch (SecurityException sex)
          {
          }
          // Test when the group exists.
          Group group = null;
          try
          {
              gms.addGroup("/testgetgroup");
              group = gms.getGroup("/testgetgroup");
          }
          catch (SecurityException sex)
          {
              assertTrue("group exists. should not have thrown an exception.", false);
          }
          assertNotNull("group is null", group);
          // Test the GroupPrincipal.
          GroupPrincipal groupPrincipal = group.getPrincipal();
          assertNotNull("group principal is null", groupPrincipal);
          assertEquals(
              "expected group principal full path == /group/testgetgroup",
              "/group/testgetgroup",
              SecurityHelper.getPrincipalFullPath(groupPrincipal));
  
          // Test the Group Preferences.
          Preferences preferences = group.getPreferences();
          assertEquals("expected group node == /group/testgetgroup", "/group/testgetgroup", preferences.absolutePath());
  
          // Cleanup test.
          gms.removeGroup("/testgetgroup");
      }
  
      /**
       * <p>Test get groups for user.</p>
       */
      public void testGetGroupsForUser()
      {
          // Init test.
          GroupManagerService gms = getGroupManagerService();
          UserManagerService ums = getUserManagerService();
          try
          {
              ums.addUser("anonuser2", "password");
              gms.addGroup("/testgroup1");
              gms.addGroup("/testgroup1/group1");
              gms.addGroup("/testgroup1/group2");
              gms.addGroup("/testgroup2");
              gms.addGroup("/testgroup2/group1");
              gms.addUserToGroup("anonuser2", "/testgroup1/group1");
              gms.addUserToGroup("anonuser2", "/testgroup1/group2");
              gms.addUserToGroup("anonuser2", "/testgroup2/group1");
          }
          catch (SecurityException sex)
          {
              assertTrue("failed to init testGetGroupsForUser(), " + sex, false);
          }
  
          try
          {
              Collection groups = gms.getGroupsForUser("anonuser2");
              assertEquals("groups size should be == 3", 3, groups.size());
          }
          catch (SecurityException sex)
          {
              assertTrue("user exists. should not have thrown an exception: " + sex, false);
          }
  
          // Cleanup test.
          ums.removeUser("anonuser2");
          gms.removeGroup("/testgroup1");
          gms.removeGroup("/testgroup2");
      }
  
      /**
       * <p>Test get users in group.</p>
       */
      public void testGetUsersInGroup()
      {
          // Init test.
          GroupManagerService gms = getGroupManagerService();
          UserManagerService ums = getUserManagerService();
          try
          {
              ums.addUser("anonuser2", "password");
              ums.addUser("anonuser3", "password");
              ums.addUser("anonuser4", "password");
              gms.addGroup("/testgroup1");
              gms.addGroup("/testgroup1/group1");
              gms.addUserToGroup("anonuser2", "/testgroup1/group1");
              gms.addUserToGroup("anonuser3", "/testgroup1/group1");
              gms.addUserToGroup("anonuser4", "/testgroup1/group1");
          }
          catch (SecurityException sex)
          {
              assertTrue("failed to init testGetUsersInGroup(), " + sex, false);
          }
  
          try
          {
              Collection users = gms.getUsersInGroup("/testgroup1/group1");
              assertEquals("users size should be == 3", 3, users.size());
          }
          catch (SecurityException sex)
          {
              assertTrue("group exists. should not have thrown an exception: " + sex, false);
          }
  
          // Cleanup test.
          ums.removeUser("anonuser2");
          ums.removeUser("anonuser3");
          ums.removeUser("anonuser4");
          gms.removeGroup("/testgroup1");
      }
  
      /**
       * <p>Test remove user from group.</p>
       */
      public void testRemoveUserFromGroup()
      {
          // Init test.
          GroupManagerService gms = getGroupManagerService();
          UserManagerService ums = getUserManagerService();
          try
          {
              ums.addUser("anonuser4", "password");
              gms.addGroup("/testgroup1");
              gms.addGroup("/testgroup1/group1");
              gms.addUserToGroup("anonuser4", "/testgroup1/group1");
          }
          catch (SecurityException sex)
          {
              assertTrue("failed to init testRemoveUserFromGroup(), " + sex, false);
          }
  
          gms.removeUserFromGroup("anonuser4", "/testgroup1/group1");
          try
          {
              Collection groups = gms.getGroupsForUser("anonuser4");
              assertEquals("groups size should be == 0", 0, groups.size());
          }
          catch (SecurityException sex)
          {
              assertTrue("user exists. should not have thrown an exception: " + sex, false);
          }
  
          // Cleanup test.
          ums.removeUser("anonuser4");
          gms.removeGroup("/testgroup1");
      }
  
      /**
       * <p>Test is user in role.</p>
       */
      public void testIsUserInGroup()
      {
          // Init test.
          GroupManagerService gms = getGroupManagerService();
          UserManagerService ums = getUserManagerService();
          try
          {
              ums.addUser("anonuser3", "password");
              gms.addGroup("/testgroup1");
              gms.addGroup("/testgroup1/group1");
              gms.addUserToGroup("anonuser3", "/testgroup1/group1");
          }
          catch (SecurityException sex)
          {
              assertTrue("failed to init testRemoveUserFromGroup(), " + sex, false);
          }
  
          try
          {
              boolean isUserInGroup = gms.isUserInGroup("anonuser3", "/testgroup1/group1");
              assertTrue("anonuser3 should be in group /testgroup1/group1", isUserInGroup);
          }
          catch (SecurityException sex)
          {
              assertTrue("user and group exist. should not have thrown an exception: " + sex, false);
          }
  
          // Cleanup test.
          ums.removeUser("anonuser4");
          gms.removeGroup("/testgroup1");
      }
  
      /**
       * <p>Destroy group test objects.</p>
       */
      protected void destroyGroups() throws Exception
      {
          UserManagerService ums = getUserManagerService();
          GroupManagerService gms = getGroupManagerService();
          ums.removeUser("anonuser1");
          ums.removeUser("anonuser2");
          ums.removeUser("anonuser3");
          ums.removeUser("anonuser4");
          gms.removeGroup("/testgroup1");
          gms.removeGroup("/testgroup2");
          gms.removeGroup("/testusertogroup1");
          gms.removeGroup("/testgetgroup");
      }
  
  }
  
  
  

---------------------------------------------------------------------
To unsubscribe, e-mail: jetspeed-dev-unsubscribe@jakarta.apache.org
For additional commands, e-mail: jetspeed-dev-help@jakarta.apache.org


Mime
View raw message