Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Groovy Goodness: Check Configuration Property Is Set In ConfigObject

DZone's Guide to

Groovy Goodness: Check Configuration Property Is Set In ConfigObject

· Java Zone ·
Free Resource

Java-based (JDBC) data connectivity to SaaS, NoSQL, and Big Data. Download Now.

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.

Connect any Java based application to your SaaS data.  Over 100+ Java-based data source connectors.

Topics:

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}