Content migration

In this blog post, I’d like to present a cool functionality that can be used for a content migration – AEM Groovy Console. You can find here its official webpage.

The official doc says: “The AEM Groovy Console provides an interface for running Groovy scripts in the AEM container.” In other words, you can write content migration scripts in Groovy language and execute them inside Groovy console. Also, the console makes some common Sling objects (like resource resolver, session, query manager, etc.) accessible so you can use them in the scripts.

Let’s demonstrate the usage on one simple and real scenario. Imagine that we have a component which path is /apps/someproject/components/content/samplecmp, and there are a lot of pages where this component is presented. Due to some refactoring, the component path is going to be changed in something like /apps/someproject/components/content/sample. In order to finish the refactoring work completely, we need to migrate the content as well. The old value someproject/components/content/samplecmp of sling:resourceType property has to be changed into someproject/components/content/sample.

The script could look like the following:

def doMigration() {

def queryManager = session.workspace.queryManager
def statement = "/jcr:root/content/someproject//*[@sling:resourceType='someproject/components/content/samplecmp']"
def query = queryManager.createQuery(statement, "xpath")
def result = query.execute()
def rows = result.rows

rows.each { row ->
def sampleComponentNode = getNode(row.path)
sampleComponentNode.set("sling:resourceType", "someproject/components/content/sample")
println "Updated sling:resourceType on ${row.path}"
}
}

doMigration()
session.save()

You can see in lines 3 and 5 that the script is referencing Sling objects (provided by the console as some kind of the global objects). In order to save the modifications made by the script, the statement in line 17 is important. The script can be further enhanced with dry run functionality if needed.

In order to run the script, open the console on the following URL – http://localhost:4502/etc/groovyconsole.html, copy/paste the script and press Run Script button.