10. Groovy Script - Use Cases
Magnolia Groovy Script - Use Cases
Here you will find a selection of use cases that will support you in your daily work with Groovy script
Content Manipulation
Bulk updating content properties
import info.magnolia.context.MgnlContext
def jcrSession = MgnlContext.getJCRSession("website")
def rootNode = jcrSession.getNode("/path/to/page")
rootNode.nodes.each { node ->
if (node.isNodeType("mgnl:content")) {
node.setProperty("newProperty", "newValue")
}
}
jcrSession.save()
Page Node Manipulation
Change a property in a page node, save and publish it
import info.magnolia.context.MgnlContext
import info.magnolia.commands.CommandsManager
import info.magnolia.jcr.util.NodeUtil
// Function to update a property on a node
def updateProperty(Node node, String propertyName, String propertyValue) {
if (node.hasProperty(propertyName)) {
node.setProperty(propertyName, propertyValue)
println "Property '${propertyName}' changed on node: ${node.getPath()}"
} else {
println "Property '${propertyName}' not found on node: ${node.path}"
}
}
// Function to publish a node using the workflow module
def publishNode(Node node) {
String nodePath = node.getPath()
println(nodePath)
try {
map = new java.util.LinkedHashMap<String, String>()
map.put("path", nodePath)
map.put("repository", "website")
map.put("recursive", false)
cm = info.magnolia.commands.CommandsManager.getInstance()
cm.executeCommand('default','publish',map)
println "Published node: ${nodePath}"
} catch (Exception e) {
println "Unable to publish node: ${nodePath}"
println "Error: ${e.message}"
}
}
// Main script logic
def session = MgnlContext.getJCRSession("website")
def nodePath = "/your/path"
try {
def rootNode = session.getNode(nodePath)
// Update property
updateProperty(rootNode, "temp", "2")
// Save session changes
session.save()
// Publish the node
publishNode(rootNode)
} catch (javax.jcr.PathNotFoundException e) {
println "Error: The node with path '${nodePath}' does not exist."
} catch (Exception e) {
println "Error processing node: ${nodePath}, Error: ${e.message}"
}
User Management Tasks
Accessing user Data
import info.magnolia.context.MgnlContext
def jcrSession = MgnlContext.getJCRSession("users")
def rootNode = jcrSession.getNode("/system")
def childNodes = rootNode.getNodes()
childNodes.eachWithIndex { user, index ->
def username = user.getName()
println "Username ${index+1}: $username"
}
Change the publish date of a page
import info.magnolia.context.MgnlContext
import java.text.SimpleDateFormat
import java.util.Calendar
// Define the path of the page and the new publish date
def pagePath = "/your/path"
def newPublishDateStr = "2024-02-22" // Format: YYYY-MM-DD
def targetProperty = "mgnl:lastActivated"
// Function to parse the date string and return a Calendar object
def parseDate(String dateStr) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd")
Calendar cal = Calendar.getInstance()
cal.time = sdf.parse(dateStr)
return cal
}
// Main script logic
def session = MgnlContext.getJCRSession("website")
if (session.nodeExists(pagePath)) {
def pageNode = session.getNode(pagePath)
def newPublishDate = parseDate(newPublishDateStr)
// Update the publish date
if (pageNode.hasProperty(targetProperty)) {
pageNode.setProperty(targetProperty, newPublishDate)
session.save()
println "Updated publish date of '${pagePath}' to '${newPublishDateStr}'"
} else {
println "Publish date property not found on '${pagePath}'"
}
} else {
println "Page node not found: ${pagePath}"
}
Change a category of a page
Check if category is available
import info.magnolia.context.MgnlContext
// Define the path of the page and the category
def pagePath = "/your/page/path"
def catName = "your/category"
//Setup sessions
categorySession = MgnlContext.getJCRSession("category")
websiteSession = MgnlContext.getJCRSession("website")
// Function to check if a category exists
def categoryExists(String categoryName) {
rootCategoryNode = categorySession.getRootNode()
return rootCategoryNode.hasNode(categoryName)
}
// Function to get category uuId
def getCategoryUUID(String categoryName) {
rootCategoryNode = categorySession.getRootNode()
def categoryNode = rootCategoryNode.getNode(categoryName)
return categoryNode.getIdentifier()
}
// Main script logic
if (websiteSession.nodeExists(pagePath)) {
def pageNode = websiteSession.getNode(pagePath)
if (categoryExists(catName)) {
// Get the uuId
def catId = getCategoryUUID(catName)
// Update the category of the page
pageNode.setProperty("category", catId)
websiteSession.save()
println "Updated category of page '${pagePath}' to '${catId}' (${catName})"
} else {
println "Category '${catName}' does not exist"
}
} else {
println "Page node not found: ${pagePath}"
}
[Hint: Your implementation may differ depending on how you define the category on the page node. It is often stored as an array if several categories can be assigned per page]
Language properties
Recursively iterate over pages and their components, find and delete specific language properties
import info.magnolia.context.MgnlContext
import javax.jcr.Node
import javax.jcr.Session
// Define the language code to identify the properties to delete
def languageCode = "de" // Example: 'de' for German
// Function to delete language-specific properties of a node
def deleteLanguageSpecificProperties(Node node, String langCode) {
def properties = node.properties
properties.each { property ->
if (property.name.endsWith("_${langCode}")) {
property.remove()
println "Deleted property: ${property.name} from node: ${node.path}"
}
}
}
// Function to process page and component nodes
def processNode(Node node, String langCode) {
deleteLanguageSpecificProperties(node, langCode)
// Recursively process child nodes
node.nodes.each { childNode ->
processNode(childNode, langCode)
}
}
// Main script logic
def session = MgnlContext.getJCRSession("website")
def rootNode = session.getRootNode()
rootNode.nodes.each { pageNode ->
if (childNode.isNodeType("mgnl:page")) {
try {
processNode(pageNode, languageCode)
session.save() // Save the session after processing each page
} catch (Exception e) {
println "Error processing page: ${pageNode.path}, Error: ${e.message}"
}
}
}
Get the activation status of a node
def getActivationStatusAsString(Node node){
java.lang.Integer status = info.magnolia.jcr.util.NodeTypes.Activatable.getActivationStatus(node);
switch(status){
case 0:{
return "notActivated";
}
case 1:{
return "isModified";
}
case 2:{
return "isActivated";
}
default:{
return ""
}
}
}
[notActivated(0): status red]
[isModified(1): status yellow]
[isActivated(2): status green]
Properties can also be accessed directly:
info.magnolia.jcr.util.NodeTypes.Activatable.ACTIVATION_STATUS_MODIFIED;
info.magnolia.jcr.util.NodeTypes.Activatable.ACTIVATION_STATUS_ACTIVATED;
info.magnolia.jcr.util.NodeTypes.Activatable.ACTIVATION_STATUS_NOT_ACTIVATED;
they return true/false in each case
Contact the author