com.adobe.cq.social.ugcbase.core.LocalJcrUtils Maven / Gradle / Ivy
/*************************************************************************
*
* ADOBE CONFIDENTIAL
* __________________
*
* Copyright 2015 Adobe Systems Incorporated
* All Rights Reserved.
*
* NOTICE: All information contained herein is, and remains
* the property of Adobe Systems Incorporated and its suppliers,
* if any. The intellectual and technical concepts contained
* herein are proprietary to Adobe Systems Incorporated and its
* suppliers and are protected by trade secret or copyright law.
* Dissemination of this information or reproduction of this material
* is strictly forbidden unless prior written permission is obtained
* from Adobe Systems Incorporated.
**************************************************************************/
package com.adobe.cq.social.ugcbase.core;
import javax.jcr.AccessDeniedException;
import javax.jcr.Node;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import org.apache.jackrabbit.commons.JcrUtils;
import org.apache.jackrabbit.util.Text;
public class LocalJcrUtils {
/*
* Creates or gets the {@link javax.jcr.Node Node} at the given path. In case it has to create the Node all
* non-existent intermediate path-elements will be created with the given intermediate node type and the returned
* node will be created with the given nodeType. This version exists to ensure creation only needs to read and
* write the deepest of the existing ancestors of the target node. This allows creation of paths where some
* ancestors exist but are not readable by the session in use. For further details see: {@link
* org.apache.jackrabbit.commons.JcrUtils.getOrCreateByPath(Node, String, boolean, String, String, boolean) }
*/
public static Node getOrCreateByPathDepthFirst(final String path, final boolean createUniqueLeaf,
final String intermediateNodeType, final String nodeType, final Session session, final boolean autoSave)
throws RepositoryException {
String workingPath = path.startsWith("/") ? path : ("/" + path);
if (workingPath.endsWith("/")) {
workingPath = workingPath.substring(0, workingPath.length() - 1);
}
String checkPath = Text.getRelativeParent(workingPath, 1);
Node base = null;
do {
if (session.nodeExists(checkPath)) {
base = session.getNode(checkPath);
break;
}
checkPath = Text.getRelativeParent(checkPath, 1);
} while (!checkPath.isEmpty() && !"/".equals(checkPath));
if (base == null) {
try {
base = session.getRootNode();
} catch (final AccessDeniedException ade) {
throw new AccessDeniedException("Failed to access root node for the creation of " + path, ade);
}
}
String createPath = workingPath.substring(checkPath.length());
if (createPath.startsWith("/")) {
createPath = createPath.substring(1);
}
return JcrUtils.getOrCreateByPath(base, createPath, false, intermediateNodeType, nodeType, autoSave);
}
}