[AEM6.5] Create a service which receives the path of a folder in DAM as input, and Output as JSON | Community
Skip to main content
tushaar_srivastava
Level 6
June 22, 2021
Solved

[AEM6.5] Create a service which receives the path of a folder in DAM as input, and Output as JSON

  • June 22, 2021
  • 2 replies
  • 2199 views

Hi Team,
I have a requirement, where
Create a service which receives the path of a folder in DAM as input and iterates through all image assets in that folder and returns a json response capturing the name and altText of each image in that folder. The output format should be -

 

[

{

"name":"<imageName>",

"altText": "<imageAltText>"

},

{

"name":"<imageName>",

"altText": "<imageAltText>"

},

...

]

Can anyone help me with this.

@vijayalakshmi_s   @himanshu_singhal  @arunpatidar 

This post is no longer active and is closed to new replies. Need help? Start a new post to ask your question.
Best answer by Vijayalakshmi_S

Hi @tushaar_srivastava,

Please find below sample snippet making use of Query Builder API to bring in the AEM assets under specific path.

  • Result sets are adapted to Asset object (com.day.cq.dam.api.Asset)
  • Assuming altText is a custom Metadata property, we can gain access to the same via Asset object.
  • org.json API(org.json.JSONObject & org.json.JSONArray) is used for JSON output. 
@Component(service = Servlet.class, property = {"sling.servlet.methods=" + HttpConstants.METHOD_GET, "sling.servlet.paths=/bin/assetdetails", "sling.servlet.extensions=json"}) public class AssetDetailsJSON extends SlingSafeMethodsServlet { private static final long serialVersionUID = 1L; private final Logger LOG = LoggerFactory.getLogger(this.getClass()); @Reference private QueryBuilder queryBuilder; @Override protected void doGet(final SlingHttpServletRequest req, final SlingHttpServletResponse resp) { //String assetFolderPath = req.getParameter("assetFolder"); String assetFolderPath = "/content/dam/we-retail/en/features"; Map<String, String> predicatesMap = new HashMap<String, String>(); ResourceResolver rescResolver = req.getResourceResolver(); Session session = rescResolver.adaptTo(Session.class); if (null != assetFolderPath) { predicatesMap.put("path", assetFolderPath); predicatesMap.put("type", "dam:Asset"); predicatesMap.put("p.limit", "-1"); Query query = queryBuilder.createQuery(PredicateGroup.create(predicatesMap), session); SearchResult queryResults = query.getResult(); JSONArray jsonArr = new JSONArray(); queryResults.getHits().forEach((hit) -> { try { String assetPath = hit.getPath(); Resource assetResc = rescResolver.resolve(assetPath); Asset assetObj = assetResc.adaptTo(Asset.class); String assetName = assetObj.getName(); String assetDAMPath = assetObj.getPath(); String assetFormat = assetObj.getMetadataValue("dc:format"); // can use getMetadataValueFromJcr as well JSONObject jsonObj = new JSONObject(); jsonObj.put("name", assetName); jsonObj.put("path", assetDAMPath); // can have altText here jsonObj.put("assetFormat", assetFormat); jsonArr.put(jsonObj); } catch (RepositoryException e) { LOG.error("RepositoryException={}", e.getMessage()); } catch (JSONException e) { LOG.error("JSONException={}", e.getMessage()); } }); try { LOG.debug("JSON Output={}", jsonArr.toString()); resp.setContentType("application/json"); resp.setCharacterEncoding("UTF-8"); resp.getWriter().write(jsonArr.toString()); } catch (IOException e) { LOG.error("IOException={}", e.getMessage()); } } else{ LOG.debug("No asset folder input !!"); } } }

 

2 replies

BrianKasingli
Community Advisor and Adobe Champion
Community Advisor and Adobe Champion
June 22, 2021

@tushaar_srivastava ,

Assuming that your use will be used within the author environment, I would create a Sling Servlet that will accept "path". The servlet will utilise the Query Manager, JCR-SQL2. Once when the results are obtained, then the backend logic will transform the result object, which will then output the formatted JSON.

// just a brief example below...

 

private static final String JCR_SQL_QUERY = "SELECT * FROM [dam:AssetContent] AS nodes WHERE ISDESCENDANTNODE ([{my_query}]"; ... @Override protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) { ... String formattedQuery = JCR_SQL_QUERY.replace("{my_query}", request.getParameter("path")); // JCR-SQL2 API (PICK ONE); Workspace workspace = session.getWorkspace(); QueryManager queryManager = workspace.getQueryManager(); Query query = queryManager.createQuery(formattedQuery, Query.JCR_SQL2); QueryResult result = query.execute(); // return transform and return JSON Object formattedJSON = formattedJSON(result); // output the response in JSON response.setContentType("application/json"); response.setCharacterEncoding("utf-8"); response.getWriter().write(formattedJSON); }

 

 

 

 

tushaar_srivastava
Level 6
June 23, 2021
Thank you BrianKasingli for this approach, I have created a textbox and on click on submit button invoked the servlet and based on that able to get the json.
Vijayalakshmi_S
Vijayalakshmi_SAccepted solution
Level 10
June 22, 2021

Hi @tushaar_srivastava,

Please find below sample snippet making use of Query Builder API to bring in the AEM assets under specific path.

  • Result sets are adapted to Asset object (com.day.cq.dam.api.Asset)
  • Assuming altText is a custom Metadata property, we can gain access to the same via Asset object.
  • org.json API(org.json.JSONObject & org.json.JSONArray) is used for JSON output. 
@Component(service = Servlet.class, property = {"sling.servlet.methods=" + HttpConstants.METHOD_GET, "sling.servlet.paths=/bin/assetdetails", "sling.servlet.extensions=json"}) public class AssetDetailsJSON extends SlingSafeMethodsServlet { private static final long serialVersionUID = 1L; private final Logger LOG = LoggerFactory.getLogger(this.getClass()); @Reference private QueryBuilder queryBuilder; @Override protected void doGet(final SlingHttpServletRequest req, final SlingHttpServletResponse resp) { //String assetFolderPath = req.getParameter("assetFolder"); String assetFolderPath = "/content/dam/we-retail/en/features"; Map<String, String> predicatesMap = new HashMap<String, String>(); ResourceResolver rescResolver = req.getResourceResolver(); Session session = rescResolver.adaptTo(Session.class); if (null != assetFolderPath) { predicatesMap.put("path", assetFolderPath); predicatesMap.put("type", "dam:Asset"); predicatesMap.put("p.limit", "-1"); Query query = queryBuilder.createQuery(PredicateGroup.create(predicatesMap), session); SearchResult queryResults = query.getResult(); JSONArray jsonArr = new JSONArray(); queryResults.getHits().forEach((hit) -> { try { String assetPath = hit.getPath(); Resource assetResc = rescResolver.resolve(assetPath); Asset assetObj = assetResc.adaptTo(Asset.class); String assetName = assetObj.getName(); String assetDAMPath = assetObj.getPath(); String assetFormat = assetObj.getMetadataValue("dc:format"); // can use getMetadataValueFromJcr as well JSONObject jsonObj = new JSONObject(); jsonObj.put("name", assetName); jsonObj.put("path", assetDAMPath); // can have altText here jsonObj.put("assetFormat", assetFormat); jsonArr.put(jsonObj); } catch (RepositoryException e) { LOG.error("RepositoryException={}", e.getMessage()); } catch (JSONException e) { LOG.error("JSONException={}", e.getMessage()); } }); try { LOG.debug("JSON Output={}", jsonArr.toString()); resp.setContentType("application/json"); resp.setCharacterEncoding("UTF-8"); resp.getWriter().write(jsonArr.toString()); } catch (IOException e) { LOG.error("IOException={}", e.getMessage()); } } else{ LOG.debug("No asset folder input !!"); } } }