Wednesday 13 May 2015

Working with ITERATOR


Iterator is the most important thing when it comes to traversing the nodes or pages in cq5. so, let's know what exactly is it and how does it work.

What is iterator :
Iterator is an interface which is in "java.util.Iterator".

What is it used for :
It is used to iterate through the nodes or pages in cq, it returns the references of the existing child nodes or pages inside a particular node or page

How does it work internally :
It calls a recursive function (Recursion is when a function calls itself, data is stored in stack which works on LIFO).
1. Information of current node is stored in stack and if it has child node, it will go to child and child of child  till a node has no child.
2. Then it will find the another sibling of the current node, repeat 1.
3. It visits all the nodes by backtracking to the parent node.
4. It follows preorder traversing, described at the end of this post.

It returns all the child pages inside it when "true" parameter is passed
Iterator<Page> children = root.listChildren(new PageFilter(),true);

But returns only its immediate children when
Iterator<Page> children = root.listChildren(new PageFilter());


Creating a component which will return all the child pages of the selected page with restricted depth :

                       




Names :-
pathField = ./path
numberField = ./depth

Code in jsp :


<%-- showchild component.


  It will display the child pages a/c to the selector


--%>

   <%@include file="/libs/wcm/global.jsp"%><%
%><%@ page import="java.util.Iterator,com.day.cq.wcm.api.PageFilter"%>

    <h2>show</h2>

    <%

String path = properties.get("path", currentPage.getPath());

String value=properties.get("depth","1");
int required_depth = Integer.valueOf(value);
int relative_depth=0;
int i;
Page root=pageManager.getPage(path);

if (root != null) 

{
String title_root = root.getTitle() == null ? root.getName() : root.getTitle();
%><a href="<%=root%>.html"><b><%=title_root%></b></a><br><%

    int root_depth = root.getDepth();



     Iterator<Page> children = root.listChildren(new PageFilter(),true);

     while (children.hasNext()) 
     {

    Page child = children.next();

  relative_depth= child.getDepth() - root_depth;


        if(relative_depth<=required_depth)

        {
           for(i=0;i<relative_depth;i++)
           {
            %><b>--------></b><%
           }

           String title = child.getTitle() == null ? child.getName() : child.getTitle();


     %><a href="<%=child.getPath()%>.html"><b><%=title%></b></a><br><%

       }
     }
   
}

%>



Preorder explained :

(i) Visit the root.
(ii) Traverse the left subtree.
(iii) Traverse the right subtree.

Let's assume a tree :



The Preorder traversal output of the above tree :
               7, 1, 0, 3, 2, 5, 4, 6, 9, 8, 10




No comments:

Post a Comment