Login or create workspace
[lgpl/argeo-commons.git] / server / runtime / org.argeo.server.jcr / src / main / java / org / argeo / jcr / JcrUtils.java
index e2f5b54279ad424ce3aec09248f695d2f1c7ab1c..b32e4404e61b260b74d4c6c6c78a8612d6b8b034 100644 (file)
@@ -36,6 +36,7 @@ import java.util.TreeMap;
 
 import javax.jcr.Binary;
 import javax.jcr.NamespaceRegistry;
+import javax.jcr.NoSuchWorkspaceException;
 import javax.jcr.Node;
 import javax.jcr.NodeIterator;
 import javax.jcr.Property;
@@ -966,6 +967,29 @@ public class JcrUtils implements ArgeoJcrConstants {
                }
        }
 
+       /**
+        * Login to a workspace with implicit credentials, creates the workspace
+        * with these credentials if it does not already exist.
+        */
+       public static Session loginOrCreateWorkspace(Repository repository,
+                       String workspaceName) throws RepositoryException {
+               Session workspaceSession = null;
+               Session defaultSession = null;
+               try {
+                       try {
+                               workspaceSession = repository.login(workspaceName);
+                       } catch (NoSuchWorkspaceException e) {
+                               // try to create workspace
+                               defaultSession = repository.login();
+                               defaultSession.getWorkspace().createWorkspace(workspaceName);
+                               workspaceSession = repository.login(workspaceName);
+                       }
+                       return workspaceSession;
+               } finally {
+                       logoutQuietly(defaultSession);
+               }
+       }
+
        /** Logs out the session, not throwing any exception, even if it is null. */
        public static void logoutQuietly(Session session) {
                try {