April 7, 2020
Estimated Post Reading Time ~

Servlet to get all tags assigned to a DAM Asset in JSON format

Recently there was a requirement to fetch all tags assigned to DAM Assets. It can be implemented via servlets where an Ajax call can be made. If you have never worked on such kind of use case then this is a must to learn and implement article for you. It uses Tag Manager API and returns data in JSON format. In our scenario it was easy to get data in JSON format, however, you are free to convert it to any bases on your requirement

1. Define the annotaton @slingServlet with path you want to use for accessing it.

@SlingServlet(paths = "/bin/getDamTags") 
public class DamTags extends org.apache.sling.api.servlets.SlingAllMethodsServlet

2. Get the ‘path‘ parameter from the request to get the image location. Once received, adapt this resource to the Asset class. Start reading the ‘cq:tags‘ property where all tags are stored.


String path = slingRequest.getParameter("path");
LOGGER.info("Path received.. {}", path);

Resource resource = slingRequest.getResourceResolver().getResource(path);
Asset asset = resource.adaptTo(Asset.class);

Object[] titleArray = null;
Object titleObj = asset.getMetadata("cq:tags");
if (titleObj instanceof Object[]) {
 titleArray = (Object[]) titleObj;
}

3. Now you have tags, but we need to get the title of tags and convert them into a JSON object that has to be returned.


JSONObject damTagsJson = new JSONObject();
JSONArray tags = new JSONArray();

for (Object ob: titleArray) {
 String a = ob.toString();
 TagManager tagManager = null;
 tagManager = slingRequest.getResourceResolver().adaptTo(TagManager.class);
 Tag custTag = tagManager.resolve(a);
 tags.put(custTag.getTitle());
}

4. At last, return the output in JSON format
// Output tags in json format 
out.print(damTagsJson.put("damTags", tags));

5. The same request can be made via JS to get the response



Here is the final complete code that can be used 

package com.simple.util;

import java.io.PrintWriter;
import org.apache.felix.scr.annotations.sling.SlingServlet;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.commons.json.JSONArray;
import org.apache.sling.commons.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.day.cq.dam.api.Asset;
import com.day.cq.tagging.TagManager;
import com.day.cq.tagging.Tag;
import com.day.cq.dam.api.Asset;

/**
 * 
 * @author praveen
 *
 */

@SlingServlet(paths = "/bin/getDamTags")
public class DamTags extends org.apache.sling.api.servlets.SlingAllMethodsServlet {

 private static final Logger LOGGER = LoggerFactory.getLogger(DamTags.class);

 protected void doGet(SlingHttpServletRequest slingRequest,
  SlingHttpServletResponse slingResponse) {
  try {
   LOGGER.info("Getting request to .....");

   // Get print writer object to output
   PrintWriter out = slingResponse.getWriter();
   String path = slingRequest.getParameter("path");
   LOGGER.info("Path received.. {}", path);

   Resource resource = slingRequest.getResourceResolver().getResource(path);
   Asset asset = resource.adaptTo(Asset.class);

   Object[] titleArray = null;
   Object titleObj = asset.getMetadata("cq:tags");
   if (titleObj instanceof Object[]) {
    titleArray = (Object[]) titleObj;
   }

   JSONObject damTagsJson = new JSONObject();
   JSONArray tags = new JSONArray();

   for (Object ob: titleArray) {
    String a = ob.toString();
    TagManager tagManager = null;
    tagManager = slingRequest.getResourceResolver().adaptTo(
     TagManager.class);
    Tag custTag = tagManager.resolve(a);
    tags.put(custTag.getTitle());
   }

   // Output tags in json format
   out.print(damTagsJson.put("damTags", tags));

  } catch (Exception e) {
   LOGGER.info("Exception while fetching DAM assets tags " +
    e.getMessage());
  }
 }
}


By aem4beginner

No comments:

Post a Comment

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