I came across this “challenge” a few weeks ago when I had to write content synchronization code for a project, where it was essential to specify the UUID of a JCR node in code to keep it consistent across systems.

Magnolia CMS offers several convenience classes and methods to work with the underlying JCR repository like the

info.magnolia.jcr.util.NodeUtil

class that offers methods for creating or updating content nodes - but none of them offers to directly set the UUID property.

When you have a technical background of working with Magnolia CMS or another JCR content system, you are aware of the possibility to keep ID’s the same when using import/export functionality.

Digging around in Jackrabbit core classes like org.apache.jackrabbit.core.NodeImpl you indeed can find the method

  public Node addNodeWithUuid(
            String relPath, String nodeTypeName, String uuid)
            throws RepositoryException {
        return perform(new AddNodeOperation(this, relPath, nodeTypeName, uuid));
    }

that solves the problem of setting a JCR UUID in code, see also https://issues.apache.org/jira/browse/JCR-1972.

Setting the UUID in Magnolia code

Typically, in Magnolia CMS you will work with nodes that are of the type javax.jcr.Node that has no direct possibitlity to “manually” set the UUID.

As we have seen above the NodeImpl class has the needed method so what we can do is to cast the existing java.jcr.node to the NodeImpl incarnation. We achieve this by unwrapping the node.

Example pseudo code

  // info.magnolia.jcr.util.NodeUtil
  // java.jcr.Node myParentNode

  final Node myUnwrappedNode = NodeUtil.unwrap(myParentNode);
  ((NodeImpl) myUnwrappedNode).addNodeWithUuid("my/node/path", "mgnl:page", "d172344e-6164-4268-8782-d03766b0e82e")

Of course you would create a generic method and not use static values.