Groovy's NodeBuilder for Configuration File Notation
I have always liked the way ant uses java properties files for configuration options. I also liked the convention of separating contexts within the property names by '.' I wanted to do something similar in groovy, but found that whatever I came up with always fell short because ant offered property validation. That is if you referred to a property that wasn't set or misspelled a property name, ant was all too happy to let you know. If you want that in groovy, you find yourself using AntBuilder. That practically means you're using ant at that point. I wanted something more native to groovy that would validate, have structure for contexts (hierarchical even), be modularly inclusive (that is I could reuse the configuration), and I wouldn't have to build much infrastructure for it.
Praise be to God!! NodeBuilder! Here is an example of how I create a configuration that represents my rdbms
cfg = new NodeBuilder().cfg {
db {
url 'jdbc:oracle:thin:@localhost:1521:UAZKFCFG'
ua {
name 'ua'
password 'secret'
}
kulowner {
name 'kulowner'
password 'secret'
}
}
}
You can see it creates a hierarchy. I don't have to redefine the 'url'. I can have multiple schemas attached to the url. It's great. Now how do I use this in my groovy code? Here's that example.
evaluate new File('config/environments.gv')
...
...
cfgTableDb = Sql.newInstance(cfg.db.url.text(),
cfg.db.ua.name.text(),
cfg.db.ua.password.text(),
ORACLE_DRIVER_NAME)
targetDb = Sql.newInstance(cfg.db.url.text(),
cfg.db.kulowner.name.text(),
cfg.db.kulowner.password.text(),
ORACLE_DRIVER_NAME)
You can see that I use evaluate() to load the configuration as normal groovy code within my script. I am then able to access the NodeBuilder instances and pass the values in to Sql.newInstance(). The best part is it's native groovy. It's not a String. If I misspell something, groovy will let me know with a compile error. Man I love this language!