aemjcr

How to create a series of nodes in AEM


I want to create a series of nodes like parentProduct/subCategory1/subCategory2/subCategory3/subCategory4 inside /var/temp location. I tried to use addNode() method of Node class and createPath() method of JcrUtil class but both did not work. addNode() method just creates only one immediate node(ex, parentProduct) but it is creating second level onwards.

Is there any API available that can create a series of nodes, ex-parentProduct/subCategory1/subCategory2/subCategory3/subCategory4?

protected final void doGet(final SlingHttpServletRequest request, final SlingHttpServletResponse response)
            throws IOException {
        final Session session;
        final ResourceResolver resourceResolver = request.getResourceResolver();
        session = resourceResolver.adaptTo(Session.class);
        long count = 0;
        final String path = "/var/temp";
        final PrintWriter out = response.getWriter();
        try {

            if (session.nodeExists(path)) {
                Node jcrNode = session.getNode(path);
                jcrNode.addNode("parentProduct/subCategory1/subCategory2/subCategory3/subCategory4");
                //jcrNode.addNode("parentProduct");
                //JcrUtil.createPath("parentProduct/subCategory1/subCategory2/subCategory3/subCategory4",JcrConstants.NT_UNSTRUCTURED, session);

            }
            session.save();

        } catch (ItemExistsException ex) {
            LOG.error("ItemExistsException", ex);
        } catch (RepositoryException exp) {
            LOG.error("RepositoryException", exp);
        } finally {
            if (session != null) {
                session.logout();
            }
        }
    }

Solution

  • There is more than one way to do it. For example,

    import org.apache.sling.api.resource.ResourceUtil;
    import org.apache.jackrabbit.JcrConstants;
    
    String path = "/var/temp/parentProduct/subCategory1/subCategory2/subCategory3/subCategory4";
    Resource subCategory4 = ResourceUtil.getOrCreateResource(
            resourceResolver, 
            path,                         // The full path to be created 
            JcrConstants.NT_UNSTRUCTURED, // resource type of the final resource to create
            JcrConstants.NT_UNSTRUCTURED, // resource type of all intermediate resources
            true                          // save  chnages
            );