0

I am trying to dynamically create an XML file with Groovy. I'm pleased with the simplicity everything works, but i am having a hard time understanding the whole mechanism behind closures and delegates. While it appears to be easy to add properties and child nodes with a fixed name, adding a node with a dynamic name appears to be a special case.

My use case is creating a _rep_policy file, which can be used in CQ5.

<?xml version="1.0" encoding="UTF-8"?>
<jcr:root xmlns:jcr="http://www.jcp.org/jcr/1.0" xmlns:rep="internal"
          jcr:primaryType="rep:ACL">
  <allow
      jcr:primaryType="rep:GrantACE"
      rep:principalName="administrators"
      rep:privileges="{Name}[jcr:all]"/>
  <allow0
      jcr:primaryType="rep:GrantACE"
      rep:principalName="contributor"
      rep:privileges="{Name}[jcr:read]"/>
</jcr:root>

Processing the collections works fine, but generating the name ...

import groovy.xml.StreamingMarkupBuilder import groovy.xml.XmlUtil

def _rep_policy_files = [
    '/content': [ // the path
        'deny': [ // permission
            'jcr:read': [ // action
                'a1', 'b2']], // groups
        'allow': [
            'jcr:read, jcr:write': [
                'c2']
        ]
    ]
]

def getNodeName(n, i) {
  (i == 0) ? n : n + (i - 1)
}

_rep_policy_files.each {
  path, permissions ->
    def builder = new StreamingMarkupBuilder();

    builder.encoding = "UTF-8";

    def p = builder.bind {
      mkp.xmlDeclaration()

      namespaces << [
          jcr: 'http://www.jcp.org/jcr/1.0',
          rep: 'internal'
      ]

      'jcr:root'('jcr:primaryType': 'rep:ACL') {
        permissions.each {
          permission, actions ->
            actions.each {
              action, groups ->
                groups.eachWithIndex {
                  group, index ->
                    def nodeName = getNodeName(permission, index)
                    "$nodeName"(
                        'jcr:primaryType': 'rep:GrantACE',
                        'rep:principalName': "$group",
                        'rep:privileges': "{Name}[$action]")
                }
            }
        }
      }
    }

    print(XmlUtil.serialize(p))
}
Florian Salihovic
  • 3,921
  • 2
  • 19
  • 26

1 Answers1

1

Is this something (or similar) that you are looking for?

'jcr:root'('jcr:primaryType': 'rep:ACL') {
    _rep_policy_files['/content'].each {k, v ->
       if(k == 'allow')
           "$k"('jcr:primaryType': 'rep:GrantACE', 
                'rep:principalName': 'administrators', 
                'rep:privileges': "$v"  ){}
       if(k == 'deny')
           "$k"('jcr:primaryType': 'rep:GrantACE', 
                'rep:principalName': 'contributor', 
                'rep:privileges': "$v"  ){}
    }
}

The resultant xml shown in question cannot be apprehended properly with what you have in _rep_policy_files.

dmahapatro
  • 49,365
  • 7
  • 88
  • 117