Expand my Community achievements bar.

Dive into Adobe Summit 2024! Explore curated list of AEM sessions & labs, register, connect with experts, ask questions, engage, and share insights. Don't miss the excitement.
SOLVED

I tried deleting one node and iterating forward it gives error

Avatar

Level 7

I tried the below code but it gives error NODE DOESN'T EXIST ANY MORE

 

 

public void deleteNode(Resource resource, Node n) throws RepositoryException 
     {
    	 int flag=0;
    	 if("/".equals(n.getPath())) {
             return;
         }
    	 if(Objects.nonNull(resource) && resource.hasChildren()) {
    		 for(Map.Entry delete:deleteNode.entrySet()) {
        		 String delPath[]=delete.getKey().toString().split("=");
        		 boolean value=(boolean) delete.getValue();
        		 LOG.info("NON DELETION is "+delPath[0]+" should be "+delPath[1]+" "+value);
        		if (n.getPath().equals(delPath[0])||n.getName().equals(launchName)|| n.getName().equals("cq:LiveSyncConfig")||n.getName().equals("root")||n.getName().equals("responsivegrid")) {flag++;}
        		
        	 }
    		 
    	 }
    	 //n.getSession().save();
    	 final NodeIterator it = n.getNodes();
         while(it.hasNext()) {
             final Node next = it.nextNode();
             if(flag==0)
    		 {
    			 LOG.info("DELETING NODE "+n.getPath());
    			 n.remove();
    			 n.getSession().save();
    		 }
             deleteNode(resource,next);
         }
    }

 

1 Accepted Solution

Avatar

Correct answer by
Level 7
 	 if(flag==0)
		 {
			 LOG.info("DELETING NODE "+n.getPath());
			n.remove();
			n=resource.adaptTo(Node.class);
			n.getSession().save();
		 }

   	 final NodeIterator it = n.getNodes();
        while(it.hasNext()) {
            final Node next = it.nextNode();
           
            deleteNode(resource,next);
        }
   	 

View solution in original post

3 Replies

Avatar

Community Advisor

Hi,

 

Check if you are deleting the parent node and trying to delete the child node. Once parent node is deleted all child nodes will be deleted. Based on the exception which you are getting seems the parent node is getting deleted first and you are trying to delete child node. 

 

Note: NodeIterator is present before delete it will have all the nodes 

Avatar

Community Advisor

@Ronnie09 

Hi It seems to me we are iterating child nodes of node 'n' and instead of doing next.remove() we are doing n.remove(). Once the parent node is removed there won't be anything to iterate forward.

Avatar

Correct answer by
Level 7
 	 if(flag==0)
		 {
			 LOG.info("DELETING NODE "+n.getPath());
			n.remove();
			n=resource.adaptTo(Node.class);
			n.getSession().save();
		 }

   	 final NodeIterator it = n.getNodes();
        while(it.hasNext()) {
            final Node next = it.nextNode();
           
            deleteNode(resource,next);
        }