Performance Zone is brought to you in partnership with:

Hi all, my name is Hubert A. Klein Ikkink. Not a very common name, right? To make things easier I just picked the first letters of my firstname and surname and came up with haki. So there you have it, now I am also known as Mr. Haki or mrhaki for short. You can read more blog postings at www.mrhaki.com. I am a passionate Groovy and Java developer based in Tilburg, The Netherlands. My goal is to write clean, elegant, user-centered and high quality software. You can find me on Google+ and Twitter. Hubert is a DZone MVB and is not an employee of DZone and has posted 167 posts at DZone. You can read more from them at their website. View Full User Profile

Groovy Goodness: Check Configuration Property Is Set In ConfigObject

05.14.2014
| 4446 views |
  • submit to reddit

When we use ConfigSlurper to read a configuration file or script we get a ConfigObject as return result. We can get the values of the configuration properties by simply referring to the property name. The ConfigObject instance will resolve the name and returns the value. If we want to check if a property has a value we can use the property name in a condition. For example app.active ? 'active' : 'non-active'. But then Groovy truth also has a say here. app.active in a conditional context will return false if the property is not set or if the value returns false(taking into account Groovy truth).

Since Groovy 2.3 we can use the isSet method to check if a configuration property is available, before we get the value. This way we can distinguish between a non-existing property or a false value for an existing property.

// Configuration script.
def config = '''
app {
    version = 0
    active = false
}
'''

// Read configuration.
def configuration = new ConfigSlurper().parse(config)

// Check values for app. configuration properties.
configuration.app.with {
    // Existing boolean property.
    // Is property value false or non-existing?
    assert !active
    // Answer: value is false.
    assert isSet('active')


    // Not existing boolean property.
    // Is property value false or non-existing?
    assert !enabled
    // Answer: non-existing.
    assert !isSet('enabled')


    // Non boolean property.
    assert !version
    assert isSet('version')
    assert version == 0
}

Code written with Groovy 2.3.

Published at DZone with permission of Hubert Klein Ikkink, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)