Quantcast
Viewing all articles
Browse latest Browse all 526

AEM 61 - Get References of a Page or Asset

Goal


Servlet for returning Page or Asset references....

Solution


1) Install OSGI Servlet apps.experienceaem.references.GetReferences with the following code

package apps.experienceaem.references;

import com.day.cq.commons.TidyJSONWriter;
import com.day.cq.wcm.commons.ReferenceSearch;
import org.apache.commons.lang3.StringUtils;
import org.apache.felix.scr.annotations.Properties;
import org.apache.felix.scr.annotations.Property;
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.ResourceResolver;
import org.apache.sling.api.servlets.SlingAllMethodsServlet;

import javax.servlet.ServletException;
import java.io.IOException;
import java.util.Collection;

@SlingServlet
@Properties({
@Property(name = "sling.servlet.methods", value = {"GET"}, propertyPrivate = true),
@Property(name = "sling.servlet.paths", value = "/bin/experience-aem/references", propertyPrivate = true),
@Property(name = "sling.servlet.extensions", value = "json", propertyPrivate = true)})
public class GetReferences extends SlingAllMethodsServlet {
@Override
protected void doGet(SlingHttpServletRequest request,SlingHttpServletResponse response)
throws ServletException, IOException {
String path = request.getParameter("path");

if(StringUtils.isEmpty(path)){
throw new ServletException("Empty path");
}

try{
ResourceResolver resolver = request.getResourceResolver();
TidyJSONWriter writer = new TidyJSONWriter(response.getWriter());

ReferenceSearch referenceSearch = new ReferenceSearch();
referenceSearch.setExact(true);
referenceSearch.setHollow(true);
referenceSearch.setMaxReferencesPerPage(-1);

Collection<ReferenceSearch.Info> resultSet = referenceSearch.search(resolver, path).values();

writer.array();

for (ReferenceSearch.Info info: resultSet) {
for (String p: info.getProperties()) {
writer.value(p);
}
}

writer.endArray();
}catch(Exception e){
throw new ServletException("Error getting references", e);
}
}
}

2) Sample call returning asset referenceshttp://localhost:4502/bin/experience-aem/references?path=/content/dam/geometrixx/portraits/jane_doe.jpg

Image may be NSFW.
Clik here to view.

3) Sample call returning page references - http://localhost:4502/bin/experience-aem/references?path=/content/geometrixx/en

Image may be NSFW.
Clik here to view.



Viewing all articles
Browse latest Browse all 526

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>