AEM - Manipulate Nodes Using A Servlet (Java)
Often times we come across a situation where bunch of nodes need to be added to a certain “component” to every occurrence of that component in a specific folder. Sounds mouthful :-) We have several options for this.. write a javascript, run some groovy scripts and through a servlet.
tl;dr
This post details how to manipulate nodes in AEM using a Java servlet. Code at https://gist.github.com/ksurendra/168d7f3c7927419b8468ce5bd5b2f976
The Servlet
A servlet that has some path to be accessible. Remember this (can be) a one-time used code.
The sample I used the path as “/bin/sampleapp/manipulatecontent”. You may use any.
The input to the servlet is the path. So the above can be called as “/bin/sampleapp/manipulatecontent?searchpath=/content/sampleapp”
1: Search query
In this example I am looking for all occurrences of the component “bg” and then adding extra nodes to that component. “SearchPath” would be the input (or if you know the path, you may hard code it).
Map<String, String> queryParameterMap = new HashMap<>();
queryParameterMap.put("path", searchPath);
queryParameterMap.put("type", JcrConstants.NT_UNSTRUCTURED);
queryParameterMap.put("1_property", "sling:resourceType");
queryParameterMap.put("1_property.value", "sampleapp/components/content/bg");
2: Find the component’s node
Find all the paths that have the component.
List<Hit> hits = searchResult.getHits();
if (CollectionUtils.isNotEmpty(hits)) {
for (Hit hit : hits) {
hitPath = hit.getPath();
pageResource = resourceResolver.getResource(hitPath);
nodeToUpdate = resourceResolver.getResource(hitPath).adaptTo(Node.class);
...
3: Add the extra nodes
Add the properties you’d like to add to the component’s node.
Note: If you look at the example, I added some extra checks before adding nodes.
nodeToUpdate.setProperty("backgroundSpacing", "theme-3");
session.save();
That’s it!
Note: This is by no means THE solution. This worked for us. I would love to see ore such examples and code more simpler or efficient.
Resources
Complete servlet at https://gist.github.com/ksurendra/168d7f3c7927419b8468ce5bd5b2f976
Using Groovy scripts - <TBD>
Using Javascript - <TBD>