You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@jackrabbit.apache.org by ju...@apache.org on 2009/11/25 15:04:50 UTC

svn commit: r884108 [8/10] - in /jackrabbit/sandbox/JCR-1456: ./ jackrabbit-api/ jackrabbit-api/src/main/java/org/apache/jackrabbit/api/security/ jackrabbit-api/src/main/java/org/apache/jackrabbit/api/security/user/ jackrabbit-core/ jackrabbit-core/src...

Modified: jackrabbit/sandbox/JCR-1456/jackrabbit-core/src/test/java/org/apache/jackrabbit/core/security/user/ImpersonationImplTest.java
URL: http://svn.apache.org/viewvc/jackrabbit/sandbox/JCR-1456/jackrabbit-core/src/test/java/org/apache/jackrabbit/core/security/user/ImpersonationImplTest.java?rev=884108&r1=884107&r2=884108&view=diff
==============================================================================
--- jackrabbit/sandbox/JCR-1456/jackrabbit-core/src/test/java/org/apache/jackrabbit/core/security/user/ImpersonationImplTest.java (original)
+++ jackrabbit/sandbox/JCR-1456/jackrabbit-core/src/test/java/org/apache/jackrabbit/core/security/user/ImpersonationImplTest.java Wed Nov 25 14:04:38 2009
@@ -20,6 +20,7 @@
 import org.apache.jackrabbit.api.security.user.Authorizable;
 import org.apache.jackrabbit.api.security.user.User;
 import org.apache.jackrabbit.api.security.user.UserManager;
+import org.apache.jackrabbit.api.security.user.Impersonation;
 import org.apache.jackrabbit.test.NotExecutableException;
 
 import javax.jcr.AccessDeniedException;
@@ -48,7 +49,10 @@
         Principal p = getTestPrincipal();
         String pw = buildPassword(p);
         creds = buildCredentials(p.getName(), pw);
+
         UserImpl u = (UserImpl) userMgr.createUser(p.getName(), pw);
+        save(superuser);
+
         uID = u.getID();
         uSession = getHelper().getRepository().login(creds);
         uMgr = getUserManager(uSession);
@@ -56,7 +60,10 @@
         // create a second user 'below' the first user.
         p = getTestPrincipal();
         pw = buildPassword(p);
+        
         User u2 = userMgr.createUser(p.getName(), pw);
+        save(superuser);
+        
         otherUID = u2.getID();
     }
 
@@ -65,9 +72,14 @@
             uSession.logout();
         } finally {
             Authorizable a = userMgr.getAuthorizable(uID);
-            if (a != null) a.remove();
+            if (a != null) {
+                a.remove();
+            }
             a = userMgr.getAuthorizable(otherUID);
-            if (a != null) a.remove();
+            if (a != null) {
+                a.remove();
+            }
+            save(superuser);
         }
         super.tearDown();
     }
@@ -75,12 +87,24 @@
     public void testModifyOwnImpersonation() throws RepositoryException, NotExecutableException {
         User u = (User) uMgr.getAuthorizable(uID);
 
+        if (!uSession.hasPermission(((UserImpl) u).getNode().getPath(), "set_property")) {
+            throw new NotExecutableException("Users should be able to modify their properties -> Check repository config.");
+        }
+
         Principal otherP = uMgr.getAuthorizable(otherUID).getPrincipal();
 
-        assertTrue(u.getImpersonation().grantImpersonation(otherP));
-        assertTrue(u.getImpersonation().allows(buildSubject(otherP)));
-        assertTrue(u.getImpersonation().revokeImpersonation(otherP));
-        assertFalse(u.getImpersonation().allows(buildSubject(otherP)));
+        Impersonation impers = u.getImpersonation();
+        assertFalse(impers.allows(buildSubject(otherP)));
+
+        assertTrue(impers.grantImpersonation(otherP));
+        save(uSession);
+
+        assertTrue(impers.allows(buildSubject(otherP)));
+
+        assertTrue(impers.revokeImpersonation(otherP));
+        save(uSession);
+
+        assertFalse(impers.allows(buildSubject(otherP)));
     }
 
     public void testModifyOthersImpersonators() throws RepositoryException {
@@ -89,6 +113,7 @@
         User other = (User) uMgr.getAuthorizable(otherUID);
         try {
             boolean success = other.getImpersonation().grantImpersonation(p);
+            // omit save call
             assertFalse("A simple user may not add itself as impersonator to another user.",success);
         } catch (AccessDeniedException e) {
             // fine as well -> access denied.

Modified: jackrabbit/sandbox/JCR-1456/jackrabbit-core/src/test/java/org/apache/jackrabbit/core/security/user/IndexNodeResolverTest.java
URL: http://svn.apache.org/viewvc/jackrabbit/sandbox/JCR-1456/jackrabbit-core/src/test/java/org/apache/jackrabbit/core/security/user/IndexNodeResolverTest.java?rev=884108&r1=884107&r2=884108&view=diff
==============================================================================
--- jackrabbit/sandbox/JCR-1456/jackrabbit-core/src/test/java/org/apache/jackrabbit/core/security/user/IndexNodeResolverTest.java (original)
+++ jackrabbit/sandbox/JCR-1456/jackrabbit-core/src/test/java/org/apache/jackrabbit/core/security/user/IndexNodeResolverTest.java Wed Nov 25 14:04:38 2009
@@ -23,7 +23,6 @@
 import org.slf4j.LoggerFactory;
 
 import javax.jcr.RepositoryException;
-import javax.jcr.Session;
 import javax.jcr.Value;
 import javax.jcr.NodeIterator;
 
@@ -32,11 +31,8 @@
 
     private static Logger log = LoggerFactory.getLogger(IndexNodeResolver.class);
 
-    protected NodeResolver createNodeResolver(Session session) throws RepositoryException, NotExecutableException {
-        if (!(session instanceof SessionImpl)) {
-            throw new NotExecutableException();
-        }
-        return new IndexNodeResolver(session, (SessionImpl) session);
+    protected NodeResolver createNodeResolver(SessionImpl session) throws RepositoryException, NotExecutableException {
+        return new IndexNodeResolver(session, session);
     }
 
 
@@ -48,9 +44,10 @@
      * @throws RepositoryException
      */
     public void testFindNodesNonExact() throws NotExecutableException, RepositoryException {
-        UserImpl currentUser = getCurrentUser(superuser);
+        UserImpl currentUser = getCurrentUser();
         Value vs = superuser.getValueFactory().createValue("value \\, containing backslash");
         currentUser.setProperty(propertyName1, vs);
+        save();
 
         Name propName = ((SessionImpl) superuser).getQName(propertyName1);
         try {
@@ -62,6 +59,7 @@
             assertFalse("expected no more results", result.hasNext());
         } finally {
             currentUser.removeProperty(propertyName1);
+            save();
         }
     }
 }
\ No newline at end of file

Modified: jackrabbit/sandbox/JCR-1456/jackrabbit-core/src/test/java/org/apache/jackrabbit/core/security/user/NodeResolverTest.java
URL: http://svn.apache.org/viewvc/jackrabbit/sandbox/JCR-1456/jackrabbit-core/src/test/java/org/apache/jackrabbit/core/security/user/NodeResolverTest.java?rev=884108&r1=884107&r2=884108&view=diff
==============================================================================
--- jackrabbit/sandbox/JCR-1456/jackrabbit-core/src/test/java/org/apache/jackrabbit/core/security/user/NodeResolverTest.java (original)
+++ jackrabbit/sandbox/JCR-1456/jackrabbit-core/src/test/java/org/apache/jackrabbit/core/security/user/NodeResolverTest.java Wed Nov 25 14:04:38 2009
@@ -19,12 +19,14 @@
 import org.apache.jackrabbit.api.JackrabbitSession;
 import org.apache.jackrabbit.api.security.user.UserManager;
 import org.apache.jackrabbit.api.security.user.Authorizable;
+import org.apache.jackrabbit.api.security.user.Group;
 import org.apache.jackrabbit.core.SessionImpl;
 import org.apache.jackrabbit.spi.Name;
 import org.apache.jackrabbit.spi.commons.name.NameConstants;
 import org.apache.jackrabbit.spi.commons.name.NameFactoryImpl;
 import org.apache.jackrabbit.test.AbstractJCRTest;
 import org.apache.jackrabbit.test.NotExecutableException;
+import org.apache.jackrabbit.util.Text;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -41,37 +43,68 @@
     private static Logger log = LoggerFactory.getLogger(NodeResolverTest.class);
 
     NodeResolver nodeResolver;
+    UserManager umgr;
+    String usersPath = UserConstants.USERS_PATH;
+    String groupsPath = UserConstants.GROUPS_PATH;
+    String authorizablesPath = UserConstants.AUTHORIZABLES_PATH;
 
     protected void setUp() throws Exception {
         super.setUp();
 
         nodeResolver = createNodeResolver(superuser);
-    }
-
-    protected static UserImpl getCurrentUser(Session session) throws NotExecutableException, RepositoryException {
-        if (!(session instanceof JackrabbitSession)) {
+        if (!(superuser instanceof JackrabbitSession)) {
             throw new NotExecutableException();
         }
-        try {
-            UserManager uMgr = ((JackrabbitSession) session).getUserManager();
-            String uid = session.getUserID();
-            if (uid != null) {
-                Authorizable auth = uMgr.getAuthorizable(session.getUserID());
-                if (auth != null && auth instanceof UserImpl) {
-                    return (UserImpl) auth;
-                }
+
+        umgr = ((JackrabbitSession) superuser).getUserManager();
+        if (umgr instanceof UserManagerImpl) {
+            UserManagerImpl uImpl = (UserManagerImpl) umgr;
+            usersPath = uImpl.getUsersPath();
+            groupsPath = uImpl.getGroupsPath();
+
+            authorizablesPath = usersPath;
+            while (!Text.isDescendant(authorizablesPath, groupsPath)) {
+                authorizablesPath = Text.getRelativeParent(authorizablesPath, 1);
+            }
+        }
+    }
+
+    protected UserImpl getCurrentUser() throws NotExecutableException, RepositoryException {
+        String uid = superuser.getUserID();
+        if (uid != null) {
+            Authorizable auth = umgr.getAuthorizable(uid);
+            if (auth != null && auth instanceof UserImpl) {
+                return (UserImpl) auth;
             }
-        } catch (RepositoryException e) {
-            // ignore
         }
         // unable to retrieve current user
         throw new NotExecutableException();
     }
 
-    protected abstract NodeResolver createNodeResolver(Session session) throws RepositoryException, NotExecutableException;
+    protected void save() throws RepositoryException {
+        if (!umgr.isAutoSave() && superuser.hasPendingChanges()) {
+            superuser.save();
+        }
+    }
+
+    protected abstract NodeResolver createNodeResolver(SessionImpl session) throws RepositoryException, NotExecutableException;
+
+    protected NodeResolver createNodeResolver(Session session) throws NotExecutableException, RepositoryException {
+        if (!(session instanceof SessionImpl)) {
+            throw new NotExecutableException();
+        }
+
+        NodeResolver resolver = createNodeResolver((SessionImpl) session);
+        UserManager umr = ((SessionImpl) session).getUserManager();
+        if (umr instanceof UserManagerImpl) {
+            UserManagerImpl uImpl = (UserManagerImpl) umr;
+            resolver.setSearchRoots(uImpl.getUsersPath(), uImpl.getGroupsPath());
+        }
+        return resolver;
+    }
 
     public void testFindNode() throws NotExecutableException, RepositoryException {
-        UserImpl currentUser = getCurrentUser(superuser);
+        UserImpl currentUser = getCurrentUser();
 
         NodeResolver nr = createNodeResolver(currentUser.getNode().getSession());
 
@@ -86,7 +119,7 @@
         result = nr.findNode(currentUser.getNode().getQName(), UserConstants.NT_REP_GROUP);
         assertNull(result);
 
-        Iterator it = currentUser.memberOf();
+        Iterator<Group> it = currentUser.memberOf();
         while (it.hasNext()) {
             GroupImpl gr = (GroupImpl) it.next();
 
@@ -104,7 +137,7 @@
     }
 
     public void testFindNodeByPrincipalName() throws NotExecutableException, RepositoryException {
-        UserImpl currentUser = getCurrentUser(superuser);
+        UserImpl currentUser = getCurrentUser();
 
         NodeResolver nr = createNodeResolver(currentUser.getNode().getSession());
 
@@ -112,7 +145,7 @@
         assertNotNull(result);
         assertTrue(currentUser.getNode().isSame(result));
 
-        Iterator it = currentUser.memberOf();
+        Iterator<Group> it = currentUser.memberOf();
         while (it.hasNext()) {
             GroupImpl gr = (GroupImpl) it.next();
 
@@ -126,13 +159,14 @@
     }
 
     public void testFindNodeByMultiValueProp() throws NotExecutableException, RepositoryException {
-        UserImpl currentUser = getCurrentUser(superuser);
+        UserImpl currentUser = getCurrentUser();
 
         Value[] vs = new Value[] {
                 superuser.getValueFactory().createValue("blub"),
                 superuser.getValueFactory().createValue("blib")
         };
         currentUser.setProperty(propertyName1, vs);
+        save();
 
         NodeResolver nr = createNodeResolver(currentUser.getNode().getSession());
 
@@ -142,6 +176,7 @@
         assertTrue(currentUser.getNode().isSame(result));
 
         currentUser.removeProperty(propertyName1);
+        save();
     }
 
     public void testFindNodeWithNonExistingSearchRoot() throws NotExecutableException, RepositoryException {
@@ -161,14 +196,17 @@
                 superuser.getValueFactory().createValue("blib")
         };
 
-        UserImpl currentUser = getCurrentUser(superuser);
+        UserImpl currentUser = getCurrentUser();
         currentUser.setProperty(propertyName1, vs);
 
-        Iterator it = currentUser.memberOf();
+        int expResultSize = 1;
+        Iterator<Group> it = currentUser.memberOf();
         while (it.hasNext()) {
             GroupImpl gr = (GroupImpl) it.next();
             gr.setProperty(propertyName1, vs);
+            expResultSize++;
         }
+        save();
 
         Name propName = ((SessionImpl) superuser).getQName(propertyName1);
 
@@ -181,7 +219,7 @@
             assertFalse("expected no more results", result.hasNext());
 
             result = nr.findNodes(propName, "blub", UserConstants.NT_REP_AUTHORIZABLE, false);
-            assertTrue(getSize(result) > 1);
+            assertEquals(expResultSize, getSize(result));
 
         } finally {
             currentUser.removeProperty(propertyName1);
@@ -190,6 +228,7 @@
                 GroupImpl gr = (GroupImpl) it.next();
                 gr.removeProperty(propertyName1);
             }
+            save();
         }
     }
 
@@ -207,25 +246,25 @@
     public void testGetSearchRoot() {
         String searchRoot = nodeResolver.getSearchRoot(UserConstants.NT_REP_AUTHORIZABLE);
         assertNotNull(searchRoot);
-        assertEquals(UserConstants.AUTHORIZABLES_PATH, searchRoot);
+        assertEquals(authorizablesPath, searchRoot);
 
         searchRoot = nodeResolver.getSearchRoot(UserConstants.NT_REP_GROUP);
         assertNotNull(searchRoot);
-        assertEquals(UserConstants.GROUPS_PATH, searchRoot);
+        assertEquals(groupsPath, searchRoot);
 
         searchRoot = nodeResolver.getSearchRoot(UserConstants.NT_REP_USER);
         assertNotNull(searchRoot);
-        assertEquals(UserConstants.USERS_PATH, searchRoot);
+        assertEquals(usersPath, searchRoot);
     }
 
     public void testGetSearchRootDefault() {
         String searchRoot = nodeResolver.getSearchRoot(UserConstants.NT_REP_AUTHORIZABLE_FOLDER);
         assertNotNull(searchRoot);
-        assertEquals(UserConstants.AUTHORIZABLES_PATH, searchRoot);
+        assertEquals(authorizablesPath, searchRoot);
 
         searchRoot = nodeResolver.getSearchRoot(NameConstants.NT_UNSTRUCTURED);
         assertNotNull(searchRoot);
-        assertEquals(UserConstants.AUTHORIZABLES_PATH, searchRoot);
+        assertEquals(authorizablesPath, searchRoot);
     }
 
     public void testGetNamePathResolver() {

Modified: jackrabbit/sandbox/JCR-1456/jackrabbit-core/src/test/java/org/apache/jackrabbit/core/security/user/NotUserAdministratorTest.java
URL: http://svn.apache.org/viewvc/jackrabbit/sandbox/JCR-1456/jackrabbit-core/src/test/java/org/apache/jackrabbit/core/security/user/NotUserAdministratorTest.java?rev=884108&r1=884107&r2=884108&view=diff
==============================================================================
--- jackrabbit/sandbox/JCR-1456/jackrabbit-core/src/test/java/org/apache/jackrabbit/core/security/user/NotUserAdministratorTest.java (original)
+++ jackrabbit/sandbox/JCR-1456/jackrabbit-core/src/test/java/org/apache/jackrabbit/core/security/user/NotUserAdministratorTest.java Wed Nov 25 14:04:38 2009
@@ -49,7 +49,10 @@
         // created for that new user.
         Principal p = getTestPrincipal();
         String pw = buildPassword(p);
+
         UserImpl u = (UserImpl) userMgr.createUser(p.getName(), pw);
+        save(superuser);
+        
         uID = u.getID();
 
         // create a session for the other user.
@@ -66,15 +69,18 @@
             Authorizable a = userMgr.getAuthorizable(uID);
             if (a != null) {
                 a.remove();
+                save(superuser);
             }
         }
         super.tearDown();
     }
 
-    public void testCreateUser() {
+    public void testCreateUser() throws NotExecutableException {
         try {
             Principal p = getTestPrincipal();
             User u = uMgr.createUser(p.getName(), buildPassword(p));
+            save(uSession);
+
             fail("A non-UserAdmin should not be allowed to create a new User.");
 
             // clean-up: let superuser remove the user created by fault.
@@ -87,10 +93,12 @@
         }
     }
 
-    public void testCreateUserWithItermediatePath() {
+    public void testCreateUserWithItermediatePath() throws NotExecutableException {
         try {
             Principal p = getTestPrincipal();
             User u = uMgr.createUser(p.getName(), buildPassword(p), p, "/any/intermediate/path");
+            save(uSession);
+
             fail("A non-UserAdmin should not be allowed to create a new User.");
 
             // clean-up: let superuser remove the user created by fault.
@@ -103,101 +111,96 @@
         }
     }
 
-    public void testRemoveOwnAuthorizable() throws RepositoryException {
+    public void testRemoveOwnAuthorizable() throws RepositoryException, NotExecutableException {
         Authorizable himself = uMgr.getAuthorizable(uID);
         try {
             himself.remove();
+            save(uSession);
+
             fail("A user should not be allowed to remove him/herself.");
         } catch (AccessDeniedException e) {
             // success
         }
     }
 
-    public void testRemoveChildUser() throws RepositoryException {
-        // let superuser create a child-user.
+    public void testRemoveUser() throws RepositoryException, NotExecutableException {
+        // let superuser create another user.
         Principal p = getTestPrincipal();
-        String childID = userMgr.createUser(p.getName(), buildPassword(p)).getID();
+        String user2ID = userMgr.createUser(p.getName(), buildPassword(p)).getID();
+        save(superuser);
+
         try {
-            Authorizable a = uMgr.getAuthorizable(childID);
+            Authorizable a = uMgr.getAuthorizable(user2ID);
             a.remove();
-            fail("A non-administrator user should not be allowed to remove a child-user.");
+            save(uSession);
+
+            fail("A non-administrator user should not be allowed to remove another user.");
         } catch (AccessDeniedException e) {
             // success
         }
 
         // let superuser do clean up.
-        Authorizable child = userMgr.getAuthorizable(childID);
-        if (child != null) {
-            child.remove();
+        Authorizable user2 = userMgr.getAuthorizable(user2ID);
+        if (user2 != null) {
+            user2.remove();
+            save(superuser);
         }
     }
 
-    public void testRemoveOtherUser() throws RepositoryException {
-        // let superuser create a child-user.
+    public void testRemoveOtherUser() throws RepositoryException, NotExecutableException {
+        // let superuser create another user.
         Principal p = getTestPrincipal();
-        String childID = userMgr.createUser(p.getName(), buildPassword(p), p, "/any/intermediate/path").getID();
+        String user2ID = userMgr.createUser(p.getName(), buildPassword(p), p, "/any/intermediate/path").getID();
+        save(superuser);
+
         try {
-            Authorizable a = uMgr.getAuthorizable(childID);
+            Authorizable a = uMgr.getAuthorizable(user2ID);
             a.remove();
+            save(uSession);
+
             fail("A non-administrator user should not be allowed to remove another user.");
         } catch (AccessDeniedException e) {
             // success
         }
 
         // let superuser do clean up.
-        Authorizable child = userMgr.getAuthorizable(childID);
-        if (child != null) {
-            child.remove();
+        Authorizable user2 = userMgr.getAuthorizable(user2ID);
+        if (user2 != null) {
+            user2.remove();
+            save(superuser);
         }
     }
 
-    public void testModifyImpersonation() throws RepositoryException {
-        // let superuser create a child-user.
+    public void testModifyImpersonationOfAnotherUser() throws RepositoryException, NotExecutableException {
+        // let superuser create another user.
         Principal p = getTestPrincipal();
-        Authorizable child = userMgr.createUser(p.getName(), buildPassword(p));
-        try {
-            p = child.getPrincipal();
-
-            Authorizable himself = uMgr.getAuthorizable(uID);
-            Impersonation impers = ((User) himself).getImpersonation();
+        String user2ID = userMgr.createUser(p.getName(), buildPassword(p)).getID();
+        save(superuser);
 
-            assertFalse(impers.allows(buildSubject(p)));
-            assertTrue(impers.grantImpersonation(p));
-            assertTrue(impers.allows(buildSubject(p)));
-            assertTrue(impers.revokeImpersonation(p));
-            assertFalse(impers.allows(buildSubject(p)));
-
-        } finally {
-            // let superuser do clean up.
-            child.remove();
-        }
-    }
-
-    public void testModifyImpersonationOfChildUser() throws RepositoryException {
-        // let superuser create a child-user.
-        Principal p = getTestPrincipal();
-        String childID = userMgr.createUser(p.getName(), buildPassword(p)).getID();
         try {
-            Authorizable child = uMgr.getAuthorizable(childID);
+            Authorizable a = uMgr.getAuthorizable(user2ID);
 
-            Impersonation impers = ((User) child).getImpersonation();
+            Impersonation impers = ((User) a).getImpersonation();
             Principal himselfP = uMgr.getAuthorizable(uID).getPrincipal();
             assertFalse(impers.allows(buildSubject(himselfP)));
             impers.grantImpersonation(himselfP);
-            fail("A non-administrator user should not be allowed modify Impersonation of a child user.");
+            save(uSession);
+
+            fail("A non-administrator user should not be allowed modify Impersonation of another user.");
         } catch (AccessDeniedException e) {
             // success
         }
 
         // let superuser do clean up.
-        Authorizable child = userMgr.getAuthorizable(childID);
-        if (child != null) {
-            child.remove();
+        Authorizable user2 = userMgr.getAuthorizable(user2ID);
+        if (user2 != null) {
+            user2.remove();
+            save(superuser);
         }
     }
 
     public void testAddToGroup() throws NotExecutableException, RepositoryException {
-        Authorizable auth = userMgr.getAuthorizable(SecurityConstants.ADMINISTRATORS_NAME);
+        Authorizable auth = uMgr.getAuthorizable(SecurityConstants.ADMINISTRATORS_NAME);
         if (auth == null || !auth.isGroup()) {
             throw new NotExecutableException("Couldn't find 'administrators' group");
         }
@@ -206,10 +209,15 @@
         try {
             auth = uMgr.getAuthorizable(uID);
             gr.addMember(auth);
+            save(uSession);
+
             fail("a common user should not be allowed to modify any groups.");
-            gr.removeMember(auth);
         } catch (AccessDeniedException e) {
             // success
+        } finally {
+            if (gr.removeMember(auth)) {
+                save(uSession);
+            }
         }
     }
 }
\ No newline at end of file

Modified: jackrabbit/sandbox/JCR-1456/jackrabbit-core/src/test/java/org/apache/jackrabbit/core/security/user/TestAll.java
URL: http://svn.apache.org/viewvc/jackrabbit/sandbox/JCR-1456/jackrabbit-core/src/test/java/org/apache/jackrabbit/core/security/user/TestAll.java?rev=884108&r1=884107&r2=884108&view=diff
==============================================================================
--- jackrabbit/sandbox/JCR-1456/jackrabbit-core/src/test/java/org/apache/jackrabbit/core/security/user/TestAll.java (original)
+++ jackrabbit/sandbox/JCR-1456/jackrabbit-core/src/test/java/org/apache/jackrabbit/core/security/user/TestAll.java Wed Nov 25 14:04:38 2009
@@ -45,7 +45,9 @@
         suite.addTestSuite(IndexNodeResolverTest.class);
         suite.addTestSuite(TraversingNodeResolverTest.class);
 
-        suite.addTestSuite(IdResolverTest.class);
+        suite.addTestSuite(NodeCreationTest.class);
+
+        suite.addTestSuite(UserImporterTest.class);
 
         return suite;
     }

Modified: jackrabbit/sandbox/JCR-1456/jackrabbit-core/src/test/java/org/apache/jackrabbit/core/security/user/TraversingNodeResolverTest.java
URL: http://svn.apache.org/viewvc/jackrabbit/sandbox/JCR-1456/jackrabbit-core/src/test/java/org/apache/jackrabbit/core/security/user/TraversingNodeResolverTest.java?rev=884108&r1=884107&r2=884108&view=diff
==============================================================================
--- jackrabbit/sandbox/JCR-1456/jackrabbit-core/src/test/java/org/apache/jackrabbit/core/security/user/TraversingNodeResolverTest.java (original)
+++ jackrabbit/sandbox/JCR-1456/jackrabbit-core/src/test/java/org/apache/jackrabbit/core/security/user/TraversingNodeResolverTest.java Wed Nov 25 14:04:38 2009
@@ -22,17 +22,13 @@
 import org.slf4j.LoggerFactory;
 
 import javax.jcr.RepositoryException;
-import javax.jcr.Session;
 
 /** <code>TraversingNodeResolverTest</code>... */
 public class TraversingNodeResolverTest extends NodeResolverTest {
 
     private static Logger log = LoggerFactory.getLogger(TraversingNodeResolverTest.class);
 
-    protected NodeResolver createNodeResolver(Session session) throws RepositoryException, NotExecutableException {
-        if (!(session instanceof SessionImpl)) {
-            throw new NotExecutableException();
-        }
-        return new TraversingNodeResolver(session, (SessionImpl) session);
+    protected NodeResolver createNodeResolver(SessionImpl session) throws RepositoryException, NotExecutableException {
+        return new TraversingNodeResolver(session, session);
     }
 }
\ No newline at end of file

Modified: jackrabbit/sandbox/JCR-1456/jackrabbit-core/src/test/java/org/apache/jackrabbit/core/security/user/UserAdministratorTest.java
URL: http://svn.apache.org/viewvc/jackrabbit/sandbox/JCR-1456/jackrabbit-core/src/test/java/org/apache/jackrabbit/core/security/user/UserAdministratorTest.java?rev=884108&r1=884107&r2=884108&view=diff
==============================================================================
--- jackrabbit/sandbox/JCR-1456/jackrabbit-core/src/test/java/org/apache/jackrabbit/core/security/user/UserAdministratorTest.java (original)
+++ jackrabbit/sandbox/JCR-1456/jackrabbit-core/src/test/java/org/apache/jackrabbit/core/security/user/UserAdministratorTest.java Wed Nov 25 14:04:38 2009
@@ -40,10 +40,10 @@
  */
 public class UserAdministratorTest extends AbstractUserTest {
 
-    // user 'above'
+    // a test user
     private String uID;
 
-    // user-admin 'below'
+    // a test user being member of the user-admin group
     private String otherUID;
     private Session otherSession;
 
@@ -57,6 +57,8 @@
         // created for that new user.
         Principal p = getTestPrincipal();
         UserImpl u = (UserImpl) userMgr.createUser(p.getName(), buildPassword(p));
+        save(superuser);
+
         uID = u.getID();
 
         // create a second user
@@ -64,12 +66,14 @@
         String pw = buildPassword(p);
         Credentials otherCreds = buildCredentials(p.getName(), pw);
         User other = userMgr.createUser(p.getName(), pw);
+        save(superuser);
+
         otherUID = other.getID();
 
         // make other user a user-administrator:
         Authorizable ua = userMgr.getAuthorizable(UserConstants.USER_ADMIN_GROUP_NAME);
         if (ua == null || !ua.isGroup()) {
-            throw new NotExecutableException("Cannot execute test. User-Admin name has been changed by config.");
+            throw new NotExecutableException("Cannot execute test. No user-administrator group found.");
         }
         uAdministrators = (Group) ua;
         uAdministrators.addMember(other);
@@ -86,8 +90,8 @@
         } finally {
             Authorizable a = userMgr.getAuthorizable(otherUID);
             if (a != null) {
-                for (Iterator it = a.memberOf(); it.hasNext();) {
-                    Group gr = (Group) it.next();
+                for (Iterator<Group> it = a.memberOf(); it.hasNext();) {
+                    Group gr = it.next();
                     if (!gr.getPrincipal().equals(EveryonePrincipal.getInstance())) {
                         gr.removeMember(a);
                     }
@@ -98,6 +102,7 @@
             if (a != null) {
                 a.remove();
             }
+            save(superuser);
         }
         super.tearDown();
     }
@@ -110,13 +115,13 @@
         return (Group) auth;
     }
 
-    public void testUserIsUserAdmin() throws RepositoryException, NotExecutableException {
-        Set principals = getPrincipalSetFromSession(otherSession);
-        boolean isAdmin = false;
-        for (Iterator it = principals.iterator(); it.hasNext() && !isAdmin;) {
-           isAdmin = UserConstants.USER_ADMIN_GROUP_NAME.equals(((Principal) it.next()).getName());
+    public void testIsUserAdministrator() throws RepositoryException, NotExecutableException {
+        Set<Principal> principals = getPrincipalSetFromSession(otherSession);
+        boolean isUserAdmin = false;
+        for (Iterator<Principal> it = principals.iterator(); it.hasNext() && !isUserAdmin;) {
+           isUserAdmin = UserConstants.USER_ADMIN_GROUP_NAME.equals(it.next().getName());
         }
-        assertTrue(isAdmin);
+        assertTrue(isUserAdmin);
     }
 
     public void testCreateUser() throws RepositoryException, NotExecutableException {
@@ -126,9 +131,11 @@
         try {
             Principal p = getTestPrincipal();
             u = (UserImpl) umgr.createUser(p.getName(), buildPassword(p));
+            save(otherSession);
         } finally {
             if (u != null) {
                 u.remove();
+                save(otherSession);
             }
         }
     }
@@ -152,11 +159,14 @@
         for (String intermediatePath : m.keySet()) {
             try {
                 u = (UserImpl) umgr.createUser(p.getName(), buildPassword(p), p, intermediatePath);
+                save(otherSession);
+
                 String expPath = m.get(intermediatePath);
                 assertEquals(expPath, u.getNode().getPath());
             } finally {
                 if (u != null) {
                     u.remove();
+                    save(otherSession);
                 }
             }
         }
@@ -170,12 +180,15 @@
         try {
             Principal p = getTestPrincipal();
             u = (UserImpl) umgr.createUser(p.getName(), buildPassword(p), p, invalidIntermediatePath);
+            save(otherSession);
+
             fail("An attempt to create a user below an existing user must fail.");
         } catch (RepositoryException e) {
             // success
         } finally {
             if (u != null) {
                 u.remove();
+                save(otherSession);
             }
         }
     }
@@ -186,6 +199,8 @@
         Authorizable himself = umgr.getAuthorizable(otherUID);
         try {
             himself.remove();
+            save(otherSession);
+
             fail("A UserAdministrator should not be allowed to remove himself.");
         } catch (AccessDeniedException e) {
             // success
@@ -203,6 +218,7 @@
 
         Authorizable user = umgr.getAuthorizable(uID);
         user.remove();
+        save(otherSession);
     }
 
     public void testModifyImpersonationOfUser() throws RepositoryException, NotExecutableException {
@@ -214,26 +230,36 @@
         try {
             Principal p = getTestPrincipal();
             u = umgr.createUser(p.getName(), buildPassword(p));
+            save(otherSession);
 
             Impersonation impers = u.getImpersonation();
             assertFalse(impers.allows(buildSubject(otherP)));
+
             assertTrue(impers.grantImpersonation(otherP));
+            save(otherSession);
+
             assertTrue(impers.allows(buildSubject(otherP)));
         } finally {
             // impersonation get removed while removing the user u.
             if (u != null) {
                 u.remove();
+                save(otherSession);
             }
         }
 
         // modify impersonation of another user
         u = (User) umgr.getAuthorizable(uID);
         Impersonation uImpl = u.getImpersonation();
+
         if (!uImpl.allows(buildSubject(otherP))) {
             // ... trying to modify 'impersonators of another user must succeed
             assertTrue(uImpl.grantImpersonation(otherP));
+            save(otherSession);
+
             assertTrue(uImpl.allows(buildSubject(otherP)));
+
             uImpl.revokeImpersonation(otherP);
+            save(otherSession);
         } else {
             throw new NotExecutableException("Cannot execute test. OtherP can already impersonate UID-user.");
         }
@@ -246,8 +272,14 @@
         Group gr = getGroupAdminGroup(umgr);
         try {
             assertFalse(gr.addMember(userHimSelf));
+            // conditional save call omitted.
         } catch (RepositoryException e) {
             // success as well.
+        } finally {
+            // clean up using the superuser
+            if (getGroupAdminGroup(userMgr).removeMember(userMgr.getAuthorizable(otherUID))) {
+                save(superuser);
+            }
         }
     }
 
@@ -270,9 +302,13 @@
         User childU = null;
         try {
             childU = umgr.createUser(cp.getName(), buildPassword(cp));
+            save(otherSession);
+
             Group gr = getGroupAdminGroup(umgr);
             try {
-                assertFalse("A UserAdmin must not be allowed to modify group memberships", gr.addMember(childU));
+                assertFalse("A UserAdmin must not be allowed to modify group " +
+                        "memberships", gr.addMember(childU));
+                // con-save call omitted.
             } catch (RepositoryException e) {
                 // success
             }
@@ -285,23 +321,49 @@
 
     public void testCreateGroup() throws RepositoryException, NotExecutableException {
         UserManager umgr = getUserManager(otherSession);
+        String grId = null;
         try {
             Group testGroup = umgr.createGroup(getTestPrincipal());
+            save(otherSession);
+            grId = testGroup.getID();
+
             fail("UserAdmin should not be allowed to create a new Group.");
-            testGroup.remove();
+
         } catch (RepositoryException e) {
             // success.
+        } finally {
+            // let superuser clean up
+            if (grId != null) {
+                Authorizable gr = userMgr.getAuthorizable(grId);
+                if (gr != null) {
+                    gr.remove();
+                    save(superuser);
+                }
+            }
         }
     }
 
     public void testCreateGroupWithIntermediatePath() throws RepositoryException, NotExecutableException {
         UserManager umgr = getUserManager(otherSession);
+        String grId = null;
         try {
             Group testGroup = umgr.createGroup(getTestPrincipal(), "/any/intermediate/path");
-            fail("UserAdmin should not be allowed to create a new Group.");
-            testGroup.remove();
+            save(otherSession);
+            grId = testGroup.getID();
+
+            fail("UserAdmin should not be allowed to create a new Group with intermediate path.");
+
         } catch (RepositoryException e) {
             // success.
+        } finally {
+            // let superuser clean up
+            if (grId != null) {
+                Authorizable gr = userMgr.getAuthorizable(grId);
+                if (gr != null) {
+                    gr.remove();
+                    save(superuser);
+                }
+            }
         }
     }
 
@@ -310,13 +372,18 @@
         Group g = null;
         try {
             g = userMgr.createGroup(getTestPrincipal());
+            save(superuser);
+
             umgr.getAuthorizable(g.getID()).remove();
+            save(otherSession);
+
             fail("UserAdmin should not be allowed to remove a Group.");
         } catch (RepositoryException e) {
             // success.
         } finally {
             if (g != null) {
                 g.remove();
+                save(superuser);
             }
         }
     }
@@ -328,6 +395,7 @@
         Authorizable auth = umgr.getAuthorizable(uID);
         try {
             assertFalse(gr.addMember(auth));
+            // omit conditional save call.
         } catch (AccessDeniedException e) {
             // success as well.
         }
@@ -335,6 +403,7 @@
         auth = umgr.getAuthorizable(otherUID);
         try {
             assertFalse(gr.addMember(auth));
+            // omit conditional save call.
         } catch (AccessDeniedException e) {
             // success as well.
         }
@@ -344,6 +413,7 @@
         auth = umgr.getAuthorizable(otherUID);
         try {
             assertFalse(gr.addMember(auth));
+            // omit cond-save call.
         } catch (AccessDeniedException e) {
             // success
         }
@@ -356,6 +426,7 @@
         try {
             Principal p = getTestPrincipal();
             u = (UserImpl) umgr.createUser(p.getName(), buildPassword(p));
+            save(otherSession);
 
             Authorizable az = userMgr.getAuthorizable(u.getID());
             assertNotNull(az);
@@ -363,6 +434,7 @@
         } finally {
             if (u != null) {
                 u.remove();
+                save(otherSession);
             }
         }
     }

Modified: jackrabbit/sandbox/JCR-1456/jackrabbit-core/src/test/java/org/apache/jackrabbit/core/security/user/UserImplTest.java
URL: http://svn.apache.org/viewvc/jackrabbit/sandbox/JCR-1456/jackrabbit-core/src/test/java/org/apache/jackrabbit/core/security/user/UserImplTest.java?rev=884108&r1=884107&r2=884108&view=diff
==============================================================================
--- jackrabbit/sandbox/JCR-1456/jackrabbit-core/src/test/java/org/apache/jackrabbit/core/security/user/UserImplTest.java (original)
+++ jackrabbit/sandbox/JCR-1456/jackrabbit-core/src/test/java/org/apache/jackrabbit/core/security/user/UserImplTest.java Wed Nov 25 14:04:38 2009
@@ -30,6 +30,7 @@
 import javax.jcr.RepositoryException;
 import javax.jcr.Session;
 import javax.jcr.SimpleCredentials;
+import javax.jcr.Value;
 import java.io.UnsupportedEncodingException;
 import java.security.NoSuchAlgorithmException;
 import java.security.Principal;
@@ -52,7 +53,10 @@
         Principal p = getTestPrincipal();
         String pw = buildPassword(p);
         creds = new SimpleCredentials(p.getName(), pw.toCharArray());
+
         User u = userMgr.createUser(p.getName(), pw);
+        save(superuser);
+
         uID = u.getID();
         uSession = getHelper().getRepository().login(creds);
         uMgr = getUserManager(uSession);
@@ -61,6 +65,7 @@
     protected void tearDown() throws Exception {
         try {
             userMgr.getAuthorizable(uID).remove();
+            save(superuser);
         } finally {
             uSession.logout();
         }
@@ -81,17 +86,38 @@
         assertFalse(auth.isGroup());
     }
 
-    public void testUserCanModifyItsOwnProperties() throws RepositoryException {
+    public void testUserCanModifyItsOwnProperties() throws RepositoryException, NotExecutableException {
         User u = (User) uMgr.getAuthorizable(uID);
         if (u == null) {
             fail("User " +uID+ "hast not been removed and must be visible to the Session created with its credentials.");
         }
 
+        if (!uSession.hasPermission(((UserImpl) u).getNode().getPath(), "set_property")) {
+            throw new NotExecutableException("Users should be able to modify their properties -> Check repository config.");
+        }
+
+        // single valued properties
         u.setProperty("Email", new StringValue("tu@security.test"));
+        save(uSession);
+
+        assertNotNull(u.getProperty("Email"));
         assertEquals("tu@security.test", u.getProperty("Email")[0].getString());
 
         u.removeProperty("Email");
+        save(uSession);
+
         assertNull(u.getProperty("Email"));
+
+        // multivalued properties
+        u.setProperty(propertyName1, new Value[] {uSession.getValueFactory().createValue("anyValue")});
+        save(uSession);
+
+        assertNotNull(u.getProperty(propertyName1));
+
+        u.removeProperty(propertyName1);
+        save(uSession);
+        
+        assertNull(u.getProperty(propertyName1));
     }
 
     public void testChangePassword() throws RepositoryException, NotExecutableException, NoSuchAlgorithmException, UnsupportedEncodingException {
@@ -104,11 +130,13 @@
         User user = getTestUser(superuser);
         try {
             user.changePassword("pw");
+            save(superuser);
 
             SimpleCredentials creds = new SimpleCredentials(user.getID(), "pw".toCharArray());
             assertTrue(((CryptedSimpleCredentials) user.getCredentials()).matches(creds));
         } finally {
             user.changePassword(oldPw);
+            save(superuser);
         }
     }
 }

Modified: jackrabbit/sandbox/JCR-1456/jackrabbit-core/src/test/java/org/apache/jackrabbit/core/security/user/UserManagerImplTest.java
URL: http://svn.apache.org/viewvc/jackrabbit/sandbox/JCR-1456/jackrabbit-core/src/test/java/org/apache/jackrabbit/core/security/user/UserManagerImplTest.java?rev=884108&r1=884107&r2=884108&view=diff
==============================================================================
--- jackrabbit/sandbox/JCR-1456/jackrabbit-core/src/test/java/org/apache/jackrabbit/core/security/user/UserManagerImplTest.java (original)
+++ jackrabbit/sandbox/JCR-1456/jackrabbit-core/src/test/java/org/apache/jackrabbit/core/security/user/UserManagerImplTest.java Wed Nov 25 14:04:38 2009
@@ -21,7 +21,6 @@
 import org.apache.jackrabbit.api.security.user.Group;
 import org.apache.jackrabbit.api.security.user.User;
 import org.apache.jackrabbit.api.security.user.UserManager;
-import org.apache.jackrabbit.core.NodeImpl;
 import org.apache.jackrabbit.core.SessionImpl;
 import org.apache.jackrabbit.core.security.TestPrincipal;
 import org.apache.jackrabbit.test.NotExecutableException;
@@ -32,10 +31,12 @@
 import javax.jcr.Session;
 import javax.jcr.SimpleCredentials;
 import javax.jcr.Value;
-import javax.jcr.nodetype.ConstraintViolationException;
+import javax.jcr.Node;
 import java.security.Principal;
 import java.util.Iterator;
 import java.util.Set;
+import java.util.List;
+import java.util.ArrayList;
 
 /**
  * <code>UserManagerImplTest</code>...
@@ -63,55 +64,24 @@
         return userId;
     }
 
-    public void testCreateNodesDirectly() throws NotExecutableException, RepositoryException {
-        User u = getTestUser(superuser);
-        if (u instanceof UserImpl) {
-            throw new NotExecutableException();
-        }
-
-        NodeImpl n = ((UserImpl)u).getNode();
-        try {
-            n.addNode("anyname", "rep:AuthorizableFolder");
-            fail("security nodes must be protected.");
-        } catch (ConstraintViolationException e) {
-            // success
-        } finally {
-            n.refresh(false);
-        }
-        try {
-            n.addNode("anyname", "rep:User");
-            fail("security nodes must be protected.");
-        } catch (ConstraintViolationException e) {
-            // success
-        } finally {
-            n.refresh(false);
-        }
-        try {
-            n.setProperty("rep:userId", "someotherUID");
-            fail("security nodes must be protected.");
-        } catch (ConstraintViolationException e) {
-            // success
-        } finally {
-            n.refresh(false);
-        }
-    }
-
-    public void testPrincipalNameEqualsUserID() throws RepositoryException {
+    public void testPrincipalNameEqualsUserID() throws RepositoryException, NotExecutableException {
         Principal p = getTestPrincipal();
         User u = null;
         try {
             u = userMgr.createUser(p.getName(), buildPassword(p));
+            save(superuser);
 
             String msg = "Implementation specific: User.getID() must return the userID pass to createUser.";
             assertEquals(msg, u.getID(), p.getName());
         } finally {
             if (u != null) {
                 u.remove();
+                save(superuser);
             }
         }
     }
 
-    public void testUserIDFromSession() throws RepositoryException {
+    public void testUserIDFromSession() throws RepositoryException, NotExecutableException {
         Principal p = getTestPrincipal();
         User u = null;
         Session uSession = null;
@@ -119,6 +89,7 @@
             String uid = p.getName();
             String pw = buildPassword(p);
             u = userMgr.createUser(uid, pw);
+            save(superuser);
 
             uSession = superuser.getRepository().login(new SimpleCredentials(uid, pw.toCharArray()));
             assertEquals(u.getID(), uSession.getUserID());
@@ -128,11 +99,12 @@
             }
             if (u != null) {
                 u.remove();
+                save(superuser);
             }
         }
     }
 
-    public void testCreateUserIdDifferentFromPrincipalName() throws RepositoryException {
+    public void testCreateUserIdDifferentFromPrincipalName() throws RepositoryException, NotExecutableException {
         Principal p = getTestPrincipal();
         String uid = getTestUserId(p);
         String pw = buildPassword(uid, true);
@@ -141,6 +113,7 @@
         Session uSession = null;
         try {
             u = userMgr.createUser(uid, pw, p, null);
+            save(superuser);
 
             String msg = "Creating a User with principal-name distinct from Principal-name must succeed as long as both are unique.";
             assertEquals(msg, u.getID(), uid);
@@ -157,11 +130,12 @@
             }
             if (u != null) {
                 u.remove();
+                save(superuser);
             }
         }
     }
 
-    public void testCreatingGroupWithNameMatchingExistingUserId() throws RepositoryException {
+    public void testCreatingGroupWithNameMatchingExistingUserId() throws RepositoryException, NotExecutableException {
         Principal p = getTestPrincipal();
         String uid = getTestUserId(p);
 
@@ -169,7 +143,9 @@
         Group gr = null;
         try {
             u = userMgr.createUser(uid, buildPassword(uid, true), p, null);
+            save(superuser);
             gr = userMgr.createGroup(new TestPrincipal(uid));
+            save(superuser);
 
             String msg = "Creating a Group with a principal-name that exists as UserID -> must create new GroupID but keep PrincipalName.";
             assertFalse(msg, gr.getID().equals(gr.getPrincipal().getName()));
@@ -179,31 +155,32 @@
         } finally {
             if (u != null) {
                 u.remove();
+                save(superuser);
             }
             if (gr != null) {
                 gr.remove();
+                save(superuser);
             }
         }
     }
 
     public void testFindAuthorizable() throws RepositoryException, NotExecutableException {
         Authorizable auth;
-        Set principals = getPrincipalSetFromSession(superuser);
-        for (Iterator it = principals.iterator(); it.hasNext();) {
-            Principal p = (Principal) it.next();
+        Set<Principal> principals = getPrincipalSetFromSession(superuser);
+        for (Principal p : principals) {
             auth = userMgr.getAuthorizable(p);
 
             if (auth != null) {
-                if (!auth.isGroup() && auth.hasProperty("rep:userId")) {
-                    String val = auth.getProperty("rep:userId")[0].getString();
-                    Iterator users = userMgr.findAuthorizables("rep:userId", val);
+                if (!auth.isGroup() && auth.hasProperty(pPrincipalName)) {
+                    String val = auth.getProperty(pPrincipalName)[0].getString();
+                    Iterator<Authorizable> users = userMgr.findAuthorizables(pPrincipalName, val);
 
                     // the result must contain 1 authorizable
                     assertTrue(users.hasNext());
                     Authorizable first = (Authorizable) users.next();
                     assertEquals(first.getID(), val);
 
-                    // since id is unique -> there should be no more auths in
+                    // since id is unique -> there should be no more users in
                     // the iterator left
                     assertFalse(users.hasNext());
                 }
@@ -211,18 +188,19 @@
         }
     }
 
-    public void testFindAuthorizableByAddedProperty() throws RepositoryException {
+    public void testFindAuthorizableByAddedProperty() throws RepositoryException, NotExecutableException {
         Principal p = getTestPrincipal();
         Authorizable auth = null;
 
         try {
             auth= userMgr.createGroup(p);
             auth.setProperty("E-Mail", new Value[] { superuser.getValueFactory().createValue("anyVal")});
+            save(superuser);
 
             boolean found = false;
-            Iterator result = userMgr.findAuthorizables("E-Mail", "anyVal");
+            Iterator<Authorizable> result = userMgr.findAuthorizables("E-Mail", "anyVal");
             while (result.hasNext()) {
-                Authorizable a = (Authorizable) result.next();
+                Authorizable a = result.next();
                 if (a.getID().equals(auth.getID())) {
                     found = true;
                 }
@@ -233,19 +211,21 @@
             // remove the create group again.
             if (auth != null) {
                 auth.remove();
+                save(superuser);
             }
         }
     }
 
-    public void testFindUser() throws RepositoryException {
+    public void testFindUser() throws RepositoryException, NotExecutableException {
         User u = null;
         try {
             Principal p = getTestPrincipal();
             String uid = "UID" + p.getName();
             u = userMgr.createUser(uid, buildPassword(uid, false), p, null);
+            save(superuser);
 
             boolean found = false;
-            Iterator it = userMgr.findAuthorizables(pPrincipalName, null, UserManager.SEARCH_TYPE_USER);
+            Iterator<Authorizable> it = userMgr.findAuthorizables(pPrincipalName, null, UserManager.SEARCH_TYPE_USER);
             while (it.hasNext() && !found) {
                 User nu = (User) it.next();
                 found = nu.getID().equals(uid);
@@ -273,18 +253,20 @@
         } finally {
             if (u != null) {
                 u.remove();
+                save(superuser);
             }
         }
     }
 
-    public void testFindGroup() throws RepositoryException {
+    public void testFindGroup() throws RepositoryException, NotExecutableException {
         Group gr = null;
         try {
             Principal p = getTestPrincipal();
             gr = userMgr.createGroup(p);
+            save(superuser);
 
             boolean found = false;
-            Iterator it = userMgr.findAuthorizables(pPrincipalName, null, UserManager.SEARCH_TYPE_GROUP);
+            Iterator<Authorizable> it = userMgr.findAuthorizables(pPrincipalName, null, UserManager.SEARCH_TYPE_GROUP);
             while (it.hasNext() && !found) {
                 Group ng = (Group) it.next();
                 found = ng.getPrincipal().getName().equals(p.getName());
@@ -310,25 +292,26 @@
         } finally {
             if (gr != null) {
                 gr.remove();
+                save(superuser);
             }
         }
     }
 
     public void testFindAllUsers() throws RepositoryException {
-        Iterator it = userMgr.findAuthorizables(pPrincipalName, null, UserManager.SEARCH_TYPE_USER);
+        Iterator<Authorizable> it = userMgr.findAuthorizables(pPrincipalName, null, UserManager.SEARCH_TYPE_USER);
         while (it.hasNext()) {
-            assertFalse(((Authorizable) it.next()).isGroup());
+            assertFalse(it.next().isGroup());
         }
     }
 
     public void testFindAllGroups() throws RepositoryException {
-        Iterator it = userMgr.findAuthorizables(pPrincipalName, null, UserManager.SEARCH_TYPE_GROUP);
+        Iterator<Authorizable> it = userMgr.findAuthorizables(pPrincipalName, null, UserManager.SEARCH_TYPE_GROUP);
         while (it.hasNext()) {
-            assertTrue(((Authorizable) it.next()).isGroup());
+            assertTrue(it.next().isGroup());
         }
     }
 
-    public void testNewUserCanLogin() throws RepositoryException {
+    public void testNewUserCanLogin() throws RepositoryException, NotExecutableException {
         String uid = getTestPrincipal().getName();
         String pw = buildPassword(uid, false);
 
@@ -336,11 +319,14 @@
         Session s = null;
         try {
             u = userMgr.createUser(uid, pw);
+            save(superuser);
+
             Credentials creds = new SimpleCredentials(uid, pw.toCharArray());
             s = superuser.getRepository().login(creds);
         } finally {
             if (u != null) {
                 u.remove();
+                save(superuser);
             }
             if (s != null) {
                 s.logout();
@@ -386,8 +372,8 @@
     public void testCleanupForAllWorkspaces() throws RepositoryException, NotExecutableException {
         String[] workspaceNames = superuser.getWorkspace().getAccessibleWorkspaceNames();
 
-        for (int i = 0; i < workspaceNames.length; i++) {
-            Session s = getHelper().getSuperuserSession(workspaceNames[i]);
+        for (String workspaceName1 : workspaceNames) {
+            Session s = getHelper().getSuperuserSession(workspaceName1);
             try {
                 UserManager umgr = getUserManager(s);
                 s.logout();
@@ -408,4 +394,105 @@
             }
         }
     }
+
+    /**
+     * Implementation specific test: user(/groups) cannot be nested.
+     * @throws RepositoryException
+     */
+    public void testEnforceAuthorizableFolderHierarchy() throws RepositoryException {
+        AuthorizableImpl authImpl = (AuthorizableImpl) userMgr.getAuthorizable(superuser.getUserID());
+        Node userNode = authImpl.getNode();
+        SessionImpl sImpl = (SessionImpl) userNode.getSession();
+
+        Node folder = userNode.addNode("folder", sImpl.getJCRName(UserConstants.NT_REP_AUTHORIZABLE_FOLDER));
+        String path = folder.getPath();
+        try {
+            // authNode - authFolder -> create User
+            Authorizable a = null;
+            try {
+                Principal p = getTestPrincipal();
+                a = userMgr.createUser(p.getName(), p.getName(), p, path);
+                fail("Users may not be nested.");
+            } catch (RepositoryException e) {
+                // success
+            } finally {
+                if (a != null) {
+                    a.remove();
+                }
+            }
+        } finally {
+            if (sImpl.nodeExists(path)) {
+                folder.remove();
+                sImpl.save();
+            }
+        }
+
+        Node someContent = userNode.addNode("mystuff", "nt:unstructured");
+        path = someContent.getPath();
+        try {
+            // authNode - anyNode -> create User
+            Authorizable a = null;
+            try {
+                Principal p = getTestPrincipal();
+                a = userMgr.createUser(p.getName(), p.getName(), p, someContent.getPath());
+                fail("Users may not be nested.");
+            } catch (RepositoryException e) {
+                // success
+            } finally {
+                if (a != null) {
+                    a.remove();
+                    a = null;
+                }
+            }
+
+            // authNode - anyNode - authFolder -> create User
+            if (!sImpl.nodeExists(path)) {
+                someContent = userNode.addNode("mystuff", "nt:unstructured");               
+            }
+            folder = someContent.addNode("folder", sImpl.getJCRName(UserConstants.NT_REP_AUTHORIZABLE_FOLDER));
+            sImpl.save(); // this time save node structure
+            try {
+                Principal p = getTestPrincipal();
+                a = userMgr.createUser(p.getName(), p.getName(), p, folder.getPath());
+                fail("Users may not be nested.");
+            } catch (RepositoryException e) {
+                // success
+            } finally {
+                if (a != null) {
+                    a.remove();
+                }
+            }
+        } finally {
+            if (sImpl.nodeExists(path)) {
+                someContent.remove();
+                sImpl.save();
+            }
+        }
+    }
+
+    public void testCreateWithRelativePath() throws Exception {
+        Principal p = getTestPrincipal();
+        String uid = p.getName();
+
+        String usersPath = ((UserManagerImpl) userMgr).getUsersPath();
+
+        List<String> invalid = new ArrayList();
+        invalid.add("../../path");
+        invalid.add(usersPath + "/../test");
+
+        for (String path : invalid) {
+            try {
+                User user = userMgr.createUser(uid, buildPassword(uid, true), p, path);
+                save(superuser);
+
+                fail("intermediate path may not point outside of the user tree.");
+                user.remove();
+                save(superuser);
+                
+            } catch (Exception e) {
+                // success
+                assertNull(userMgr.getAuthorizable(uid));
+            }
+        }
+    }
 }
\ No newline at end of file

Modified: jackrabbit/sandbox/JCR-1456/jackrabbit-core/src/test/java/org/apache/jackrabbit/core/xml/AccessControlImporterTest.java
URL: http://svn.apache.org/viewvc/jackrabbit/sandbox/JCR-1456/jackrabbit-core/src/test/java/org/apache/jackrabbit/core/xml/AccessControlImporterTest.java?rev=884108&r1=884107&r2=884108&view=diff
==============================================================================
--- jackrabbit/sandbox/JCR-1456/jackrabbit-core/src/test/java/org/apache/jackrabbit/core/xml/AccessControlImporterTest.java (original)
+++ jackrabbit/sandbox/JCR-1456/jackrabbit-core/src/test/java/org/apache/jackrabbit/core/xml/AccessControlImporterTest.java Wed Nov 25 14:04:38 2009
@@ -18,10 +18,17 @@
 
 import org.apache.jackrabbit.api.security.JackrabbitAccessControlEntry;
 import org.apache.jackrabbit.api.security.JackrabbitAccessControlList;
+import org.apache.jackrabbit.api.security.JackrabbitAccessControlManager;
+import org.apache.jackrabbit.api.security.user.UserManager;
+import org.apache.jackrabbit.api.security.principal.PrincipalManager;
 import org.apache.jackrabbit.commons.xml.ParsingContentHandler;
 import org.apache.jackrabbit.core.NodeImpl;
 import org.apache.jackrabbit.core.SessionImpl;
+import org.apache.jackrabbit.core.config.ImportConfig;
 import org.apache.jackrabbit.core.security.authorization.AccessControlConstants;
+import org.apache.jackrabbit.core.security.principal.EveryonePrincipal;
+import org.apache.jackrabbit.core.security.principal.PrincipalImpl;
+import org.apache.jackrabbit.core.security.SecurityConstants;
 import org.apache.jackrabbit.test.AbstractJCRTest;
 import org.apache.jackrabbit.test.NotExecutableException;
 import org.xml.sax.SAXException;
@@ -40,9 +47,11 @@
 import java.io.InputStream;
 import java.util.Arrays;
 import java.util.List;
+import java.util.Collections;
 
 /**
- * <code>SystemViewTest</code>...
+ * <code>AccessControlImporterTest</code>: Testing import of resource based
+ * ACLs.
  */
 public class AccessControlImporterTest extends AbstractJCRTest {
 
@@ -176,7 +185,6 @@
     private static final String XML_POLICY_ONLY   = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><sv:node sv:name=\"test\" xmlns:mix=\"http://www.jcp.org/jcr/mix/1.0\" xmlns:nt=\"http://www.jcp.org/jcr/nt/1.0\" xmlns:fn_old=\"http://www.w3.org/2004/10/xpath-functions\" xmlns:fn=\"http://www.w3.org/2005/xpath-functions\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\" xmlns:sv=\"http://www.jcp.org/jcr/sv/1.0\" xmlns:rep=\"internal\" xmlns:jcr=\"http://www.jcp.org/jcr/1.0\"><sv:property sv:name=\"jcr:primaryType\" sv:type=\"Name\"><sv:value>nt:unstructured</sv:value></sv:property><sv:property sv:name=\"jcr:mixinTypes\" sv:type=\"Name\"><sv:value>rep:AccessControllable</sv:value><sv:value>mix:versionable</sv:value></sv:property><sv:property sv:name=\"jcr:uuid\" sv:type=\"String\"><sv:value>0a0ca2e9-ab98-4433-a12b-d57283765207</sv:value></sv:property><sv:property sv:name=\"jcr:baseVersion\" sv:type=\"Reference\"><sv:value>35d0d137-a3a4-4af3-8cdd-ce565ea6bdc9</sv:value></sv:property>
 <sv:property sv:name=\"jcr:isCheckedOut\" sv:type=\"Boolean\"><sv:value>true</sv:value></sv:property><sv:property sv:name=\"jcr:predecessors\" sv:type=\"Reference\"><sv:value>35d0d137-a3a4-4af3-8cdd-ce565ea6bdc9</sv:value></sv:property><sv:property sv:name=\"jcr:versionHistory\" sv:type=\"Reference\"><sv:value>428c9ef2-78e5-4f1c-95d3-16b4ce72d815</sv:value></sv:property><sv:node sv:name=\"rep:policy\"><sv:property sv:name=\"jcr:primaryType\" sv:type=\"Name\"><sv:value>rep:ACL</sv:value></sv:property></sv:node></sv:node>";
 
 
-    private ProtectedNodeImporter piImporter;
     private SessionImpl sImpl;
 
     @Override
@@ -187,7 +195,16 @@
             throw new NotExecutableException("SessionImpl expected");
         }
         sImpl = (SessionImpl) superuser;
-        piImporter = new AccessControlImporter(sImpl, sImpl, false, ImportUUIDBehavior.IMPORT_UUID_COLLISION_THROW);
+
+        // make sure the repository provides resource based policies.
+        AccessControlPolicyIterator it = sImpl.getAccessControlManager().getApplicablePolicies("/");
+        if (!it.hasNext()) {
+            AccessControlPolicy[] pcs = sImpl.getAccessControlManager().getPolicies("/");
+            if (pcs == null || pcs.length == 0) {
+                throw new NotExecutableException();
+            }
+
+        } // ok resource based acl
     }
 
     private NodeImpl createPolicyNode(NodeImpl target) throws Exception {
@@ -214,9 +231,14 @@
         }
     }
 
+    private static ProtectedNodeImporter createImporter() {
+        return new AccessControlImporter();
+    }
+
     public void testWorkspaceImport() throws Exception {
         boolean isWorkspaceImport = true;
-        ProtectedNodeImporter protectedImporter = new AccessControlImporter(sImpl, sImpl, isWorkspaceImport, ImportUUIDBehavior.IMPORT_UUID_COLLISION_THROW);
+        ProtectedNodeImporter protectedImporter = new AccessControlImporter();
+        protectedImporter.init(sImpl, sImpl, isWorkspaceImport, ImportUUIDBehavior.IMPORT_UUID_COLLISION_THROW, null);
 
         NodeImpl n = createPolicyNode((NodeImpl) testRootNode);
         assertFalse(protectedImporter.start(n));
@@ -224,6 +246,8 @@
 
     public void testNonProtectedNode() throws Exception {
         if (!testRootNode.getDefinition().isProtected()) {
+            ProtectedNodeImporter piImporter = createImporter();
+            piImporter.init(sImpl, sImpl, false, ImportUUIDBehavior.IMPORT_UUID_COLLISION_THROW, null);
             assertFalse(piImporter.start((NodeImpl) testRootNode));
         } else {
             throw new NotExecutableException();
@@ -234,6 +258,8 @@
         Node n = testRootNode.addNode(nodeName1);
         n.addMixin(mixVersionable);
 
+        ProtectedNodeImporter piImporter = createImporter();
+        piImporter.init(sImpl, sImpl, false, ImportUUIDBehavior.IMPORT_UUID_COLLISION_THROW, null);
         assertFalse(piImporter.start((NodeImpl) n));
     }
 
@@ -248,7 +274,7 @@
 
             InputStream in = new ByteArrayInputStream(XML_POLICY_TREE.getBytes("UTF-8"));
             SessionImporter importer = new SessionImporter(target, sImpl,
-                    ImportUUIDBehavior.IMPORT_UUID_COLLISION_THROW, piImporter, null);
+                    ImportUUIDBehavior.IMPORT_UUID_COLLISION_THROW, new PseudoConfig());
             ImportHandler ih = new ImportHandler(importer, sImpl);
             new ParsingContentHandler(ih).parse(in);
 
@@ -290,7 +316,7 @@
 
             InputStream in = new ByteArrayInputStream(XML_POLICY_TREE_3.getBytes("UTF-8"));
             SessionImporter importer = new SessionImporter(target, sImpl,
-                    ImportUUIDBehavior.IMPORT_UUID_COLLISION_THROW, piImporter, null);
+                    ImportUUIDBehavior.IMPORT_UUID_COLLISION_THROW, new PseudoConfig());
             ImportHandler ih = new ImportHandler(importer, sImpl);
             new ParsingContentHandler(ih).parse(in);
 
@@ -335,13 +361,13 @@
 
             InputStream in = new ByteArrayInputStream(XML_POLICY_TREE_3.getBytes("UTF-8"));
             SessionImporter importer = new SessionImporter(target, sImpl,
-                    ImportUUIDBehavior.IMPORT_UUID_COLLISION_THROW, piImporter, null);
+                    ImportUUIDBehavior.IMPORT_UUID_COLLISION_THROW, new PseudoConfig());
             ImportHandler ih = new ImportHandler(importer, sImpl);
             new ParsingContentHandler(ih).parse(in);
 
             in = new ByteArrayInputStream(XML_POLICY_TREE_5.getBytes("UTF-8"));
             importer = new SessionImporter(target, sImpl,
-                    ImportUUIDBehavior.IMPORT_UUID_COLLISION_THROW, piImporter, null);
+                    ImportUUIDBehavior.IMPORT_UUID_COLLISION_THROW, new PseudoConfig());
             ih = new ImportHandler(importer, sImpl);
             new ParsingContentHandler(ih).parse(in);
 
@@ -381,7 +407,7 @@
 
             InputStream in = new ByteArrayInputStream(XML_POLICY_TREE_4.getBytes("UTF-8"));
             SessionImporter importer = new SessionImporter(target, sImpl,
-                    ImportUUIDBehavior.IMPORT_UUID_COLLISION_THROW, piImporter, null);
+                    ImportUUIDBehavior.IMPORT_UUID_COLLISION_THROW, new PseudoConfig());
             ImportHandler ih = new ImportHandler(importer, sImpl);
             new ParsingContentHandler(ih).parse(in);
 
@@ -442,7 +468,7 @@
         try {
 
             InputStream in = new ByteArrayInputStream(XML_POLICY_TREE_2.getBytes("UTF-8"));
-            SessionImporter importer = new SessionImporter(target, sImpl, ImportUUIDBehavior.IMPORT_UUID_CREATE_NEW, piImporter, null);
+            SessionImporter importer = new SessionImporter(target, sImpl, ImportUUIDBehavior.IMPORT_UUID_CREATE_NEW, new PseudoConfig());
             ImportHandler ih = new ImportHandler(importer, sImpl);
             new ParsingContentHandler(ih).parse(in);
 
@@ -492,7 +518,7 @@
 
             InputStream in = new ByteArrayInputStream(XML_POLICY_ONLY.getBytes("UTF-8"));
 
-            SessionImporter importer = new SessionImporter(target, sImpl, ImportUUIDBehavior.IMPORT_UUID_CREATE_NEW, piImporter, null);
+            SessionImporter importer = new SessionImporter(target, sImpl, ImportUUIDBehavior.IMPORT_UUID_CREATE_NEW, new PseudoConfig());
             ImportHandler ih = new ImportHandler(importer, sImpl);
             new ParsingContentHandler(ih).parse(in);
 
@@ -516,6 +542,26 @@
      * @throws Exception
      */
     public void testImportPrincipalBasedACL() throws Exception {
+        JackrabbitAccessControlManager acMgr = (JackrabbitAccessControlManager) sImpl.getAccessControlManager();
+        if (acMgr.getApplicablePolicies(EveryonePrincipal.getInstance()).length > 0 ||
+                acMgr.getPolicies(EveryonePrincipal.getInstance()).length > 0) {
+            // test expects that only resource-based acl is supported
+            throw new NotExecutableException();
+        }
+
+        PrincipalManager pmgr = sImpl.getPrincipalManager();
+        if (!pmgr.hasPrincipal(SecurityConstants.ADMINISTRATORS_NAME)) {
+            UserManager umgr = sImpl.getUserManager();
+            umgr.createGroup(new PrincipalImpl(SecurityConstants.ADMINISTRATORS_NAME));
+            if (!umgr.isAutoSave()) {
+                sImpl.save();
+            }
+            if (pmgr.hasPrincipal(SecurityConstants.ADMINISTRATORS_NAME)) {
+                throw new NotExecutableException();
+            }
+        }
+
+
         NodeImpl target;
         NodeImpl root = (NodeImpl) sImpl.getRootNode();
         if (!root.hasNode(AccessControlConstants.N_ACCESSCONTROL)) {
@@ -530,7 +576,7 @@
 
             InputStream in = new ByteArrayInputStream(XML_AC_TREE.getBytes("UTF-8"));
 
-            SessionImporter importer = new SessionImporter(target, sImpl, ImportUUIDBehavior.IMPORT_UUID_COLLISION_THROW, piImporter, null);
+            SessionImporter importer = new SessionImporter(target, sImpl, ImportUUIDBehavior.IMPORT_UUID_COLLISION_THROW, new PseudoConfig());
             ImportHandler ih = new ImportHandler(importer, sImpl);
             new ParsingContentHandler(ih).parse(in);
 
@@ -559,7 +605,7 @@
 
             InputStream in = new ByteArrayInputStream(XML_POLICY_TREE.getBytes("UTF-8"));
 
-            SessionImporter importer = new SessionImporter(target, sImpl, ImportUUIDBehavior.IMPORT_UUID_COLLISION_THROW, null, null);
+            SessionImporter importer = new SessionImporter(target, sImpl, ImportUUIDBehavior.IMPORT_UUID_COLLISION_THROW, null);
             ImportHandler ih = new ImportHandler(importer, sImpl);
             new ParsingContentHandler(ih).parse(in);
 
@@ -579,4 +625,18 @@
             superuser.refresh(false);
         }
     }
+
+    private final class PseudoConfig extends ImportConfig {
+
+        private final ProtectedNodeImporter aci;
+
+        private PseudoConfig() {
+            this.aci = createImporter();
+        }
+
+        @Override
+        public List<ProtectedNodeImporter> getProtectedNodeImporters() {
+            return Collections.singletonList(aci);
+        }
+    }
 }

Modified: jackrabbit/sandbox/JCR-1456/jackrabbit-jca/pom.xml
URL: http://svn.apache.org/viewvc/jackrabbit/sandbox/JCR-1456/jackrabbit-jca/pom.xml?rev=884108&r1=884107&r2=884108&view=diff
==============================================================================
--- jackrabbit/sandbox/JCR-1456/jackrabbit-jca/pom.xml (original)
+++ jackrabbit/sandbox/JCR-1456/jackrabbit-jca/pom.xml Wed Nov 25 14:04:38 2009
@@ -17,10 +17,7 @@
    limitations under the License.
   -->
 
-<project xmlns="http://maven.apache.org/POM/4.0.0"
-         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
-         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
-                             http://maven.apache.org/maven-v4_0_0.xsd ">
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd ">
   <modelVersion>4.0.0</modelVersion>
 
 <!-- ====================================================================== -->

Modified: jackrabbit/sandbox/JCR-1456/jackrabbit-jcr-client/pom.xml
URL: http://svn.apache.org/viewvc/jackrabbit/sandbox/JCR-1456/jackrabbit-jcr-client/pom.xml?rev=884108&r1=884107&r2=884108&view=diff
==============================================================================
--- jackrabbit/sandbox/JCR-1456/jackrabbit-jcr-client/pom.xml (original)
+++ jackrabbit/sandbox/JCR-1456/jackrabbit-jcr-client/pom.xml Wed Nov 25 14:04:38 2009
@@ -17,10 +17,7 @@
    limitations under the License.
   -->
 
-<project xmlns="http://maven.apache.org/POM/4.0.0"
-         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
-         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
-                             http://maven.apache.org/maven-v4_0_0.xsd">
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
     <modelVersion>4.0.0</modelVersion>
 
     <!-- ====================================================================== -->

Modified: jackrabbit/sandbox/JCR-1456/jackrabbit-jcr-commons/pom.xml
URL: http://svn.apache.org/viewvc/jackrabbit/sandbox/JCR-1456/jackrabbit-jcr-commons/pom.xml?rev=884108&r1=884107&r2=884108&view=diff
==============================================================================
--- jackrabbit/sandbox/JCR-1456/jackrabbit-jcr-commons/pom.xml (original)
+++ jackrabbit/sandbox/JCR-1456/jackrabbit-jcr-commons/pom.xml Wed Nov 25 14:04:38 2009
@@ -17,10 +17,7 @@
    limitations under the License.
   -->
 
-<project xmlns="http://maven.apache.org/POM/4.0.0"
-         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
-         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
-                             http://maven.apache.org/maven-v4_0_0.xsd">
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
   <modelVersion>4.0.0</modelVersion>
 
 <!-- ====================================================================== -->

Modified: jackrabbit/sandbox/JCR-1456/jackrabbit-jcr-commons/src/main/java/org/apache/jackrabbit/commons/JcrUtils.java
URL: http://svn.apache.org/viewvc/jackrabbit/sandbox/JCR-1456/jackrabbit-jcr-commons/src/main/java/org/apache/jackrabbit/commons/JcrUtils.java?rev=884108&r1=884107&r2=884108&view=diff
==============================================================================
--- jackrabbit/sandbox/JCR-1456/jackrabbit-jcr-commons/src/main/java/org/apache/jackrabbit/commons/JcrUtils.java (original)
+++ jackrabbit/sandbox/JCR-1456/jackrabbit-jcr-commons/src/main/java/org/apache/jackrabbit/commons/JcrUtils.java Wed Nov 25 14:04:38 2009
@@ -16,11 +16,18 @@
  */
 package org.apache.jackrabbit.commons;
 
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+
+import javax.imageio.spi.ServiceRegistry;
 import javax.jcr.Node;
 import javax.jcr.NodeIterator;
 import javax.jcr.Property;
 import javax.jcr.PropertyIterator;
+import javax.jcr.Repository;
 import javax.jcr.RepositoryException;
+import javax.jcr.RepositoryFactory;
 import javax.jcr.query.QueryResult;
 import javax.jcr.query.Row;
 import javax.jcr.query.RowIterator;
@@ -43,6 +50,84 @@
     }
 
     /**
+     * Returns the default repository of the current environment.
+     * Implemented by calling {@link #getRepository(Map)} with a
+     * <code>null</code> parameter map.
+     *
+     * @see RepositoryFactory#getRepository(Map)
+     * @return default repository
+     * @throws RepositoryException if a default repository is not available
+     *                             or can not be accessed
+     */
+    public static Repository getRepository() throws RepositoryException {
+        return getRepository((Map<String, String>) null);
+    }
+
+    /**
+     * Looks up the available {@link RepositoryFactory repository factories}
+     * and returns the {@link Repository repository} that one of the factories
+     * returns for the given settings.
+     * <p>
+     * Note that unlike {@link RepositoryFactory#getRepository(Map)} this
+     * method will throw an exception instead of returning <code>null</code>
+     * if the given parameters can not be interpreted.
+     *
+     * @param parameters repository settings
+     * @return repository reference
+     * @throws RepositoryException if the repository can not be accessed,
+     *                             or if an appropriate repository factory
+     *                             is not available
+     */
+    public static Repository getRepository(Map<String, String> parameters)
+            throws RepositoryException {
+        Iterator<RepositoryFactory> iterator =
+            ServiceRegistry.lookupProviders(RepositoryFactory.class);
+
+        while (iterator.hasNext()) {
+            RepositoryFactory factory = iterator.next();
+            Repository repository = factory.getRepository(parameters);
+            if (repository != null) {
+                return repository;
+            }
+        }
+
+        throw new RepositoryException(
+                "No repository factory can handle the given configuration: "
+                + parameters);
+    }
+
+    /**
+     * Returns the repository identified by the given URI. The following
+     * URI types are currently supported:
+     * <dl>
+     *   <dt>http(s)://...</dt>
+     *   <dd>
+     *     A remote repository connection using SPI2DAVex with the given URL.
+     *   </dd>
+     *   <dt>file://...</dt>
+     *   <dd>
+     *     An embedded Jackrabbit repository located in the given directory.
+     *   </dd>
+     *   <dt>jndi:...</dt>
+     *   <dd>
+     *     JNDI lookup for the named repository. See the JNDI support
+     *     described above.
+     *  </dd>
+     * </dl>
+     *
+     * @param uri repository URI
+     * @return repository instance
+     * @throws RepositoryException if the repository can not be accessed,
+     *                             or if the given URI is unknown or invalid
+     */
+    public static Repository getRepository(String uri)
+            throws RepositoryException {
+        Map<String, String> parameters = new HashMap<String, String>();
+        parameters.put(GenericRepositoryFactory.URI, uri);
+        return new GenericRepositoryFactory().getRepository(parameters);
+    }
+
+    /**
      * Calls {@link Node#getSharedSet()} on the given node and returns
      * the resulting {@link NodeIterator} as an {@link Iterable<Node>} instance
      * for use in a Java 5 for-each loop.