Over a million developers have joined DZone.

Groovy Goodness: Check Configuration Property Is Set In ConfigObject

· Java Zone

Discover how AppDynamics steps in to upgrade your performance game and prevent your enterprise from these top 10 Java performance problems, brought to you in partnership with AppDynamics.

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.

The Java Zone is brought to you in partnership with AppDynamics. AppDynamics helps you gain the fundamentals behind application performance, and implement best practices so you can proactively analyze and act on performance problems as they arise, and more specifically with your Java applications. Start a Free Trial.


Published at DZone with permission of Hubert Klein Ikkink , DZone MVB .

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}