April 11, 2020
Estimated Post Reading Time ~

AEM - Query list of components and templates

Some time while migration or for auditing purposes we need to know where a particular component/template or any other resource has been used. Have you ever wondered about how to fetch a list of all the paths where a particular component or template is being used?

I this short article I am going to show a quick way to write a utility with which you can get a list of paths (actual resource nodes) where a targeted resource is being used.

Here is the code snipped:
public void getResourceListHelper(Resource parentResource, String targetSearchPropertyKey,
String targetSearchPropertyValue, List components) {

Resource childResource;
for (Iterator resourceChildrenIter = parentResource.listChildren(); resourceChildrenIter.hasNext();
getResourceListHelper(childResource, targetSearchPropertyKey, targetSearchPropertyValue, components)) {
childResource = (Resource) resourceChildrenIter.next();
ValueMap childProperties = (ValueMap) childResource.adaptTo(ValueMap.class);

if (targetSearchPropertyValue.equals(childProperties.get(
targetSearchPropertyKey, String.class))) {
components.add(childResource);
}
}

}



Code is pretty much self-explanatory but, I’ll give you a quick walkthrough:

  • Here we have Java method take 4 arguments
  1. parentResource: this is a parent resource/node under which we want to perform a search.
  2. targetSearchPropertyKey: property name under “parentResource” and its sub-resources (child nodes) that we want to search for
  3. targetSearchPropertyValue: the value of the property that should be matched
  4. components: This is a collection/list where all the resources after the search are completed will be accumulated.
  • There is a recursive call to navigate child resources/nodes under given parent resource
  • The method will not return anything rather result (resources that matched the search) will be accumulated in components collection.
Let’s look at one quick day-to-day scenario. Let’s say we have a web site create in AEM under /content/sites/demo and we want to know all the nodes where the “title” component is used. To get this information we need to call:

getResourceListHelper(demo, “sling:resourceType”, “app/components/title”, resourceList);


By aem4beginner

No comments:

Post a Comment

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