April 3, 2020
Estimated Post Reading Time ~

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 than the 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.

An 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();
  }
 }
}

Reference: https://cqwemblog.wordpress.com/2013/12/07/servlet-to-remove-rendition-at-certain-path-in-cq5/


By aem4beginner

No comments:

Post a Comment

If you have any doubts or questions, please let us know.