get all descendant nodes of a given JCR Node

Question

Would it be possible to get all descendant nodes of a given JCR node? 

Answer

In scripts or actions, it could be useful to get all the subcontent of a given JCR node. Dependent on the required use case, you have different possibilities:

With a direct method on the node, you can get all the direct child nodes:

JCRNodeWrapper node = session.getNode(myPathToANode); //given JCR Node

JCRNodeIteratorWrapper nodes = node.getNodes();
while (nodes.hasNext()) {
    JCRNodeWrapper subNode = (JCRNodeWrapper)nodes.next();
    //TODO: your code with subNode  
}

 

To get all subNodes, not only the first level, you can use a simple query. The advantage of the query is you can also specify a specific nodeType:

 

        String myPathToGivenJCRNode = givenNode.getPath(); // givenNode is the given JCRNode

        String stmt = "SELECT * FROM [nt:base] where ISDESCENDANTNODE(myPathToGivenJCRNode)";
        QueryWrapper query = session.getWorkspace().getQueryManager().createQuery(stmt, Query.JCR_SQL2);
        javax.jcr.NodeIterator nodeIterator = query.execute().getNodes();
        while (nodeIterator.hasNext()) {
            JCRNodeWrapper node = (JCRNodeWrapper) nodeIterator.nextNode();
            //TODO: your code with the subnode
        }

The query above is using nodeType nt:base, this should return all subNodes of the given JCR Path. Any other nodeType can be used to return only the specific nodeTypes.