Servlet to remove renditions at certain path in CQ5

You see a lot of space is being taken by dam assets that are uploaded on a daily basis and want to claim some of that disk space. This need can arrive when the authors of your system do not care about renditions other that original one they submitted. So, how would you remove the renditions other than the original one.

Here is the servlet code to do the same. The code written below expects a path like /content/dam  -> don’t give such a path because all your renditions might get removed. Concentrate on blocks where a large number of images are submitted and give them as paths. I am using QueryBuilder API to search for the rendition folder and then i iterate over each node and remove them and finally i save the session and phew!! all the renditions other than original ones are deleted.

A example URI to run the sample code below will be like this.
http://localhost:4502/bin/removerenditions?path=/content/dam/yourpath

 @SlingServlet(paths = "/bin/removerenditions", metatype = true, methods = { "GET",  
 "POST" })  
 public class RemoveRenditionServlet extends AbstractPredicateServlet{  
      private Session session;  
      @Reference  
       private QueryBuilder builder;  
      public void doGet(final SlingHttpServletRequest slingHTTPrequest,final SlingHttpServletResponse response) throws IOException {  
           try{  
                ResourceResolver resourceResolver = slingHTTPrequest.getResourceResolver();  
                String path = slingHTTPrequest.getParameter("path");  
                session = resourceResolver.adaptTo(Session.class);  
                Map<String, String> map = new HashMap<String, String>();  
                map.put("path", path);  
                map.put("property", "jcr:primaryType");  
                map.put("property.1_value", "nt:folder");  
                Query query = builder.createQuery(PredicateGroup.create(map), session);  
          SearchResult result = query.getResult();  
          List<Hit> hits = result.getHits();  
          for(Hit hit: hits){  
               Resource renditionResource = resourceResolver.resolve(hit.getPath());       
               Iterator<Resource> reneditionIterator = renditionResource.listChildren();  
                while(reneditionIterator.hasNext()){  
                  Resource specificResource= reneditionIterator.next();  
                  Node renditionNode = specificResource.adaptTo(Node.class);  
                  if(!renditionNode.getName().equals("original")){  
                       renditionNode.remove();  
                  }  
             }  
          }  
          session.save(); 
          session.logout();
     }catch(Exception e){  
                e.printStackTrace();  
           }  
      }  
 }  

One thought on “Servlet to remove renditions at certain path in CQ5

  1. Pingback: Workflow to remove renditions other than the original one | cqwemblog

Leave a comment