ian.
---------------------------------------------------------------------
To unsubscribe from this list, please visit:
http://xircles.codehaus.org/manage_email
Ian
boardtc wrote:
> Thanks for the idea. I think you are suggesting to add my maps to my
> configObject, that sounds ideal. Looking at the api, t descends from a
> LinkedHashMap.
>
> Would one use addEntry(int hash, K key, V value, int bucketIndex) .to
> add the map? Some example code would be much appreciated.
>
> Cheers,
>
> Tom.
>
>
> On 27 June 2010 10:07, Ian Cairns <i...@iancairns.org
I'm not sure the Groovy gurus would consider this groovy, it's probably
too Java-ish.
The basis of what I do, ignoring error checking code, is:
----------------------------------------8<-----------------------------------------
class Configuration {
ConfigObject cfg
File file
Configuration(filePath) {
this.file = new File(filePath)
if ( file.exists() ) {
cfg = new ConfigSlurper().parse(file.toURL())
} else {
cfg = new ConfigObject()
}
}
def persist() {
file.withWriter { writer ->
cfg.writeTo(writer)
}
}
def put(String key, value) {
def pathElements = []
key.split('/').each { if (it) {pathElements << it} }
def depth = pathElements.size() - 1
def node = cfg
for (int i = 0; i < depth; i++) {
node = node.getProperty(pathElements[i])
}
node.put(pathElements[depth], value)
}
def get(String key) {
def pathElements = []
key.split('/').each { if (it) {pathElements << it} }
def depth = pathElements.size() - 1
def node = cfg
for (int i = 0; i < depth; i++) {
node = node.getProperty(pathElements[i])
}
return node.get(pathElements[depth])
}
}
def config = new Configuration('/tmp/testConfig')
config.put('/a/b/f1', 'first field')
config.put('/a/b/f2', 'second field')
config.persist()
----------------------------------------8<-----------------------------------------
and then just "cat /tmp/testConfig" and you should see something like:
a {
b {
f1="first field"
f2="second field"
}
}
Note the use of "getProperty(key)" which creates subsidiary ConfigObject
objects when necessary.
How get() and put() are implemented is really dependent on your
application. I've assumed the key is a String to keep things simple.
I actually have a tree of DefaultMutableTreeNode objects based on the
ConfigObject tree, and the latter gets updated when changes are made to
the former, so there's no direct get() / put() as such.
Glad to be able to help.
What flavour of Map are you storing? HashMap? LinkedHashMap?
I'm not sure that persisting the ConfigObject to file will work if
there's a POJO Map in there.
Ian