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 have 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 list if 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 walkthourhg:
  1. Here we have Java method take 4 arguments
    • parentResource: this is parent resource/node under which we want to perform search.
    • targetSearchPropertyKey: property name under “parentResource” and its sub-resources (child nodes) that we want to search for
    • targetSearchPropertyValue: value of property that should be matched
    • components: This is a collection/list where all the resources after search is completed will be accumulated.
  1. There is a recursive call to navigate child resources/nodes under given parent resource
  2. Method will not return anything rather result (resources that matched 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 “title” component is used. To get this information we need to call:

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

Thanks for reading!!!

Comments

Unknown said…
Hi Suryakant,

Thanks a lot for share your knowledge, i always read your blogs, it helps me understand AEM.

Popular posts from this blog

AEM as a Cloud Service (AEMaaCS) – Architecture Overview

Custom synchronisation or rollout action for blueprint ?

AEM as a Cloud Service (AEMaaCS) – Quick Introduction

Generating URL based on AEM RUN mode using AEM Externalizer Service