April 8, 2020
Estimated Post Reading Time ~

How to get all dam assets referred in a page?

At times when you quickly want to retrieve the list of all the assets that have been authored in a page, it can be an image, pdf, docs you can use this small piece of handy code. No need to write big and heavy services.

Here it has been shown as a simple class with a method getReferencesInPage(final String pagePath). When you are working on a project you can integrate this with service, servlets, sling model class according to your comfort and need.

Here is the main Asset API which has been used here. It returns a Map object, in case of servlets you can convert this Map objects to any String format , JSON format, etc.

package com.adobe.sample;

import org.apache.jackrabbit.JcrConstants;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceResolver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.day.cq.dam.api.Asset;
import com.day.cq.dam.api.DamConstants;
import com.day.cq.dam.commons.util.AssetReferenceSearch;
import java.util.Map;
import javax.jcr.Node;

public class AssetReferenceHelper {
 ResourceResolver resourceResolver = null;
 Logger log = LoggerFactory.getLogger(getClass());

 public Map < String, Asset > getReferencesInPage(final String pagePath) {
  log.info("Assets references to be retrieved for page {} ", pagePath);
  Resource resource = resourceResolver.getResource(pagePath + "/" + JcrConstants.JCR_CONTENT);
  Node pageNode = resource.adaptTo(Node.class);
  AssetReferenceSearch referenceSearch = new AssetReferenceSearch(pageNode, DamConstants.MOUNTPOINT_ASSETS, resourceResolver);

  if (referenceSearch.search().size() > 0) {
   log.info(" {} assets references on page {} ", referenceSearch.search().size(), pagePath);
   return referenceSearch.search();
  } else
   return null;
 }
}


By aem4beginner

No comments:

Post a Comment

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