This article shows how to set a JCR’s UUID in code to keep it consistent across systems. Magnolia CMS provides several convenient classes and methods for working with the underlying JCR repository, such as the
info.magnolia.jcr.util.NodeUtil
class that provides methods for creating or updating content nodes. None of these provide a way to set the UUID property directly.
If you have a technical background working with Magnolia CMS or any other JCR content system, you may be familiar with the ability to keep IDs the same when using import/export functionality.
If you dig around in Jackrabbit core classes like org.apache.jackrabbit.core.NodeImpl, you will indeed find the method
public Node addNodeWithUuid (String relPath, String nodeTypeName, String uuid) throws RepositoryException {
return perform(new AddNodeOperation(this, relPath, nodeTypeName, uuid));
}
which solves the problem of setting a JCR UUID in code, see also Preserving UUID and document version history on repository migration.
Set the UUID in the code
Typically, in Magnolia CMS, you will be working with nodes that are of type javax.jcr.Node, which has no direct way to “manually” set the UUID. The NodeImpl class has the required method, so we can simply convert the existing java.jcr.Node to the NodeImpl version. We accomplish this by unwrapping the node.
Example pseudocode
// 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 should make a general method and not use fixed values.