private static JcrNode createNodeWithUUID(JcrNode originalNode, JcrNode parentNode, String xmlns,
Map<String, String> uuidMap) {
// construct the import xml snippet
String uuid = originalNode.getIdentifier();
String name = originalNode.getName();
JcrSession session = parentNode.getSession();
StringBuilder xml = new StringBuilder();
xml.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
xml.append("<sv:node ");
xml.append(xmlns);
xml.append(" sv:name=\"");
xml.append(escapeMarkup(name));
xml.append("\">");
xml.append("<sv:property sv:name=\"jcr:primaryType\" sv:type=\"Name\"><sv:value>");
xml.append(escapeMarkup(originalNode.getPrimaryNodeType().getName()));
xml.append("</sv:value></sv:property>");
xml.append("<sv:property sv:name=\"jcr:mixinTypes\" sv:type=\"Name\">");
xml.append("<sv:value>mix:referenceable</sv:value></sv:property>");
xml.append("<sv:property sv:name=\"jcr:uuid\" sv:type=\"Name\"><sv:value>");
xml.append(uuid);
xml.append("</sv:value></sv:property></sv:node>");
InputStream stream = null;
try {
stream = new ByteArrayInputStream(xml.toString().getBytes("utf-8"));
}
catch (UnsupportedEncodingException e) {
// retarded
}
JcrNode existing = null;
try {
// there doesn't seem to be a way in JCR to check if there is
// such node in workspace
// except trying to get it and then catching the exception
existing = session.getNodeByIdentifier(uuid);
}
catch (JcrException e) {
}
int uuidBehavior;
if (existing != null && existing.getParent().equals(parentNode)) {
uuidBehavior = ImportUUIDBehavior.IMPORT_UUID_COLLISION_REPLACE_EXISTING;
} else {
uuidBehavior = ImportUUIDBehavior.IMPORT_UUID_CREATE_NEW;
}
if (uuidBehavior != ImportUUIDBehavior.IMPORT_UUID_CREATE_NEW) {
// simpler alternative - if we replace node or throw error on UUID
// clash
session.importXML(parentNode.getPath(), stream, uuidBehavior);
return session.getNodeByIdentifier(uuid);
} else {
// more complicated alternative - on uuid clash node gets new uuid
// and all
// cloned references should use the new one
boolean exists = existing != null;
session.importXML(parentNode.getPath(), stream, uuidBehavior);
if (exists == false) {
// if there was no node with such uuid in target workspace
return session.getNodeByIdentifier(uuid);
} else {
// otherwise get the latest child with such name
JcrNodeIterator iterator = parentNode.getNodes(name);
iterator.skip(iterator.getSize() - 1);
JcrNode newNode = iterator.nextNode();