I am new to ConfigObject. I am planning to use it for storing the results of an analytics job. However occasionally I might need to add new configuration field, and I am having a difficult time adding variables to ConfigObject. So I decided to add a map instead. But that is not getting formatted correctly, resulting in error while reading back. I am not sure how to proceed..
config.groovy file
-------------------
"serverX" {
var {
low=-12.89
maybe_low=1.65
maybe_high=40.45
high=55
}
}
rest of Script
----------------------
ConfigObject conf = new ConfigSlurper("development").parse(new File("config.groovy").toURI().toURL());
System.out.println(conf);
// New object to add
def var_stuff = ['low' : 0] + ['maybe_low' : 0] + ['maybe_high' : 0] + ['high' : 0]
def var_object = ['var' : var_stuff]
def final_var_object = ['ServerY' : var_object]
def new_config_object = final_var_object as ConfigObject
conf.merge(new_config_object)
def file1 = new File('newconfig.groovy')
file1.withWriter('UTF-8') { writer ->
conf.writeTo(writer)
}
But the result turns out to be
serverX {
var {
low=-12.89
maybe_low=1.65
maybe_high=40.45
high=55
}
}
serverY=["var":["low":0, "maybe_low":0, "maybe_high":0, "high":0]]
I did consider doing the following
ConfigObject conf_new = new ConfigObject();
conf_new."ServerY".tukey.low = 0
conf_new."ServerY".tukey.maybe_low = 0
conf_new."ServerY".tukey.maybe_high = 0
conf.merge(conf_new)
Which works great. But since "ServerY" is a variable for me, I cannot write such manual statements.
Any hints?
EDIT: 5th March 2016
As per Emmanuel's recommendation, i tried the following
def server = 'ServerY'
def more = [
(server): [
var: [
low: 0,
maybe_low: 0,
maybe_high: 0,
high: 0
]
]
]
conf.putAll(more)
def obj1_temp = conf as Map
System.out.println(obj1_temp)
/* which looks like this:
{ServerX={var={low=-12.89, maybe_low=1.65, maybe_high=40.45, high=55}}, ServerY={var={low=0, maybe_low=0, maybe_high=0, high=0}}}
*/
def file1 = new File('app/tasks/newconfig.groovy')
file1.withWriter('UTF-8') { writer ->
conf.writeTo(writer)
}
However output in the file is still similar as before :-(
ServerX {
var {
low=-12.89
maybe_low=1.65
maybe_high=40.45
high=55
}
}
ServerY=["var":["low":0, "maybe_low":0, "maybe_high":0, "high":0]]
which doesn't parse properly when reading back.
You can use putMap() to add the Map entries to the ConfigObject.
import groovy.util.ConfigSlurper
def content = '''
"serverX" {
var {
low=-12.89
maybe_low=1.65
maybe_high=40.45
high=55
}
}
'''
def conf = new ConfigSlurper("development").parse(content) // Using a String for demonstration purposes
def server = 'ServerY'
def more = [
(server): [
var: [
low: 0,
maybe_low: 0,
maybe_high: 0,
high: 0
]
]
]
conf.putAll(more)
// A test showing it works.
assert conf as Map == [
serverX:[
var:[
low:-12.89,
maybe_low:1.65,
maybe_high:40.45,
high:55]
],
ServerY:[
var:[
low:0,
maybe_low:0,
maybe_high:0,
high:0
]
]
]
Update
So, putAll() didn't work as I expected. Here's the solution:
import groovy.util.ConfigSlurper
import groovy.util.ConfigObject
def content = '''
"serverX" {
var {
low=-12.89
maybe_low=1.65
maybe_high=40.45
high=55
}
}
'''
def mergeConfig = { configObject, server, map ->
configObject.merge new ConfigObject().with {
def var = getProperty(server).getProperty('var')
map.each { key, value ->
var.put(key, value)
}
delegate
}
configObject
}
def conf = new ConfigSlurper("development").parse(content) // Using a String for demonstration purposes
conf = mergeConfig(conf, 'ServerY', [low: 0, maybe_low: 0, maybe_high: 0, high: 0])
You can now call mergeConfig() continuously to merge configurations. In this example, mergeConfig() is a Closure, but it would work as a method also.
Related
Why does the following work?
<something>.stop().animate(
{ 'top' : 10 }, 10
);
Whereas this doesn't work:
var thetop = 'top';
<something>.stop().animate(
{ thetop : 10 }, 10
);
To make it even clearer: At the moment I'm not able to pass a CSS property to the animate function as a variable.
{ thetop : 10 } is a valid object literal. The code will create an object with a property named thetop that has a value of 10. Both the following are the same:
obj = { thetop : 10 };
obj = { "thetop" : 10 };
In ES5 and earlier, you cannot use a variable as a property name inside an object literal. Your only option is to do the following:
var thetop = "top";
// create the object literal
var aniArgs = {};
// Assign the variable property name with a value of 10
aniArgs[thetop] = 10;
// Pass the resulting object to the animate method
<something>.stop().animate(
aniArgs, 10
);
ES6 defines ComputedPropertyName as part of the grammar for object literals, which allows you to write the code like this:
var thetop = "top",
obj = { [thetop]: 10 };
console.log(obj.top); // -> 10
You can use this new syntax in the latest versions of each mainstream browser.
With ECMAScript 2015 you are now able to do it directly in object declaration with the brackets notation:
var obj = {
[key]: value
}
Where key can be any sort of expression (e.g. a variable) returning a value.
So here your code would look like:
<something>.stop().animate({
[thetop]: 10
}, 10)
Where thetop will be evaluated before being used as key.
ES5 quote that says it should not work
Note: rules have changed for ES6: https://stackoverflow.com/a/2274327/895245
Spec: http://www.ecma-international.org/ecma-262/5.1/#sec-11.1.5
PropertyName :
IdentifierName
StringLiteral
NumericLiteral
[...]
The production PropertyName : IdentifierName is evaluated as follows:
Return the String value containing the same sequence of characters as the IdentifierName.
The production PropertyName : StringLiteral is evaluated as follows:
Return the SV [String value] of the StringLiteral.
The production PropertyName : NumericLiteral is evaluated as follows:
Let nbr be the result of forming the value of the NumericLiteral.
Return ToString(nbr).
This means that:
{ theTop : 10 } is the exact same as { 'theTop' : 10 }
The PropertyName theTop is an IdentifierName, so it gets converted to the 'theTop' string value, which is the string value of 'theTop'.
It is not possible to write object initializers (literals) with variable keys.
The only three options are IdentifierName (expands to string literal), StringLiteral, and NumericLiteral (also expands to a string).
ES6 / 2020
If you're trying to push data to an object using "key:value" from any other source, you can use something like this:
let obj = {}
let key = "foo"
let value = "bar"
obj[`${key}`] = value
// A `console.log(obj)` would return:
// {foo: "bar}
// A `typeof obj` would return:
// "object"
Hope this helps someone :)
I have used the following to add a property with a "dynamic" name to an object:
var key = 'top';
$('#myElement').animate(
(function(o) { o[key]=10; return o;})({left: 20, width: 100}),
10
);
key is the name of the new property.
The object of properties passed to animate will be {left: 20, width: 100, top: 10}
This is just using the required [] notation as recommended by the other answers, but with fewer lines of code!
Adding square bracket around the variable works good for me. Try this
var thetop = 'top';
<something>.stop().animate(
{ [thetop] : 10 }, 10
);
You can also try like this:
const arr = [{
"description": "THURSDAY",
"count": "1",
"date": "2019-12-05"
},
{
"description": "WEDNESDAY",
"count": "0",
"date": "2019-12-04"
}]
const res = arr.map(value => {
return { [value.description]: { count: value.count, date: value.date } }
})
console.log(res);
I couldn't find a simple example about the differences between ES6 and ES5, so I made one. Both code samples create exactly the same object. But the ES5 example also works in older browsers (like IE11), wheres the ES6 example doesn't.
ES6
var matrix = {};
var a = 'one';
var b = 'two';
var c = 'three';
var d = 'four';
matrix[a] = {[b]: {[c]: d}};
ES5
var matrix = {};
var a = 'one';
var b = 'two';
var c = 'three';
var d = 'four';
function addObj(obj, key, value) {
obj[key] = value;
return obj;
}
matrix[a] = addObj({}, b, addObj({}, c, d));
Update: As a commenter pointed out, any version of JavaScript that supports arrow functions will also support ({[myKey]:myValue}), so this answer has no actual use-case (and, in fact, it might break in some bizarre corner-cases).
Don't use the below-listed method.
I can't believe this hasn't been posted yet: just use arrow functions with anonymous evaluation!
Completely non-invasive, doesn't mess with the namespace, and it takes just one line:
myNewObj = ((k,v)=>{o={};o[k]=v;return o;})(myKey,myValue);
demo:
var myKey="valueof_myKey";
var myValue="valueof_myValue";
var myNewObj = ((k,v)=>{o={};o[k]=v;return o;})(myKey,myValue);
console.log(myNewObj);
useful in environments that don't support the new {[myKey]: myValue} syntax yet, such as—apparently; I just verified it on my Web Developer Console—Firefox 72.0.1, released 2020-01-08. I stand corrected; just wrap the thing in parenthesis and it works.
(I'm sure you could potentially make some more powerful/extensible solutions or whatever involving clever use of reduce, but at that point you'd probably be better served by just breaking out the Object-creation into its own function instead of compulsively jamming it all inline)
not that it matters since OP asked this ten years ago, but for completeness' sake and to demonstrate how it is exactly the answer to the question as stated, I'll show this in the original context:
var thetop = 'top';
<something>.stop().animate(
((k,v)=>{o={};o[k]=v;return o;})(thetop,10), 10
);
Given code:
var thetop = 'top';
<something>.stop().animate(
{ thetop : 10 }, 10
);
Translation:
var thetop = 'top';
var config = { thetop : 10 }; // config.thetop = 10
<something>.stop().animate(config, 10);
As you can see, the { thetop : 10 } declaration doesn't make use of the variable thetop. Instead it creates an object with a key named thetop. If you want the key to be the value of the variable thetop, then you will have to use square brackets around thetop:
var thetop = 'top';
var config = { [thetop] : 10 }; // config.top = 10
<something>.stop().animate(config, 10);
The square bracket syntax has been introduced with ES6. In earlier versions of JavaScript, you would have to do the following:
var thetop = 'top';
var config = (
obj = {},
obj['' + thetop] = 10,
obj
); // config.top = 10
<something>.stop().animate(config, 10);
2020 update/example...
A more complex example, using brackets and literals...something you may have to do for example with vue/axios. Wrap the literal in the brackets, so
[ ` ... ` ]
{
[`filter[${query.key}]`]: query.value, // 'filter[foo]' : 'bar'
}
ES5 implementation to assign keys is below:
var obj = Object.create(null),
objArgs = (
(objArgs = {}),
(objArgs.someKey = {
value: 'someValue'
}), objArgs);
Object.defineProperties(obj, objArgs);
I've attached a snippet I used to convert to bare object.
var obj = {
'key1': 'value1',
'key2': 'value2',
'key3': [
'value3',
'value4',
],
'key4': {
'key5': 'value5'
}
}
var bareObj = function(obj) {
var objArgs,
bareObj = Object.create(null);
Object.entries(obj).forEach(function([key, value]) {
var objArgs = (
(objArgs = {}),
(objArgs[key] = {
value: value
}), objArgs);
Object.defineProperties(bareObj, objArgs);
});
return {
input: obj,
output: bareObj
};
}(obj);
if (!Object.entries) {
Object.entries = function(obj){
var arr = [];
Object.keys(obj).forEach(function(key){
arr.push([key, obj[key]]);
});
return arr;
}
}
console(bareObj);
If you want object key to be same as variable name, there's a short hand in ES 2015.
New notations in ECMAScript 2015
var thetop = 10;
var obj = { thetop };
console.log(obj.thetop); // print 10
You can do it this way:
var thetop = 'top';
<something>.stop().animate(
new function() {this[thetop] = 10;}, 10
);
This way also you can achieve desired output
var jsonobj={};
var count=0;
$(document).on('click','#btnadd', function() {
jsonobj[count]=new Array({ "1" : $("#txtone").val()},{ "2" : $("#txttwo").val()});
count++;
console.clear();
console.log(jsonobj);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span>value 1</span><input id="txtone" type="text"/>
<span>value 2</span><input id="txttwo" type="text"/>
<button id="btnadd">Add</button>
You could do the following for ES5:
var theTop = 'top'
<something>.stop().animate(
JSON.parse('{"' + theTop + '":' + JSON.stringify(10) + '}'), 10
)
Or extract to a function:
function newObj (key, value) {
return JSON.parse('{"' + key + '":' + JSON.stringify(value) + '}')
}
var theTop = 'top'
<something>.stop().animate(
newObj(theTop, 10), 10
)
I'd love to know what I'm doing wrong - can't access "links" on my JSON file.
Part of code (MainActivity.kt):
var arr = arrayListOf<String>()
fun read_json() {
var json : String? = null
try {
val inputStream:InputStream = assets.open("links.json")
json = inputStream.bufferedReader().use{it.readText()}
var jsonarr = JSONArray(json)
for (i in 0..jsonarr.length()-1){
var jsonobj = jsonarr.getJSONObject(i)
arr.add(jsonobj.getString("links"))
}
var adapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, arr)
json_list.adapter = adapter
}
catch(e : IOException){
}
}
JSON file:
{
"links":
[
"google.com",
"youtube.com",
"facebook.com"
]
}
If I remake JSON file, so it will like in the following JSON file, everything works fine. However, I need to use the previous file. 😒
[
{
"links": "google.com"
}
]
Would really appreciate your help!
I believe you need to get the JSON array first and read strings from it, something like this:
var jsonarr = JSONObject(json).getJSONArray("links")
for (i in 0..jsonarr.length()-1) {
arr.add(jsonarr.getString(i))
}
I have two module that output respectively
output "discovery_service_hostname" {
value = "${aws_appmesh_virtual_service.service.name}"
}
and
output "discovery_service_arn" {
value = zipmap( aws_service_discovery_service.sd[*].name, aws_service_discovery_service.sd[*].arn)
}
Both are used in the main script that outputs
output "services" {
value = {
"web" = "${module.web.discovery_service_hostname}"
"wwb-backend" = "${module.web_backend.discovery_service_hostname}"
"wwb-backend-n" = "${module.web_backend_n.discovery_service_hostname}"
}
}
in this case I used the 1st module for web andweb-backend, while I used the 2nd module for web-backend-n
I need to access the service arn via lookup function in a 3rd script, but I would avoid duplicating the whole code to handle the two cases
final output like this
discovery_service = {
"web" = "arn:xxx1"
"web-backend" = "arn:xxx2"
"web-backend-n" = {
"web-backend-n-1" = "arn:xxx3"
"web-backend-n-2" = "arn:xxx4
"web-backend-n-3" = "arn:xxx5"
}
Is there a way to have an output like
discovery_service = {
"web" = "arn:xxx1"
"web-backend" = "arn:xxx2"
"web-backend-n-1" = "arn:xxx3"
"web-backend-n-2" = "arn:xxx4
"web-backend-n-3" = "arn:xxx5"
}
thanks!
I will answer my own question. Solution is to always output a map (even from the module with single outputs) like this:
output "discovery_service_arn" {
value = zipmap( [ aws_service_discovery_service.sd.name ], [ aws_service_discovery_service.sd.arn ])
}
and
output "discovery_service_arn" {
value = zipmap( aws_service_discovery_service.sd[*].name, aws_service_discovery_service.sd[*].arn)
}
then in the final script use merge to get a single map like
output "discovery_service" {
value = merge(
module.web.discovery_service_arn,
module.web_backend.discovery_service_arn,
module.web_backend_n.discovery_service_arn
)
}
Why does the following work?
<something>.stop().animate(
{ 'top' : 10 }, 10
);
Whereas this doesn't work:
var thetop = 'top';
<something>.stop().animate(
{ thetop : 10 }, 10
);
To make it even clearer: At the moment I'm not able to pass a CSS property to the animate function as a variable.
{ thetop : 10 } is a valid object literal. The code will create an object with a property named thetop that has a value of 10. Both the following are the same:
obj = { thetop : 10 };
obj = { "thetop" : 10 };
In ES5 and earlier, you cannot use a variable as a property name inside an object literal. Your only option is to do the following:
var thetop = "top";
// create the object literal
var aniArgs = {};
// Assign the variable property name with a value of 10
aniArgs[thetop] = 10;
// Pass the resulting object to the animate method
<something>.stop().animate(
aniArgs, 10
);
ES6 defines ComputedPropertyName as part of the grammar for object literals, which allows you to write the code like this:
var thetop = "top",
obj = { [thetop]: 10 };
console.log(obj.top); // -> 10
You can use this new syntax in the latest versions of each mainstream browser.
With ECMAScript 2015 you are now able to do it directly in object declaration with the brackets notation:
var obj = {
[key]: value
}
Where key can be any sort of expression (e.g. a variable) returning a value.
So here your code would look like:
<something>.stop().animate({
[thetop]: 10
}, 10)
Where thetop will be evaluated before being used as key.
ES5 quote that says it should not work
Note: rules have changed for ES6: https://stackoverflow.com/a/2274327/895245
Spec: http://www.ecma-international.org/ecma-262/5.1/#sec-11.1.5
PropertyName :
IdentifierName
StringLiteral
NumericLiteral
[...]
The production PropertyName : IdentifierName is evaluated as follows:
Return the String value containing the same sequence of characters as the IdentifierName.
The production PropertyName : StringLiteral is evaluated as follows:
Return the SV [String value] of the StringLiteral.
The production PropertyName : NumericLiteral is evaluated as follows:
Let nbr be the result of forming the value of the NumericLiteral.
Return ToString(nbr).
This means that:
{ theTop : 10 } is the exact same as { 'theTop' : 10 }
The PropertyName theTop is an IdentifierName, so it gets converted to the 'theTop' string value, which is the string value of 'theTop'.
It is not possible to write object initializers (literals) with variable keys.
The only three options are IdentifierName (expands to string literal), StringLiteral, and NumericLiteral (also expands to a string).
ES6 / 2020
If you're trying to push data to an object using "key:value" from any other source, you can use something like this:
let obj = {}
let key = "foo"
let value = "bar"
obj[`${key}`] = value
// A `console.log(obj)` would return:
// {foo: "bar}
// A `typeof obj` would return:
// "object"
Hope this helps someone :)
I have used the following to add a property with a "dynamic" name to an object:
var key = 'top';
$('#myElement').animate(
(function(o) { o[key]=10; return o;})({left: 20, width: 100}),
10
);
key is the name of the new property.
The object of properties passed to animate will be {left: 20, width: 100, top: 10}
This is just using the required [] notation as recommended by the other answers, but with fewer lines of code!
Adding square bracket around the variable works good for me. Try this
var thetop = 'top';
<something>.stop().animate(
{ [thetop] : 10 }, 10
);
You can also try like this:
const arr = [{
"description": "THURSDAY",
"count": "1",
"date": "2019-12-05"
},
{
"description": "WEDNESDAY",
"count": "0",
"date": "2019-12-04"
}]
const res = arr.map(value => {
return { [value.description]: { count: value.count, date: value.date } }
})
console.log(res);
I couldn't find a simple example about the differences between ES6 and ES5, so I made one. Both code samples create exactly the same object. But the ES5 example also works in older browsers (like IE11), wheres the ES6 example doesn't.
ES6
var matrix = {};
var a = 'one';
var b = 'two';
var c = 'three';
var d = 'four';
matrix[a] = {[b]: {[c]: d}};
ES5
var matrix = {};
var a = 'one';
var b = 'two';
var c = 'three';
var d = 'four';
function addObj(obj, key, value) {
obj[key] = value;
return obj;
}
matrix[a] = addObj({}, b, addObj({}, c, d));
Update: As a commenter pointed out, any version of JavaScript that supports arrow functions will also support ({[myKey]:myValue}), so this answer has no actual use-case (and, in fact, it might break in some bizarre corner-cases).
Don't use the below-listed method.
I can't believe this hasn't been posted yet: just use arrow functions with anonymous evaluation!
Completely non-invasive, doesn't mess with the namespace, and it takes just one line:
myNewObj = ((k,v)=>{o={};o[k]=v;return o;})(myKey,myValue);
demo:
var myKey="valueof_myKey";
var myValue="valueof_myValue";
var myNewObj = ((k,v)=>{o={};o[k]=v;return o;})(myKey,myValue);
console.log(myNewObj);
useful in environments that don't support the new {[myKey]: myValue} syntax yet, such as—apparently; I just verified it on my Web Developer Console—Firefox 72.0.1, released 2020-01-08. I stand corrected; just wrap the thing in parenthesis and it works.
(I'm sure you could potentially make some more powerful/extensible solutions or whatever involving clever use of reduce, but at that point you'd probably be better served by just breaking out the Object-creation into its own function instead of compulsively jamming it all inline)
not that it matters since OP asked this ten years ago, but for completeness' sake and to demonstrate how it is exactly the answer to the question as stated, I'll show this in the original context:
var thetop = 'top';
<something>.stop().animate(
((k,v)=>{o={};o[k]=v;return o;})(thetop,10), 10
);
Given code:
var thetop = 'top';
<something>.stop().animate(
{ thetop : 10 }, 10
);
Translation:
var thetop = 'top';
var config = { thetop : 10 }; // config.thetop = 10
<something>.stop().animate(config, 10);
As you can see, the { thetop : 10 } declaration doesn't make use of the variable thetop. Instead it creates an object with a key named thetop. If you want the key to be the value of the variable thetop, then you will have to use square brackets around thetop:
var thetop = 'top';
var config = { [thetop] : 10 }; // config.top = 10
<something>.stop().animate(config, 10);
The square bracket syntax has been introduced with ES6. In earlier versions of JavaScript, you would have to do the following:
var thetop = 'top';
var config = (
obj = {},
obj['' + thetop] = 10,
obj
); // config.top = 10
<something>.stop().animate(config, 10);
2020 update/example...
A more complex example, using brackets and literals...something you may have to do for example with vue/axios. Wrap the literal in the brackets, so
[ ` ... ` ]
{
[`filter[${query.key}]`]: query.value, // 'filter[foo]' : 'bar'
}
ES5 implementation to assign keys is below:
var obj = Object.create(null),
objArgs = (
(objArgs = {}),
(objArgs.someKey = {
value: 'someValue'
}), objArgs);
Object.defineProperties(obj, objArgs);
I've attached a snippet I used to convert to bare object.
var obj = {
'key1': 'value1',
'key2': 'value2',
'key3': [
'value3',
'value4',
],
'key4': {
'key5': 'value5'
}
}
var bareObj = function(obj) {
var objArgs,
bareObj = Object.create(null);
Object.entries(obj).forEach(function([key, value]) {
var objArgs = (
(objArgs = {}),
(objArgs[key] = {
value: value
}), objArgs);
Object.defineProperties(bareObj, objArgs);
});
return {
input: obj,
output: bareObj
};
}(obj);
if (!Object.entries) {
Object.entries = function(obj){
var arr = [];
Object.keys(obj).forEach(function(key){
arr.push([key, obj[key]]);
});
return arr;
}
}
console(bareObj);
If you want object key to be same as variable name, there's a short hand in ES 2015.
New notations in ECMAScript 2015
var thetop = 10;
var obj = { thetop };
console.log(obj.thetop); // print 10
You can do it this way:
var thetop = 'top';
<something>.stop().animate(
new function() {this[thetop] = 10;}, 10
);
This way also you can achieve desired output
var jsonobj={};
var count=0;
$(document).on('click','#btnadd', function() {
jsonobj[count]=new Array({ "1" : $("#txtone").val()},{ "2" : $("#txttwo").val()});
count++;
console.clear();
console.log(jsonobj);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span>value 1</span><input id="txtone" type="text"/>
<span>value 2</span><input id="txttwo" type="text"/>
<button id="btnadd">Add</button>
You could do the following for ES5:
var theTop = 'top'
<something>.stop().animate(
JSON.parse('{"' + theTop + '":' + JSON.stringify(10) + '}'), 10
)
Or extract to a function:
function newObj (key, value) {
return JSON.parse('{"' + key + '":' + JSON.stringify(value) + '}')
}
var theTop = 'top'
<something>.stop().animate(
newObj(theTop, 10), 10
)
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))
}
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.