You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@lenya.apache.org by mi...@apache.org on 2005/03/24 23:14:11 UTC

svn commit: r158954 - in lenya/sandbox/jcrsitetree/src/java/org/apache/lenya/cms/publication: AbstractPublication.java ClearRepository.java ImportSiteTree.java JCRSiteTree.java

Author: michi
Date: Thu Mar 24 14:14:11 2005
New Revision: 158954

URL: http://svn.apache.org/viewcvs?view=rev&rev=158954
Log:
accessing the repository directly

Modified:
    lenya/sandbox/jcrsitetree/src/java/org/apache/lenya/cms/publication/AbstractPublication.java
    lenya/sandbox/jcrsitetree/src/java/org/apache/lenya/cms/publication/ClearRepository.java
    lenya/sandbox/jcrsitetree/src/java/org/apache/lenya/cms/publication/ImportSiteTree.java
    lenya/sandbox/jcrsitetree/src/java/org/apache/lenya/cms/publication/JCRSiteTree.java

Modified: lenya/sandbox/jcrsitetree/src/java/org/apache/lenya/cms/publication/AbstractPublication.java
URL: http://svn.apache.org/viewcvs/lenya/sandbox/jcrsitetree/src/java/org/apache/lenya/cms/publication/AbstractPublication.java?view=diff&r1=158953&r2=158954
==============================================================================
--- lenya/sandbox/jcrsitetree/src/java/org/apache/lenya/cms/publication/AbstractPublication.java (original)
+++ lenya/sandbox/jcrsitetree/src/java/org/apache/lenya/cms/publication/AbstractPublication.java Thu Mar 24 14:14:11 2005
@@ -29,13 +29,13 @@
 import org.apache.avalon.framework.configuration.Configuration;
 import org.apache.avalon.framework.configuration.DefaultConfigurationBuilder;
 import org.apache.lenya.cms.publishing.PublishingEnvironment;
-import org.apache.log4j.Category;
+import org.apache.log4j.Logger;
 
 /**
  * A publication.
  */
 public abstract class AbstractPublication implements Publication {
-    private static Category log = Category.getInstance(AbstractPublication.class);
+    private static Logger log = Logger.getLogger(AbstractPublication.class);
 
     private static final String[] areas = { AUTHORING_AREA, STAGING_AREA, LIVE_AREA, ADMIN_AREA,
             ARCHIVE_AREA, TRASH_AREA, INFO_AREA_PREFIX + AUTHORING_AREA,
@@ -54,6 +54,7 @@
     private HashMap siteTrees = new HashMap();
     private String[] rewriteAttributeXPaths = { };
     private boolean hasSitetree = true;
+    private Configuration config = null;
 
     private static final String ELEMENT_PROXY = "proxy";
     private static final String ATTRIBUTE_AREA = "area";
@@ -86,10 +87,9 @@
         File configFile = new File(getDirectory(), CONFIGURATION_FILE);
         DefaultConfigurationBuilder builder = new DefaultConfigurationBuilder();
 
-        Configuration config;
-
         String pathMapperClassName = null;
         String documentBuilderClassName = null;
+        String siteTreeClassName = null;
 
         try {
             config = builder.buildFromFile(configFile);
@@ -320,16 +320,21 @@
      * @throws SiteTreeException if an error occurs
      */
     public SiteTree getSiteTree(String area) throws SiteTreeException {
-
+        assert config != null;
+        
         SiteTree sitetree = null;
-
         if (hasSitetree) {
             if (siteTrees.containsKey(area)) {
-                log.error("Load sitetree from MEMORY (" + area + ")");
                 sitetree = (SiteTree) siteTrees.get(area);
             } else {
-                log.error("Load sitetree from FILESYSTEM (" + area + ")");
-                sitetree = new JCRSiteTree(getDirectory(), area);
+                try {
+                    sitetree = SiteTreeFactory.getSiteTree(config, getDirectory(), area);
+                } catch (SiteTreeFactoryException e) {
+                    throw new SiteTreeException("Unable to create sitetree.", e);
+                }
+                if (sitetree == null) {
+                    throw new SiteTreeException("Unable to get sitetree.");
+                }
                 siteTrees.put(area, sitetree);
             }
         }

Modified: lenya/sandbox/jcrsitetree/src/java/org/apache/lenya/cms/publication/ClearRepository.java
URL: http://svn.apache.org/viewcvs/lenya/sandbox/jcrsitetree/src/java/org/apache/lenya/cms/publication/ClearRepository.java?view=diff&r1=158953&r2=158954
==============================================================================
--- lenya/sandbox/jcrsitetree/src/java/org/apache/lenya/cms/publication/ClearRepository.java (original)
+++ lenya/sandbox/jcrsitetree/src/java/org/apache/lenya/cms/publication/ClearRepository.java Thu Mar 24 14:14:11 2005
@@ -18,7 +18,6 @@
 package org.apache.lenya.cms.publication;
 
 import java.io.File;
-import java.io.FileInputStream;
 import java.util.Hashtable;
 
 import javax.jcr.*;
@@ -42,9 +41,6 @@
         new ClearRepository().clear(repoHomeDir);
     }
 
-    /**
-     *
-     */
     public void clear(String repoHomeDir) {
         System.out.println("Clear repository " + repoHomeDir);
 
@@ -53,8 +49,8 @@
 
             // Clear authoring workspace.
             Session authSession = repo.login(new SimpleCredentials("anonymous", "".toCharArray()), Publication.AUTHORING_AREA);
-            authSession.setNamespacePrefix(JCRSiteTree.NAMESPACE_PREFIX, JCRSiteTree.NAMESPACE_URI);
-            NodeIterator iter = authSession.getRootNode().getNodes(JCRSiteTree.NAMESPACE_PREFIX + ":*");
+            authSession.setNamespacePrefix(JCRSiteTree.NS_PREFIX_SYSTEM, JCRSiteTree.NS_URI_SYSTEM);
+            NodeIterator iter = authSession.getRootNode().getNodes(JCRSiteTree.NS_PREFIX_SYSTEM + ":*");
             while (iter.hasNext()) {
                 iter.nextNode().remove();
             }
@@ -63,8 +59,8 @@
 
             // Clear live workspace.
             Session liveSession = repo.login(new SimpleCredentials("anonymous", "".toCharArray()), Publication.LIVE_AREA);
-            liveSession.setNamespacePrefix(JCRSiteTree.NAMESPACE_PREFIX, JCRSiteTree.NAMESPACE_URI);
-            iter = liveSession.getRootNode().getNodes(JCRSiteTree.NAMESPACE_PREFIX + ":*");
+            liveSession.setNamespacePrefix(JCRSiteTree.NS_PREFIX_SYSTEM, JCRSiteTree.NS_URI_SYSTEM);
+            iter = liveSession.getRootNode().getNodes(JCRSiteTree.NS_PREFIX_SYSTEM + ":*");
             while (iter.hasNext()) {
                 iter.nextNode().remove();
             }

Modified: lenya/sandbox/jcrsitetree/src/java/org/apache/lenya/cms/publication/ImportSiteTree.java
URL: http://svn.apache.org/viewcvs/lenya/sandbox/jcrsitetree/src/java/org/apache/lenya/cms/publication/ImportSiteTree.java?view=diff&r1=158953&r2=158954
==============================================================================
--- lenya/sandbox/jcrsitetree/src/java/org/apache/lenya/cms/publication/ImportSiteTree.java (original)
+++ lenya/sandbox/jcrsitetree/src/java/org/apache/lenya/cms/publication/ImportSiteTree.java Thu Mar 24 14:14:11 2005
@@ -29,10 +29,9 @@
 import org.apache.jackrabbit.core.jndi.RegistryHelper;
 
 /**
- * Import authoring and live sitetrees from filesystem into workspaces of repository
+ * Import lenya sitetree into jackrabbit repository.
  */
 public class ImportSiteTree {
-
     /**
      *
      */
@@ -47,6 +46,13 @@
      *
      */
     public void importSitetree(String repoHomeDir, String defaultPubDir) {
+    	String nsPrefixAuthSys = null;
+        String nsPrefixAuthUser = null;
+    	String nsPrefixLiveSys = null;
+        String nsPrefixLiveUser = null;
+    	String nsPrefixDefaultSys = null;
+        String nsPrefixDefaultUser = null;
+    	
         System.out.println("Import Authoring and Live Sitetree from " + defaultPubDir + " into " + repoHomeDir);
 
         try {
@@ -56,52 +62,74 @@
             Session authSession = repo.login(new SimpleCredentials("anonymous", "".toCharArray()), Publication.AUTHORING_AREA);
             NamespaceRegistry registry = authSession.getWorkspace().getNamespaceRegistry();
             try {
-                registry.registerNamespace(JCRSiteTree.NAMESPACE_PREFIX, JCRSiteTree.NAMESPACE_URI);
+                nsPrefixAuthSys = registry.getPrefix(JCRSiteTree.NS_URI_SYSTEM);
+                nsPrefixAuthUser = registry.getPrefix(JCRSiteTree.NS_URI_USER);
             } catch (NamespaceException nse) {
-                // The namespace may be already registered.
+                registry.registerNamespace(JCRSiteTree.NS_PREFIX_USER, JCRSiteTree.NS_URI_USER);
+                registry.registerNamespace(JCRSiteTree.NS_PREFIX_SYSTEM, JCRSiteTree.NS_URI_SYSTEM);
             }
 
-            authSession.setNamespacePrefix(JCRSiteTree.NAMESPACE_PREFIX, JCRSiteTree.NAMESPACE_URI);
+            authSession.importXML("/", new FileInputStream(defaultPubDir + "/content/authoring/sitetree.xml.import"));
 
-            authSession.importXML("/", new FileInputStream(defaultPubDir + "/content/authoring/" + JCRSiteTree.SITE_TREE_FILENAME));
-            NodeIterator iter = authSession.getRootNode().getNodes(JCRSiteTree.NAMESPACE_PREFIX + ":site");
+            authSession.setNamespacePrefix(nsPrefixAuthSys, JCRSiteTree.NS_URI_SYSTEM);
+            authSession.setNamespacePrefix(nsPrefixAuthUser, JCRSiteTree.NS_URI_USER);
+            
+            NodeIterator iter = authSession.getRootNode().getNodes(nsPrefixAuthSys + ":*");
             while (iter.hasNext()) {
-                addVersionable(iter.nextNode());
+                Node node = iter.nextNode();
+                removeXMLTextNodes(node);
+                addVersionable(node);
             }
             authSession.save();
 
             // Clone authoring sitetree to live workspace
+            System.out.println("Cloning authoring area to live area.");
             Session liveSession = repo.login(new SimpleCredentials("anonymous", "".toCharArray()), Publication.LIVE_AREA);
             registry = liveSession.getWorkspace().getNamespaceRegistry();
             try {
-                registry.registerNamespace(JCRSiteTree.NAMESPACE_PREFIX, JCRSiteTree.NAMESPACE_URI);
+                nsPrefixLiveSys = registry.getPrefix(JCRSiteTree.NS_URI_SYSTEM);
+                nsPrefixLiveUser = registry.getPrefix(JCRSiteTree.NS_URI_USER);
             } catch (NamespaceException nse) {
-                // The namespace may be already registered.
+                registry.registerNamespace(JCRSiteTree.NS_PREFIX_USER, JCRSiteTree.NS_URI_USER);
+                registry.registerNamespace(JCRSiteTree.NS_PREFIX_SYSTEM, JCRSiteTree.NS_URI_SYSTEM);
             }
-            liveSession.getWorkspace().clone(Publication.AUTHORING_AREA, "/" + JCRSiteTree.NAMESPACE_PREFIX +":site",
-                                             "/" + JCRSiteTree.NAMESPACE_PREFIX + ":site", true);
+            
+            liveSession.setNamespacePrefix(nsPrefixLiveSys, JCRSiteTree.NS_URI_SYSTEM);
+            liveSession.setNamespacePrefix(nsPrefixLiveUser, JCRSiteTree.NS_URI_USER);
+          
+            liveSession.getWorkspace().clone(Publication.AUTHORING_AREA,
+                                             "/" + nsPrefixAuthSys + ":site",
+                                             "/" + nsPrefixLiveSys + ":site", true);
 
             // Remove nodes that are not in live sitetree.
+            System.out.println("Removing nodes not in live area");
             Session defaultSession = repo.login(new SimpleCredentials("anonymous", "".toCharArray()), null);
             registry = defaultSession.getWorkspace().getNamespaceRegistry();
             try {
-                registry.registerNamespace(JCRSiteTree.NAMESPACE_PREFIX, JCRSiteTree.NAMESPACE_URI);
+                nsPrefixDefaultSys = registry.getPrefix(JCRSiteTree.NS_URI_SYSTEM);
+                nsPrefixDefaultUser = registry.getPrefix(JCRSiteTree.NS_URI_USER);
             } catch (NamespaceException nse) {
-                // The namespace may be already registered.
+                registry.registerNamespace(JCRSiteTree.NS_PREFIX_USER, JCRSiteTree.NS_URI_USER);
+                registry.registerNamespace(JCRSiteTree.NS_PREFIX_SYSTEM, JCRSiteTree.NS_URI_SYSTEM);
             }
-            defaultSession.setNamespacePrefix(JCRSiteTree.NAMESPACE_PREFIX, JCRSiteTree.NAMESPACE_URI);
-            defaultSession.importXML("/", new FileInputStream(defaultPubDir + "/content/live/" + JCRSiteTree.SITE_TREE_FILENAME));
 
-            iter = authSession.getRootNode().getNodes(JCRSiteTree.NAMESPACE_PREFIX + ":site | " + JCRSiteTree.NAMESPACE_PREFIX + " :node");
+            defaultSession.importXML("/", new FileInputStream(defaultPubDir + "/content/live/sitetree.xml.import"));
+            defaultSession.setNamespacePrefix(nsPrefixDefaultSys, JCRSiteTree.NS_URI_SYSTEM);
+            defaultSession.setNamespacePrefix(nsPrefixDefaultUser, JCRSiteTree.NS_URI_USER);
+
+            iter = authSession.getRootNode().getNodes(nsPrefixAuthSys + ":*");
             while (iter.hasNext()) {
                 try {
-                    cleanupLiveArea(defaultSession, liveSession, iter.nextNode());
+                    cleanupLiveArea(defaultSession, liveSession, iter.nextNode(),
+                            nsPrefixAuthSys + ":* | " + nsPrefixAuthUser + ":*");
                 } catch (Exception e) {
                     e.printStackTrace();
                 }
             }
-            // Discard all pending changes.
+            // Discard all pending changes in temporary session.
             defaultSession.refresh(false);
+            // Save changes in live area.
+            liveSession.save();
 
             // Close sessions.
             liveSession.logout();
@@ -128,32 +156,76 @@
     }
 
     /**
-     *
+     * Add jcr:versionable property to nodes with prefix.
+     * 
+     * @param n Node to work on.
+     * @param prefix Prefix of node which should be versionable.
+     * @throws RepositoryException
      */
-    private void addVersionable(Node n) {
-        NodeIterator iter = null;
+    private void addVersionable(Node n) throws RepositoryException {
         try {
             n.addMixin("mix:versionable");
-            iter = n.getNodes(JCRSiteTree.NAMESPACE_PREFIX + ":site | " + JCRSiteTree.NAMESPACE_PREFIX + ":node");
         } catch (Exception e) {
             e.printStackTrace();
         }
+        NodeIterator iter = null;
+        iter = n.getNodes();
         while (iter.hasNext()) {
             addVersionable(iter.nextNode());
         }
     }
 
-    private void cleanupLiveArea(Session tmpSession, Session dst, Node node)
+    /**
+     * Remove empty jcr:xmltext nodes (artifact from importXML()).
+     * 
+     * @param node Node object to check for removal.
+     * @throws RepositoryException
+     */
+    private void removeXMLTextNodes(Node node) throws RepositoryException {
+        if (node.getName().startsWith("jcr:xmltext")) {
+            try {
+                node.remove();
+            } catch (Exception e) {
+                e.printStackTrace();
+            }
+        } else {
+            NodeIterator iter = null;
+            try {
+                iter = node.getNodes();
+            } catch (Exception e) {
+                e.printStackTrace();
+            }
+            while (iter.hasNext()) {
+                removeXMLTextNodes(iter.nextNode());
+            }
+        }
+    }
+
+    /**
+     * Remove all nodes from dst if they do not exist in tmpSession.
+     * 
+     * @param tmpSession Session object of temporary nodes
+     * @param dst Session object where non-existing node should be deleted
+     * @param node Node object to check if it exists in tmpSession and dst
+     * @param searchPrefix Search prefix for child nodes.
+     * @throws RepositoryException
+     */
+    private void cleanupLiveArea(Session tmpSession, Session dst, Node node, String searchPrefix)
         throws RepositoryException
     {
         try {
             tmpSession.getItem(node.getPath());
         } catch (PathNotFoundException pnfe) {
-            dst.getItem(node.getPath()).remove();
+        	try {
+        	    dst.getNodeByUUID(node.getUUID()).remove();
+                System.out.println("Removed: " + node.getPath());
+            } catch (ItemNotFoundException infe) {
+                // The node may have been removed already.
+            }
         }
-        NodeIterator iter = node.getNodes(JCRSiteTree.NAMESPACE_PREFIX + ":site | " + JCRSiteTree.NAMESPACE_PREFIX +" :node");
+        NodeIterator iter = node.getNodes();
         while (iter.hasNext()) {
-            cleanupLiveArea(tmpSession, dst, iter.nextNode());
+            cleanupLiveArea(tmpSession, dst, iter.nextNode(), searchPrefix);
         }
     }
 }

Modified: lenya/sandbox/jcrsitetree/src/java/org/apache/lenya/cms/publication/JCRSiteTree.java
URL: http://svn.apache.org/viewcvs/lenya/sandbox/jcrsitetree/src/java/org/apache/lenya/cms/publication/JCRSiteTree.java?view=diff&r1=158953&r2=158954
==============================================================================
--- lenya/sandbox/jcrsitetree/src/java/org/apache/lenya/cms/publication/JCRSiteTree.java (original)
+++ lenya/sandbox/jcrsitetree/src/java/org/apache/lenya/cms/publication/JCRSiteTree.java Thu Mar 24 14:14:11 2005
@@ -20,52 +20,55 @@
 package org.apache.lenya.cms.publication;
 
 import java.io.File;
-import java.io.IOException;
-import java.util.ArrayList;
 import java.util.Hashtable;
-import java.util.List;
 import java.util.StringTokenizer;
 
-import javax.xml.parsers.ParserConfigurationException;
-import javax.xml.transform.TransformerException;
-
-import javax.jcr.*;
+import javax.jcr.AccessDeniedException;
+import javax.jcr.InvalidItemStateException;
+import javax.jcr.NamespaceException;
+import javax.jcr.NamespaceRegistry;
+import javax.jcr.Node;
+import javax.jcr.NodeIterator;
+import javax.jcr.PathNotFoundException;
+import javax.jcr.Repository;
+import javax.jcr.RepositoryException;
+import javax.jcr.Session;
+import javax.jcr.SimpleCredentials;
+import javax.jcr.lock.LockException;
+import javax.jcr.nodetype.ConstraintViolationException;
+import javax.jcr.version.VersionException;
 
 import javax.naming.Context;
 import javax.naming.InitialContext;
 
 import org.apache.jackrabbit.core.jndi.RegistryHelper;
 
-import org.apache.lenya.xml.DocumentHelper;
-import org.apache.lenya.xml.NamespaceHelper;
 import org.apache.log4j.Category;
-import org.apache.xpath.XPathAPI;
-import org.apache.xml.serialize.OutputFormat;
-import org.apache.xml.serialize.XMLSerializer;
-
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-import org.w3c.dom.NamedNodeMap;
-import org.w3c.dom.Node;
-import org.w3c.dom.NodeList;
-import org.xml.sax.SAXException;
 
-import org.xml.sax.ContentHandler;
 
 /**
- * Sitetree implementation based on JCR
+ * Sitetree implementation based on JSR-170.
  */
 public class JCRSiteTree implements SiteTree {
     private static Category log = Category.getInstance(JCRSiteTree.class);
 
-    public static final String NAMESPACE_URI = "http://apache.org/cocoon/lenya/sitetree/1.0";
+    public static final String NS_URI_USER = "http://apache.org/cocoon/lenya/sitetree/1.0";
+    public static final String NS_PREFIX_USER = "lust"; // lenya user site tree
+    public static final String NS_URI_SYSTEM = "http://apache.org/cocoon/lenya/sitetree/system/1.0";
+    public static final String NS_PREFIX_SYSTEM = "lst"; // lenya system site tree
+    
     public static final String SITE_TREE_FILENAME = "sitetree.xml";
-    public static final String NAMESPACE_PREFIX = "lenya-sitetree";
-
-    private Document document = null;
-    private File treefile = null;
-    // the area is only retained to provide some more info when raising an exception.
-    private String area = "";
+    
+    public static final String SITETREE_NAME = "site";
+    public static final String DOCUMENT_NAME = "document";
+    
+    public static final String REPOSITORY_HOME = "repos" + File.separator + "repo-sitetree";
+
+    private String prefixSys = null;
+    private String prefixUser = null;
+    
+    private Repository repository = null;
+    private Session session = null;
 
     /**
      * Create a JCRSiteTree
@@ -76,186 +79,33 @@
      * @throws SiteTreeException if an error occurs
      */
     protected JCRSiteTree(File pubDir, String area) throws SiteTreeException {
-/*
-        this(
-            new File(
-                pubDir,
-                Publication.CONTENT_PATH
-                    + File.separator
-                    + area
-                    + File.separator
-                    + SITE_TREE_FILENAME));
-*/
-        log.error("Load sitetree: " + pubDir + " " + area);
-        this.area = area;
-
         try {
-            Repository repo = getRepository(pubDir.getAbsolutePath() + File.separator + "repos" + File.separator + "repo-sitetree");
-            log.error("Repo: " + repo);
-            Session session = repo.login(new SimpleCredentials("anonymous", "".toCharArray()), Publication.AUTHORING_AREA);
-
-            NamespaceRegistry registry = session.getWorkspace().getNamespaceRegistry();
-            String prefix = registry.getPrefix(NAMESPACE_URI);
-
-            org.apache.cocoon.xml.dom.DOMBuilder domBuilder = new org.apache.cocoon.xml.dom.DOMBuilder();
-            // NOTE: XPath cannot be used
-            //session.exportDocView("/" + area + "/*[local-name() = 'site' and namespace-uri() = '"+NAMESPACE_URI+"']", domBuilder, true, false);
-            session.exportDocView("/" + prefix + ":site", domBuilder, true, false);
-            document = domBuilder.getDocument();
-	    log.error("Root Element Name: " + document.getDocumentElement().getTagName());
-
-// For Debugging
-/*
-            java.io.FileOutputStream out = new java.io.FileOutputStream("/home/michi/repo.jcr");
-            session.exportDocView("/" + area + "/" + prefix + ":site", out, true, false);
-            out.close();
-*/
-
-            session.save();
-       } catch (Exception e) {
-            log.error(e);
-            throw new SiteTreeException();
-       }
-    }
-
-    /**
-     * Create a JCRSiteTree from a filename.
-     *
-     * @param treefilename file name of the tree
-     *
-     * @throws SiteTreeException if an error occurs
-     *  
-     * @deprecated use the JCRSiteTree(File pubDir, String area) constructor instead.
-     */
-    public JCRSiteTree(String treefilename) throws SiteTreeException {
-        this(new File(treefilename));
-    }
-
-    /**
-     * Create a JCRSiteTree from a file.
-     *
-     * @param treefile the file containing the tree
-     * 
-     * @throws SiteTreeException if an error occurs
-     * 
-     * @deprecated this constructor will be private in the future
-     */
-    public JCRSiteTree(File treefile) throws SiteTreeException {
-        this.treefile = treefile;
-
-        try {
-            if (!treefile.isFile()) {
-                //the treefile doesn't exist, so create it
-
-                document = createDocument();
-            } else {
-                // Read tree
-                document = DocumentHelper.readDocument(treefile);
+            repository = getRepository(pubDir.getAbsolutePath() + File.separator + REPOSITORY_HOME);
+            session = repository.login(new SimpleCredentials("anonymous", "".toCharArray()), area);
+            prefixUser = getNamespacePrefix(NS_URI_USER, NS_PREFIX_USER);
+            prefixSys = getNamespacePrefix(NS_URI_SYSTEM, NS_PREFIX_SYSTEM);
+            if (prefixUser == null || prefixSys == null) {
+                throw new SiteTreeException("Unable to get namespace prefixes"); 
             }
-        } catch (ParserConfigurationException e) {
-            throw new SiteTreeException(e);
-        } catch (SAXException e) {
-            throw new SiteTreeException(e);
-        } catch (IOException e) {
-            throw new SiteTreeException(e);
-        }
-
-    }
-
-    private long lastModified = 0;
-
-    /**
-     * Checks if the tree file has been modified externally and reloads the site tree.
-     * @throws SiteTreeException when something went wrong.
-     */
-    protected void checkModified() {
-        if (area.equals(Publication.LIVE_AREA)
-            && treefile.isFile()
-            && treefile.lastModified() > lastModified) {
-                
-            if (log.isDebugEnabled()) {
-                log.debug("Sitetree [" + treefile + "] has changed: reloading.");
-            }
-                
-            try {
-                document = DocumentHelper.readDocument(treefile);
-            } catch (Exception e) {
-                throw new IllegalStateException(e.getMessage());
-            }
-            lastModified = treefile.lastModified();
-        }
-    }
-
-    /**
-     * Create a new JCRSiteTree xml document.
-     *
-     * @return the new site document
-     * 
-     * @throws ParserConfigurationException if an error occurs
-     */
-    public Document createDocument() throws ParserConfigurationException {
-        document = DocumentHelper.createDocument(NAMESPACE_URI, "site", null);
-
-        Element root = document.getDocumentElement();
-        root.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
-        root.setAttribute(
-            "xsi:schemaLocation",
-            NAMESPACE_URI + "  ../../../../resources/entities/sitetree.xsd");
-
-        return document;
-    }
-
-    /**
-     * Find a node in a subtree. The search is started at the
-     * given node. The list of ids contains the document-id
-     * split by "/".
-     *
-     * @param node where to start the search
-     * @param ids list of node ids
-     * 
-     * @return the node that matches the path given in the list of ids
-     */
-    protected Node findNode(Node node, List ids) {
-
-        checkModified();
-
-        if (ids.size() < 1) {
-            return node;
-        } else {
-            NodeList nodes = node.getChildNodes();
-
-            for (int i = 0; i < nodes.getLength(); i++) {
-                NamedNodeMap attributes = nodes.item(i).getAttributes();
-
-                if (attributes != null) {
-                    Node idAttribute = attributes.getNamedItem("id");
-
-                    if (idAttribute != null
-                        && !"".equals(idAttribute.getNodeValue())
-                        && idAttribute.getNodeValue().equals(ids.get(0))) {
-                        return findNode(nodes.item(i), ids.subList(1, ids.size()));
-                    }
-                }
+            // Add sitetree root node if it does not exist already
+            if (!session.getRootNode().hasNode(prefixSys + ":" + SITETREE_NAME)) {
+                Node siteNode = session.getRootNode().addNode(prefixSys + ":" + SITETREE_NAME);
+                siteNode.addMixin("mix:versionable");
+                session.save();
             }
+        } catch (RepositoryException e) {
+            throw new SiteTreeException("Repository exception", e);
+        } catch (Exception e) {
+            throw new SiteTreeException(e);
         }
-
-        // node wasn't found
-        return null;
     }
 
     /** (non-Javadoc)
      * @see org.apache.lenya.cms.publication.SiteTree#addNode(org.apache.lenya.cms.publication.SiteTreeNode, java.lang.String)
      */
     public synchronized void addNode(SiteTreeNode node, String refDocumentId) throws SiteTreeException {
-        this.addNode(
-            node.getAbsoluteParentId(),
-            node.getId(),
-            node.getLabels(),
-            node.visibleInNav(),
-            node.getHref(),
-            node.getSuffix(),
-            node.hasLink(),
-            refDocumentId);
+        this.addNode(node.getAbsoluteParentId(), node.getId(), node.getLabels(), node.visibleInNav(),
+            node.getHref(), node.getSuffix(), node.hasLink(), refDocumentId);
     }
 
     /** (non-Javadoc)
@@ -282,15 +132,10 @@
     /** (non-Javadoc)
      * @see org.apache.lenya.cms.publication.SiteTree#addNode(java.lang.String, org.apache.lenya.cms.publication.Label[], java.lang.String, java.lang.String, boolean, java.lang.String)
      */
-    public synchronized void addNode(
-        String documentid,
-        Label[] labels,
-        boolean visibleInNav,
-        String href,
-        String suffix,
-        boolean link,
-        String refDocumentId)
-        throws SiteTreeException {
+    public synchronized void addNode(String documentid, Label[] labels, boolean visibleInNav,
+        String href, String suffix, boolean link, String refDocumentId)
+    throws SiteTreeException
+    {
         String parentid = "";
         StringTokenizer st = new StringTokenizer(documentid, "/");
         int length = st.countTokens();
@@ -306,111 +151,78 @@
     /** (non-Javadoc)
      * @see org.apache.lenya.cms.publication.SiteTree#addNode(java.lang.String, org.apache.lenya.cms.publication.Label[], java.lang.String, java.lang.String, boolean)
      */
-    public synchronized void addNode(
-        String documentid,
-        Label[] labels,
-        boolean visibleInNav,
-        String href,
-        String suffix,
-        boolean link)
-        throws SiteTreeException {
+    public synchronized void addNode(String documentid, Label[] labels, boolean visibleInNav,
+        String href, String suffix, boolean link)
+    throws SiteTreeException
+    {
         this.addNode(documentid, labels, visibleInNav, href, suffix, link, null);
     }
+    
     /** (non-Javadoc)
      * @see org.apache.lenya.cms.publication.SiteTree#addNode(java.lang.String, java.lang.String, org.apache.lenya.cms.publication.Label[], java.lang.String, java.lang.String, boolean)
      */
-    public synchronized void addNode(
-        String parentid,
-        String id,
-        Label[] labels,
-        boolean visibleInNav,
-        String href,
-        String suffix,
-        boolean link)
-        throws SiteTreeException {
+    public synchronized void addNode(String parentid, String id, Label[] labels, boolean visibleInNav,
+        String href, String suffix, boolean link)
+    throws SiteTreeException
+    {
         this.addNode(parentid, id, labels, visibleInNav, href, suffix, link, null);
     }
 
     /** (non-Javadoc)
      * @see org.apache.lenya.cms.publication.SiteTree#addNode(java.lang.String, java.lang.String, org.apache.lenya.cms.publication.Label[], java.lang.String, java.lang.String, boolean)
      */
-    public synchronized void addNode(
-        String parentid,
-        String id,
-        Label[] labels,
-        boolean visibleInNav,
-        String href,
-        String suffix,
-        boolean link,
-        String refDocumentId)
-        throws SiteTreeException {
-
-        Node parentNode = getNodeInternal(parentid);
-
-        if (parentNode == null) {
-            throw new SiteTreeException(
-                "Parentid: " + parentid + " in " + area + " tree not found");
-        }
-
-        log.debug("PARENT ELEMENT: " + parentNode);
-
-        // Check if child already exists
-        Node childNode = getNodeInternal(parentid + "/" + id);
-
-        if (childNode != null) {
-            log.info("This node: " + parentid + "/" + id + " has already been inserted");
-
-            return;
-        }
-
-        // Create node
-        NamespaceHelper helper = new NamespaceHelper(NAMESPACE_URI, "", document);
-        Element child = helper.createElement(SiteTreeNodeImpl.NODE_NAME);
-        child.setAttribute(SiteTreeNodeImpl.ID_ATTRIBUTE_NAME, id);
-        
-        if (visibleInNav) {
-            child.setAttribute(SiteTreeNodeImpl.VISIBLEINNAV_ATTRIBUTE_NAME, "true");
-        } else {
-            child.setAttribute(SiteTreeNodeImpl.VISIBLEINNAV_ATTRIBUTE_NAME, "false");
-        }
-
-        if ((href != null) && (href.length() > 0)) {
-            child.setAttribute(SiteTreeNodeImpl.HREF_ATTRIBUTE_NAME, href);
-        }
-
-        if ((suffix != null) && (suffix.length() > 0)) {
-            child.setAttribute(SiteTreeNodeImpl.SUFFIX_ATTRIBUTE_NAME, suffix);
-        }
-
-        if (link) {
-            child.setAttribute(SiteTreeNodeImpl.LINK_ATTRIBUTE_NAME, "true");
-        }
-
-        for (int i = 0; i < labels.length; i++) {
-            String labelName = labels[i].getLabel();
-            Element label = helper.createElement(SiteTreeNodeImpl.LABEL_NAME, labelName);
-            String labelLanguage = labels[i].getLanguage();
-
-            if ((labelLanguage != null) && (labelLanguage.length() > 0)) {
-                label.setAttribute(SiteTreeNodeImpl.LANGUAGE_ATTRIBUTE_NAME, labelLanguage);
+    public synchronized void addNode(String parentid, String id, Label[] labels, boolean visibleInNav,
+        String href, String suffix, boolean link, String refDocumentId)
+    throws SiteTreeException
+    {
+        try {
+            Node parentNode = null;
+            try {
+                parentNode = session.getRootNode().getNode(mapDocumentIdToJCRAbsolute(parentid).substring(1));
+            } catch (PathNotFoundException e) {
+                throw new SiteTreeException("Parent node with id " + parentid + " in workspace " +
+                        session.getWorkspace().getName() + " not found");
             }
-
-            child.appendChild(label);
-        }
-
-        // Add Node 
-        if (refDocumentId != null && !refDocumentId.equals("")) {
-            Node nextSibling = getNodeInternal(refDocumentId);
-            if (nextSibling != null) {
-                parentNode.insertBefore(child, nextSibling);
-            } else {
-                parentNode.appendChild(child);
+            // Check if child exists already.
+            if (parentNode.hasNode(prefixUser + ":" + id))
+            {
+                log.info("Node " + id + " with parent id " + parentid + " exists already.");
+                return;
             }
-        } else {
-            parentNode.appendChild(child);
+            // Try to clone node from authoring area.
+            if (clone(parentNode, id))
+                return;
+            // Create node.
+            Node newNode = parentNode.addNode(prefixUser + ":" + id);
+            newNode.addMixin("mix:versionable");
+            // Add properties.
+            newNode.setProperty(JCRSiteTreeNodeImpl.VISIBLEINNAV_ATTRIBUTE_NAME, visibleInNav);
+            if (href != null && !"".equals(href)) {
+                newNode.setProperty(JCRSiteTreeNodeImpl.HREF_ATTRIBUTE_NAME, href);
+            }
+            if (suffix != null && !"".equals(suffix)) {
+                newNode.setProperty(JCRSiteTreeNodeImpl.SUFFIX_ATTRIBUTE_NAME, suffix);
+            }
+            
+            newNode.setProperty(JCRSiteTreeNodeImpl.LINK_ATTRIBUTE_NAME, link);
+            
+            for (int i=0; i<labels.length; i++) {
+                String labelName = labels[i].getLabel();
+                String labelLanguage = labels[i].getLanguage();
+                Node labelNode = newNode.addNode(getSystemPrefix() + ":" + DOCUMENT_NAME);
+                labelNode.addMixin("mix:versionable");
+                labelNode.setProperty(JCRSiteTreeNodeImpl.LABEL_NAME, labelName);
+                labelNode.setProperty(JCRSiteTreeNodeImpl.LANGUAGE_ATTRIBUTE_NAME, labelLanguage);
+            }
+            // Order node among its siblings.
+            if (refDocumentId != null && !"".equals(refDocumentId)) {
+                Node siblingAfter = session.getRootNode().getNode(mapDocumentIdToJCRAbsolute(refDocumentId).substring(1));
+                parentNode.orderBefore(newNode.getName(), siblingAfter.getName());
+            }
+        } catch (RepositoryException e) {
+            log.error("JCRSiteTree.addNode() failed: repository exception.", e);
+            throw new SiteTreeException(e);
         }
-        log.debug("Tree has been modified: " + document.getDocumentElement());
-
     }
     /**
      *  (non-Javadoc)
@@ -439,49 +251,21 @@
      */
     public synchronized SiteTreeNode removeNode(String documentId) {
         assert documentId != null;
-
-        Node node = removeNodeInternal(documentId);
-
-        if (node == null) {
-            return null;
+        
+        Node node = null;
+        try {
+            node = session.getRootNode().getNode(mapDocumentIdToJCRAbsolute(documentId).substring(1));
+            node.remove();
+        } catch (PathNotFoundException e) {
+            // No node found. 
+        } catch (RepositoryException e) {
+            log.error("JCRSiteTree.removeNode() failed for document id " + documentId, e);
         }
-
-        return new SiteTreeNodeImpl(node);
-    }
-
-    /**
-     * removes the node corresponding to the given document-id
-     * and returns it
-     * 
-     * @param documentId the document-id of the Node to be removed
-     * 
-     * @return the <code>Node</code> that was removed
-     */
-    private synchronized Node removeNodeInternal(String documentId) {
-        Node node = this.getNodeInternal(documentId);
-        Node parentNode = node.getParentNode();
-        Node newNode = parentNode.removeChild(node);
-
-        return newNode;
-    }
-
-    /**
-     * Find a node for a given document-id
-     *
-     * @param documentId the document-id of the Node that we're trying to get
-     * 
-     * @return the Node if there is a Node for the given document-id, null otherwise
-     */
-    private Node getNodeInternal(String documentId) {
-        StringTokenizer st = new StringTokenizer(documentId, "/");
-        ArrayList ids = new ArrayList();
-
-        while (st.hasMoreTokens()) {
-            ids.add(st.nextToken());
+        if (node != null) {
+            return new JCRSiteTreeNodeImpl(node,  this);
+        } else {
+            return null;
         }
-
-        Node node = findNode(document.getDocumentElement(), ids);
-        return node;
     }
 
     /**
@@ -489,50 +273,66 @@
      */
     public SiteTreeNode getNode(String documentId) {
         assert documentId != null;
-
-        SiteTreeNode treeNode = null;
-
-        Node node = getNodeInternal(documentId);
+        Node node = null;
+        try {
+            node = session.getRootNode().getNode(mapDocumentIdToJCRAbsolute(documentId).substring(1));
+        } catch (PathNotFoundException e) {
+            // No node found.
+        } catch (RepositoryException e) {
+            log.error("JCRSiteTree.getNode() failed for document id " + documentId, e);
+        }
         if (node != null) {
-            treeNode = new SiteTreeNodeImpl(node);
+            return new JCRSiteTreeNodeImpl(node, this);
+        } else {
+            return null;
         }
+    }
 
-        return treeNode;
+    /**
+     * @see org.apache.lenya.cms.publication.SiteTree#getTopNodes()
+     */
+    public SiteTreeNode[] getTopNodes() {
+        return null;
     }
 
     /**
      * Move up the node amongst its siblings.
      * 
      * @param documentid The document id for the node.
-     * @throws SiteTreeException if the moving failed.
+     * @throws SiteTreeException if the move operation failed.
      */
     public synchronized void moveUp(String documentid) throws SiteTreeException {
-        Node node = this.getNodeInternal(documentid);
-        if (node == null) {
-            throw new SiteTreeException("Node to move: " + documentid + " not found");
-        }
-        Node parentNode = node.getParentNode();
-        if (parentNode == null) {
-            throw new SiteTreeException(
-                "Parentid of node with documentid: " + documentid + " not found");
-        }
-
-        Node previousNode;
         try {
-            previousNode =
-                XPathAPI.selectSingleNode(
-                    node,
-                    "(preceding-sibling::*[local-name() = 'node'])[last()]");
-        } catch (TransformerException e) {
-            throw new SiteTreeException(e);
-        }
-
-        if (previousNode == null) {
-            log.warn("Couldn't found a preceding sibling");
-            return;
+            Node node = null;
+            try {
+                node = session.getRootNode().getNode(mapDocumentIdToJCRAbsolute(documentid).substring(1));
+            } catch (PathNotFoundException e) {
+                throw new SiteTreeException("Node to move with id " + documentid + " not found.", e);
+            }
+        
+            Node parentNode = node.getParent();
+            NodeIterator iter = parentNode.getNodes();
+            Node siblingBefore = null;
+            while (iter.hasNext()) {
+                Node curNode = iter.nextNode();
+                if (curNode != node) {
+                    siblingBefore = curNode;
+                } else {
+                    break;
+                }
+            }
+            if (siblingBefore != null) {
+                parentNode.orderBefore(node.getName(), siblingBefore.getName());
+            } else {
+                log.warn("JCRSiteTree.moveUp() failed for document with id " + documentid +
+                        ": No preceding sibling found.");
+                return;
+            }
+        }  catch (RepositoryException e) {
+            log.error("JCRSiteTree.moveUp() for document with id " + documentid +
+                    " failed: repository exception", e);
+            throw new SiteTreeException("Repository exception", e);
         }
-        Node insertNode = parentNode.removeChild(node);
-        parentNode.insertBefore(insertNode, previousNode);
     }
 
     /**
@@ -542,44 +342,50 @@
      * @throws SiteTreeException if the moving failed.
      */
     public synchronized void moveDown(String documentid) throws SiteTreeException {
-        Node node = this.getNodeInternal(documentid);
-        if (node == null) {
-            throw new SiteTreeException("Node to move: " + documentid + " not found");
-        }
-        Node parentNode = node.getParentNode();
-        if (parentNode == null) {
-            throw new SiteTreeException(
-                "Parentid of node with documentid: " + documentid + " not found");
-        }
-        Node nextNode;
         try {
-            nextNode =
-                XPathAPI.selectSingleNode(
-                    node,
-                    "following-sibling::*[local-name() = 'node'][position()=2]");
-        } catch (TransformerException e) {
-            throw new SiteTreeException(e);
-        }
-
-        Node insertNode = parentNode.removeChild(node);
-
-        if (nextNode == null) {
-            log.warn("Couldn't found the second following sibling");
-            parentNode.appendChild(insertNode);
-        } else {
-            parentNode.insertBefore(insertNode, nextNode);
+            Node node = null;
+            try {
+                node = session.getRootNode().getNode(mapDocumentIdToJCRAbsolute(documentid).substring(1));
+            } catch (PathNotFoundException e) {
+                throw new SiteTreeException("Node to move with id " + documentid + " not found.", e);
+            }
+        
+            Node parentNode = node.getParent();
+            NodeIterator iter = parentNode.getNodes();
+            Node siblingAfter = null;
+            while (iter.hasNext()) {
+                // Get second sibling following the node to move.
+                if (iter.nextNode() == node) {
+                    if (iter.hasNext()) {
+                        iter.nextNode();
+                        if (iter.hasNext()) {
+                            siblingAfter = iter.nextNode();
+                            break;
+                        }
+                    }
+                }
+            }
+            if (siblingAfter != null) {
+                parentNode.orderBefore(node.getName(), siblingAfter.getName());
+            } else {
+                log.warn("JCRSiteTree.moveDown() failed for document with id " + documentid +
+                        ": No following sibling found.");
+                return;
+            }
+        }  catch (RepositoryException e) {
+            log.error("JCRSiteTree.moveDown() for document with id " + documentid +
+                    " failed: repository exception", e);
+            throw new SiteTreeException("Repository exception", e);
         }
     }
 
     /** (non-Javadoc)
      * @see org.apache.lenya.cms.publication.SiteTree#importSubtree(org.apache.lenya.cms.publication.SiteTreeNode, org.apache.lenya.cms.publication.SiteTreeNode, java.lang.String)
      */
-    public synchronized void importSubtree(
-        SiteTreeNode newParent,
-        SiteTreeNode subtreeRoot,
-        String newid,
-        String refDocumentId)
-        throws SiteTreeException {
+    public synchronized void importSubtree(SiteTreeNode newParent, SiteTreeNode subtreeRoot,
+        String newid, String refDocumentId)
+    throws SiteTreeException
+    {
         assert subtreeRoot != null;
         assert newParent != null;
         String parentId = newParent.getAbsoluteId();
@@ -613,15 +419,27 @@
      * @see org.apache.lenya.cms.publication.SiteTree#save()
      */
     public synchronized void save() throws SiteTreeException {
-        try {
-            DocumentHelper.writeDocument(document, treefile);
-        } catch (TransformerException e) {
-            throw new SiteTreeException(
-                "The document [" + document.getLocalName() + "] could not be transformed");
-        } catch (IOException e) {
-            throw new SiteTreeException(
-                "The saving of document [" + document.getLocalName() + "] failed");
-        }
+            try {
+                session.save();
+            } catch (AccessDeniedException e) {
+                log.error("JCRSiteTree.save() failed: access denied exception.", e);
+                throw new SiteTreeException("Access denied when trying to save the site tree.", e);
+            } catch (ConstraintViolationException e) {
+                log.error("JCRSiteTree.save() failed: constraint violation.", e);
+                throw new SiteTreeException("Constraint violation occured when saving the site tree.", e);
+            } catch (InvalidItemStateException e) {
+                log.error("JCRSiteTree.save() failed: invalid item state.", e);
+                throw new SiteTreeException("Invalid item state when saving the site tree.", e);
+            } catch (VersionException e) {
+                log.error("JCRSiteTree.save() failed: version exception.", e);
+                throw new SiteTreeException("Version issue when saving the site tree.", e);
+            } catch (LockException e) {
+                log.error("JCRSiteTree.save() failed: locking exception.", e);
+                throw new SiteTreeException("Locking issue when saving the site tree.", e);
+            } catch (RepositoryException e) {
+                log.error("JCRSiteTree.save() failed: repository exception.", e);
+                throw new SiteTreeException(e);
+            }
     }
 
     /**
@@ -634,6 +452,83 @@
         }
     }
 
+    protected String mapDocumentIdToJCRAbsolute(String documentId) {
+        assert documentId != null;
+        String mapping = "/" + prefixSys + ":" + SITETREE_NAME;
+        StringTokenizer tokenizer = new StringTokenizer(documentId, "/");
+        while (tokenizer.hasMoreTokens()) {
+            mapping += "/" + prefixUser + ":" + tokenizer.nextToken();
+        }
+        return mapping;
+    }
+
+    protected String mapDocumentIdToJCRRelative(String documentId) {
+        assert documentId != null;
+        String mapping = "";
+        StringTokenizer tokenizer = new StringTokenizer(documentId, "/");
+        while (tokenizer.hasMoreTokens()) {
+            mapping += "/" + prefixUser + ":" + tokenizer.nextToken();
+        }
+        return mapping;
+    }
+    
+    protected String mapJCRToDocumentId(String path) {
+        String mapping = path.replaceAll(prefixUser + ":", "");
+        mapping = mapping.replaceAll("/" + prefixSys + ":" + SITETREE_NAME, "");
+        return mapping;
+    }
+
+    /**
+     * Clone node from authoring area if possible. This assures that
+     * the correspondant nodes have the same UUID.
+     * 
+     * Attention: the cloning operation works directly on the repository
+     * and does not need a save.
+     * 
+     * @param parentNode
+     * @param id
+     * @return
+     */
+    private boolean clone(Node parentNode, String id) {
+        if (Publication.AUTHORING_AREA.equals(session.getWorkspace().getName())) {
+            // If in authoring area no cloning is possible.
+            return false;
+        } else {
+            // TODO: Clone node if possible from authoring area.
+            return false;
+        }
+    }
+    
+    public String getSystemPrefix() {
+        return prefixSys;
+    }
+    
+    public String getUserPrefix() {
+        return prefixUser;
+    }
+    
+    private String getNamespacePrefix(String namespace, String defaultPrefix) {
+        String prefix = null;
+        NamespaceRegistry registry = null;
+        try {
+            registry = session.getWorkspace().getNamespaceRegistry();
+            try {
+                prefix = registry.getPrefix(namespace);
+            } catch (NamespaceException e) {
+                // If prefix is not found, register default prefix
+                registry.registerNamespace(defaultPrefix, namespace);
+                prefix = defaultPrefix;
+            }
+        } catch (RepositoryException e) {
+            log.error("JCRSiteTree.getNamespacePrefix() failed: repository exception", e);
+        }
+        return prefix;
+    }
+    
+    public void logout() {
+        session.logout();
+    }
+
     /**
      * Get Repository
      * @param repHomeDir Path to repository
@@ -649,4 +544,5 @@
         RegistryHelper.registerRepository(ctx, "repo", configFile, repHomeDir, true);
         return (Repository) ctx.lookup("repo");
     }
+    
 }



---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@lenya.apache.org
For additional commands, e-mail: commits-help@lenya.apache.org