Getting Started with AEM Groovy Console: Exploring AEM Scripting with a Practical Example

14 / Jan / 2024 by Dayashankar Yadav 0 comments

Introduction

Groovy scripting provides AEM developers with a powerful toolset to enhance, automate, and extend the capabilities of Adobe Experience Manager. With its ease of use, seamless Java integration, and rapid development features, Groovy empowers developers to create efficient workflows, custom components, and seamless integrations. In this blog, we will explore AEM Groovy scripting through a simple use case example, showcasing how it can simplify content management and streamline workflows.

Understanding AEM Groovy Scripting

AEM Groovy Scripting is based on the Groovy language, a dynamic and object-oriented scripting language that runs on the Java Virtual Machine (JVM). The AEM Groovy Console serves as a user-friendly interface, enabling the execution of Groovy scripts within Adobe Experience Manager. These scripts offer extensive capabilities, such as content manipulation within the Java Content Repository (JCR), invocation of OSGi services, and the execution of custom code utilizing AEM, Sling, or JCR APIs.

Why use Groovy Script?

1. Rapid Development and Concise Syntax:  Groovy offers a concise and expressive syntax that reduces boilerplate code, leading to faster development cycles. This can significantly improve productivity, making it easier to create, modify, and maintain scripts within AEM.

2. Dynamic Typing and Flexibility: Groovy’s dynamic typing allows developers to write more flexible and adaptable code. This is particularly advantageous in AEM scripting, where content structures and requirements can evolve over time. The ability to work with dynamic types simplifies scripting tasks and promotes code reuse.

3. Powerful Scripting Capabilities:  Groovy provides powerful scripting features, enabling AEM developers to perform complex operations with concise and readable code. Scripting tasks such as content manipulation in the Java Content Repository (JCR), invocation of OSGi services, and execution of custom code are streamlined, enhancing the overall scripting experience.

4. Groovy Console for Interactive Scripting: AEM includes the Groovy Console, providing an interactive environment for testing and executing Groovy scripts. This console facilitates rapid prototyping, debugging, and exploration of AEM APIs, making it easier for developers to experiment and refine their scripts.

5. Extensibility and Customization: AEM developers can extend the functionality of their applications by incorporating custom scripts written in Groovy. This extensibility allows for tailoring solutions to specific project requirements, ensuring that AEM can meet the unique needs of diverse implementations.

Prerequisite

  • A running instance of AEM
  • Maven 3.x

Setting Up the Environment

 Before proceeding with AEM Groovy scripting, it is essential to set up the Groovy Console on your AEM instance. Below are the steps to configure the environment for Groovy scripting.

1. Install groovy-all-2.4.9.jar from http://<host>/system/console/bundles.

Download the jar from groovy-all-2.4.9 .

2. Install org.apache.felix.webconsole.plugins.scriptconsole-1.0.2.jar from http://<host>/system/console/bundles.

Download the jar from org.apache.felix.webconsole.plugins.scriptconsole.

3. Update Service user for script bundle

  • Go to http://<host>/system/console/configMgr.
  • Search for “Apache Sling Service User Mapper Service Amendment”
  • Add to Service

Mappings org.apache.felix.webconsole.plugins.scriptconsole:mysystemuser=mysystemuser

4. Access script console at http://<host>:<port>/system/console/sc.

5. Test attached sample groovy.

Sample Use Case solved by Groovy

Suppose we have an AEM page, and our objective is to remove a particular property from all of its child pages.

As part of this process, we will display each child page’s title while providing a message indicating whether the property is being deleted or if it doesn’t exist on that specific child page.

import com.day.cq.wcm.api.Page
import com.day.cq.wcm.api.PageManager
import org.apache.sling.api.resource.ResourceResolver
import org.apache.sling.api.resource.ResourceResolverFactory
import org.apache.sling.api.resource.Resource
import org.apache.sling.api.resource.ModifiableValueMap

def deletePropertyFromChildPages(String currentPage) throws IllegalArgumentException {
   Map<String, Object> param = new HashMap<String, Object>();
   param.put(ResourceResolverFactory.SUBSERVICE, "mysystemuser");
   ResourceResolverFactory resourceResolverFactory = osgi.getService(ResourceResolverFactory.class)
   ResourceResolver resolver = resourceResolverFactory.getServiceResourceResolver(param)
   PageManager pageManager = resolver.adaptTo(PageManager.class)
   Page current = pageManager.getPage(currentPage)
   Iterator<Page> iter = current.listChildren()

   while (iter.hasNext()) {
       final Page childPage = iter.next()
       String pageTitle = childPage.getTitle()
       out.println("Processing Page: " + pageTitle)
       String resourcePath = childPage.getPath() + "/jcr:content" // Adjust the path to jcr:content
       Resource jcrContentResource = resolver.getResource(resourcePath)
       if (jcrContentResource != null) {
           ModifiableValueMap properties = jcrContentResource.adaptTo(ModifiableValueMap.class)
           // Check if the property exists on this node
           if (properties.containsKey("hideSubItemsInNav")) {
               // Remove the property
               properties.remove("hideSubItemsInNav")
               resolver.commit()
               out.println("Property 'hideSubItemsInNav' removed from this node.")
           else {
               out.println("Property 'hideSubItemsInNav' does not exist on this node.")
           }
       else {
           out.println("jcr:content node not found for Page: " + pageTitle)
       }
   }
   resolver.close()
}
// calling the function here and providing the path 
deletePropertyFromChildPages("/content/we-retail/us/en")

Conclusion

The AEM Groovy Console serves as a user-friendly interface, facilitating the execution of Groovy scripts for content manipulation, invocation of OSGi services, and execution of custom code leveraging AEM, Sling, or JCR APIs. Through the exploration of a practical example, we’ve demonstrated how AEM Groovy scripting can simplify complex tasks, such as removing a specific property from all child pages of an AEM page.

Setting up the environment for AEM Groovy scripting involves configuring the Groovy Console, installing the necessary JAR files, and updating service users for script bundles. The provided use case illustrates the power of Groovy scripting in action, showcasing a script that efficiently removes a specified property from child pages while providing informative messages along the way.

FOUND THIS USEFUL? SHARE IT

Leave a Reply

Your email address will not be published. Required fields are marked *