Fullmenu null

 

07 March 2018

When your script is easy and require a few params probably parse the command line it’s enougth to you, using for example CliBuilder. As your application grown your requirements grown and you delegate to a properties file.

Although properties it’s a common option it’s easy to make mistakes. In this post we’ll see how easy is to use a format more readable for humans and powerfull than properties called YAML https://es.wikipedia.org/wiki/YAML

With this format we can write key values but also arrays, maps and so on. This is an example when we configure two datasources and one array of maps:

# config jerarquizada
dataSources:
    development:
        url: jdbc:mysql:localhost://desa
        username: user
        password: pwd
    production:
        url: jdbc:mysql:dataserver://prod
        username: sasdfoi123k
        password: asfd9.dslsd0

# array de [username,password]
logins:
    - username: pp
      password: PP

    - username: otro
      password: pazzz

The script will read the file and if they are some mistakes the parser will be throw an exception. Once the YML is loaded we can traverse the configuration using tipical groovy operators:

  • check if a key it’s present with the '?' operator

  • traverse across an array using each or eachWithIndex

@Grab('org.yaml:snakeyaml:1.17')
import org.yaml.snakeyaml.Yaml

Yaml parser = new Yaml()

config = parser.load( new File('config_script.yml').text )

println config.doesntExists ?: "doesnExists doesn't exists"

println config.dataSources?.development?.url

println config.dataSources?.production?.url

config.logins.eachWithIndex{ user, idx->
    println "index $idx:"
    println "$user.username = $user.password"
}

Script
@Grab('org.yaml:snakeyaml:1.17')
import org.yaml.snakeyaml.Yaml

Yaml parser = new Yaml()

config = parser.load( new File('config_script.yml').text )

println config.doesntExists ?: "doesnExists doesn't exists"

println config.dataSources?.development?.url

println config.dataSources?.production?.url

config.logins.eachWithIndex{ user, idx->
    println "index $idx:"
    println "$user.username = $user.password"
}