Skip to content

Creating ConfigSlurper Files Programatically

The question that arose on the Groovy mailing list a while back was:

Is it possible to use the ConfigSlurper object itself to create config files?

I’ve just gotten around to thinking about this. The answer is…”sort of.”

One does not actually use ConfigSlurper, but ConfigObject, which has a writeTo method that “Writes this config object into a String serialized representation which can later be parsed back using the parse() method.”

A short example:

def co = new ConfigObject()

def strange = [string: 'hello', 'int': 42, 'double': 3.14]
co.put('some', ['strange': strange])
co.put('something.else', 'happy towel day')

def sw = new StringWriter()

println """Output from co.writeTo():


def cs = new ConfigSlurper('dev').parse(sw.toString())

println """Output from cs.toString():


The above constructs the equivalent of:

some {
  strange {
    string = 'hello'
    int = 42
    double = 3.14
something.else = 'happy towel day'

But there is a slight wrinkle: writeTo doesn’t write a file that is as beautiful as one that you or I might write.

The output from the example above shows this:

Output from co.writeTo():

some=['strange':['string':'hello', 'int':42, 'double':3.14]]
something.else='happy towel day'
Output from cs.toString():

[some:[strange:[string:hello, int:42, double:3.14]], something:[else:happy towel day]]

Nevertheless, one can “round trip” config files, if one needs to.

Hmmm…it is a bit of a shame that ConfigSlurper#toString() doesn’t produce a round-trippable string in-and-of itself. (Might be worth a quick Jira…ah…GROOVY-5194 already exists [but is not accurate?].)

Tags: ,

C, Java Enterprise Edition, JEE, J2EE, JBoss, Application Server, Glassfish, JavaServer Pages, JSP, Tag Libraries, Servlets, Enterprise Java Beans, EJB, Java Messaging Service JMS, BEA Weblogic, JBoss, Application Servers, Spring Framework, Groovy, Grails, Griffon, GPars, GAnt, Spock, Gradle, Seam, Open Source, Service Oriented Architectures, SOA, Java 2 Standard Edition, J2SE, Eclipse, Intellij, Oracle Service Bus, OSB