- •Credits
- •About the Authors
- •About the Reviewers
- •www.PacktPub.com
- •Table of Contents
- •Preface
- •Introduction
- •Installing Groovy on Windows
- •Installing Groovy on Linux and OS X
- •Executing Groovy code from the command line
- •Using Groovy as a command-line text file editor
- •Running Groovy with invokedynamic support
- •Building Groovy from source
- •Managing multiple Groovy installations on Linux
- •Using groovysh to try out Groovy commands
- •Starting groovyConsole to execute Groovy snippets
- •Configuring Groovy in Eclipse
- •Configuring Groovy in IntelliJ IDEA
- •Introduction
- •Using Java classes from Groovy
- •Embedding Groovy into Java
- •Compiling Groovy code
- •Generating documentation for Groovy code
- •Introduction
- •Searching strings with regular expressions
- •Writing less verbose Java Beans with Groovy Beans
- •Inheriting constructors in Groovy classes
- •Defining code as data in Groovy
- •Defining data structures as code in Groovy
- •Implementing multiple inheritance in Groovy
- •Defining type-checking rules for dynamic code
- •Adding automatic logging to Groovy classes
- •Introduction
- •Reading from a file
- •Reading a text file line by line
- •Processing every word in a text file
- •Writing to a file
- •Replacing tabs with spaces in a text file
- •Deleting a file or directory
- •Walking through a directory recursively
- •Searching for files
- •Changing file attributes on Windows
- •Reading data from a ZIP file
- •Reading an Excel file
- •Extracting data from a PDF
- •Introduction
- •Reading XML using XmlSlurper
- •Reading XML using XmlParser
- •Reading XML content with namespaces
- •Searching in XML with GPath
- •Searching in XML with XPath
- •Constructing XML content
- •Modifying XML content
- •Sorting XML nodes
- •Serializing Groovy Beans to XML
- •Introduction
- •Parsing JSON messages with JsonSlurper
- •Constructing JSON messages with JsonBuilder
- •Modifying JSON messages
- •Validating JSON messages
- •Converting JSON message to XML
- •Converting JSON message to Groovy Bean
- •Using JSON to configure your scripts
- •Introduction
- •Creating a database table
- •Connecting to an SQL database
- •Modifying data in an SQL database
- •Calling a stored procedure
- •Reading BLOB/CLOB from a database
- •Building a simple ORM framework
- •Using Groovy to access Redis
- •Using Groovy to access MongoDB
- •Using Groovy to access Apache Cassandra
- •Introduction
- •Downloading content from the Internet
- •Executing an HTTP GET request
- •Executing an HTTP POST request
- •Constructing and modifying complex URLs
- •Issuing a REST request and parsing a response
- •Issuing a SOAP request and parsing a response
- •Consuming RSS and Atom feeds
- •Using basic authentication for web service security
- •Using OAuth for web service security
- •Introduction
- •Querying methods and properties
- •Dynamically extending classes with new methods
- •Overriding methods dynamically
- •Adding performance logging to methods
- •Adding transparent imports to a script
- •DSL for executing commands over SSH
- •DSL for generating reports from logfiles
- •Introduction
- •Processing collections concurrently
- •Downloading files concurrently
- •Splitting a large task into smaller parallel jobs
- •Running tasks in parallel and asynchronously
- •Using actors to build message-based concurrency
- •Using STM to atomically update fields
- •Using dataflow variables for lazy evaluation
- •Index
Working with JSON in Groovy
Using JSON to configure your scripts
The target of this recipe is to show how to use JSON as a format for configuring a
Groovy application.
The requirements for a configuration file format are:
ff
ff
ff
ff
ff
Simple Human-readable Cross-platform Multi-language support Unicode support
JSON fully satisfies the above requirements, thus making a great candidate for configuring an application.
Getting ready
For this recipe, we work on a fictional application that maintains a connection to multiple databases. Each database has a number of parameters to configure such as host, port, credentials, and connection pool initial size.
The following is a sample JSON based configuration file for our application:
{
"configuration":{
"database":[
{
"name":"database1",
"host":"10.20.30.40",
"port":"4930", "user":"user-alpha", "password":"secret", "pool-initial-size":"10", "pool-max-size":"10"
},
{
"name":"database2",
"host":"192.168.10.30",
"port":"5001", "user":"user-beta", "password":"secret", "pool-initial-size":"5",
218
www.it-ebooks.info
Chapter 6
"pool-max-size":"30"
}
]
}
}
It takes very little code (compared to Java) to build a simple configuration handler in Groovy.
How to do it...
Let's start by copying the JSON configuration displayed above to a file named db-config. json. For the sake of conciseness, let's keep all the code in one single Groovy script: create a new file named configurator.groovy.
1.Add the following class to the file: it will hold the configuration data for each database.
import groovy.json.*
import groovy.transform.TupleConstructor
@TupleConstructor class Database {
String name String host Integer port String user String password Integer initPool Integer maxPool
}
This is a terse Groovy Bean (see the Writing less verbose Java Beans with Groovy Beans recipe in Chapter 3, Using Groovy Language Features) with a bunch of attributes which are mapped 1-1 to the configuration data.
2.What follows is the configuration handling class. Copy the code after the Database class definition:
class AppConfig {
def databases = []
AppConfig(conf) { if (conf) {
conf.configuration
.database.each {
databases << new Database( it.name,
219
www.it-ebooks.info
Working with JSON in Groovy
it.host,
it.port.toInteger(),
it.user,
it.password, it.'pool-initial-size'.toInteger(), it.'pool-max-size'.toInteger())
}
}
}
def getDatabaseConfig = { name -> databases.find { it.name == name }
}
}
3.Finally, let's put our class to work by parsing the configuration file and calling the newly defined class:
def reader = new FileReader('db-config.json')
def conf = new JsonSlurper().parse(reader) def dbConfig = new AppConfig(conf)
// Execute application logic
println dbConfig.getDatabaseConfig('database2').host println dbConfig.getDatabaseConfig('database1').user
...
4.Our configurable script will output the following lines in this case:
192.168.10.30 user-alpha
How it works...
The AppConfig class takes java.util.HashMap as constructor parameter, which is the outcome of a parsed JSON payload using JsonSlurper.
For each database found in the data structure, a new Database object is built and added to the list of databases to configure. The Database object doesn't force us to specify the constructor argument name, because the POGO class is annotated with
@TupleConstructor.
The getDatabaseConfig closure elegantly returns the database configuration object that matches the given name of the database to configure.
If found, the database properties are accessible as Groovy Bean getters.
220
www.it-ebooks.info
Chapter 6
There's more...
Another popular format similar to JSON for dealing with the configuration data is YAML.
YAML is a lightweight data serialization format designed with readability in mind and with support for hierarchical data structures. YAML stands for YAML Ain't Markup Language. It is easier on the eyes than JSON and sports a simple typing system.
Additionally, YAML can be considered a superset of JSON. That means, a valid JSON file is also a valid YAML file (but not vice versa).
The ultimate goal of YAML is to be very comfortable on the eyes. The following is an example of YAML formatted data.
firstname: Mike lastname: Ross position: CFO
Groovy doesn't have any native YAML parser. So, the most convenient approach is to use a third-party Java library, such as JYaml.
@Grab('org.jyaml:jyaml:1.3') import org.ho.yaml.Yaml
yamlData = '''
firstname: Mike lastname: Ross position: CFO
''
'
class Staff {
def firstname, lastname, position
}
Staff s = Yaml.loadType(yamlData, Staff)
println s.firstname println s.position
The script will print:
Mike
CFO
This solution doesn't use any Groovy specific feature, but it nevertheless represents a good compromise if YAML is among the requirements of your application.
221
www.it-ebooks.info
Working with JSON in Groovy
Another alternative to configure your scripts is to use Groovy's native ConfigSlurper class, which is capable of consuming configuration data defined in the form of Groovy scripts.
See also
ff Parsing JSON messages with JsonSlurper
ff http://jyaml.sourceforge.net/
ff http://groovy.codehaus.org/gapi/groovy/util/ConfigSlurper.html
222
www.it-ebooks.info