Groovy Declarations
This topic covers some of the key Groovy script declarations.
Comments
Groovy uses C-style code comments.
// This is a one line comment
def a = 1 + 1
/*
This is a multi line
comment block.
*/
def b = 2 + 2
Variables
To declare a variable in Groovy, prefix it with the def
statement.
// Defining a string variable
def a = "Hello world"
The Groovy runtime will attempt to determine what type to use when you define a variable. For example:
def var1 = 'World'
println var1.class.simpleName
def var2 = true
println var2.class.simpleName
def var3 = 1
println var3.class.simpleName
def var4 = 3.1425
println var4.class.simpleName
This will print out:
String
Boolean
Integer
BigDecimal
Strings
Text values are provided using the String class. String values can be created using single or double quotes and contain C-style literals or control characters.
def msg1 = "Hello World"
def msg2 = 'Hello World'
Multi-line text values can be created using triple quotes, for example:
def longMsg = """
Line 1
Line 2
Line 3
"""
println longMsg
note
When splitting up multi-line strings, you can't simply have a line return and then continue on the next line because Groovy interprets each line separately. For example:
// This will NOT work
def longMsg = "abcefchijklmn"
+ "opqrstuvwzyz"
// Groovy actually interprets this as two expressions and adds a semi-colon at the end of each line,
// which leave the second line hanging on its own
def longMsg = "abcefchijklmn";
+ "opqrstuvwzyz"
// You can use parentheses to prevent this as below
def longMsg = ("abcefchijklmn"
+ "opqrstuvwzyz")
String Templating
Groovy also provides a GString
class for doing string templating or interpolation. The GString
class is useful for creating JSON or XML message bodies.
def accountName = ...
def ruleset = ...
def transID = ...
def message = '''
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<SOAP-ENV:Body>
<m:transaction-continue xmlns:m="java:com.verid.carbon.integration.datatypes">
<settings>
<account-name>$accountName</account-name>
<mode>$mode</mode>
<ruleset>$ruleset</ruleset>
<transaction-id>$transID</transaction-id>
</settings>
</m:transaction-continue>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
'''
For larger blocks of formatted text such as HTML email message bodies, we often use Apache Velocity for templating operations. Velocity provides powerful templating capabilities and is useful for keeping large amounts of formatted text out of your code.
In the example below, the message Velocity template is provided as an external service parameter. This value is used to create a Velocity StringTemplate
which is merged with the model map to create the SOAP message.
import com.avoka.core.util.StringTemplate
def model = [:]
model.accountName = ...
model.ruleset = ...
model.transID = ...
def message = new StringTemplate(serviceParameters.messageTemplate).merge(model)
Dates
Date and time values are provided using the Date
class. This class provides convenient methods for formatting date strings and parsing string values into date objects.
The following formatting and parsing patterns use the SimpleDateFormat class.
// Create a new date and print it out
def now = new Date()
println now
// Display value using ISO date format
println now.format("yyyy-MM-dd")
// Display value using ISO8601 date time format
println now.format("yyyy-MM-dd'T'HH:mm:ss")
The script displays the current date and time, so the output changes depending on when the script is execute. The output is formatted like this:
Mon Jul 22 21:26:51 EST 2013
2013-07-22
2013-07-22T21:26:51
note
When calling some Journey Manager Java APIs, you may need to explicitly define java.util.Date
types if the Groovy Runtime does not resolve the API method correctly.
Collections
When working with Groovy scripts, we're often dealing with collections objects. Groovy provides convenient methods for working with collections. For more information about collections, see Working with collections.
Maps and Dictionaries
Maps and dictionaries can be created and accessed using the following syntax.
// Define a new map
def car = [:]
// Set values using dictionary style access
car["seats"] = 6
car["color"] = "blue"
car["year"] = 2013
// Read values using dictionary style access
println car["seats"]
println car["color"]
println car["year"]
// Set value using property style access
car.seats = 6
car.color = "blue"
car.year = 2013
// Read value using property style access
println car.seats
println car.color
println car.year
// Test whether map has an entry accessed using the key "year"
println car.containsKey("year")
// Test whether map has an entry value of 2015
println car.containsValue(2015)
To loop through the entries of a map, use the following syntax.
// Define map and assign values
def car = [ "seats":6, "color":"blue", "year":2013 ]
for (entry in car) {
println entry.key + " : " + entry.value
}
The output from this code is:
seats : 6
color : blue
year : 2013
Under the covers, Groovy uses Java's LinkedHashMap class for maps. This class supports key-based access and insertion-order iteration.
Lists and Arrays
Lists and arrays are collections with a series of elements that can be iterated. The syntax for creating lists is shown below.
// Create a list of fruit
def fruitSalad = [ "banana", "apple", "orange", "mango", "grapes", "kiwi fruit" ]
println "ingredients: " + fruitSalad
println "number of items: " + fruitSalad.size
for (item in fruitSalad) {
println "\t" + item
}
// Modify list
fruitSalad[0] = "passion fruit"
fruitSalad.remove("apple")
fruitSalad.add("stawberry")
println "ingredients: " + fruitSalad
// Test whether the list contains a "apple" value
println fruitSalad.contains("apple")
The output of this script is shown below:
ingredients: [banana, apple, orange, mango, grapes, kiwi fruit]
number of items: 6
banana
apple
orange
mango
grapes
kiwi fruit
ingredients: [passion fruit, orange, mango, grapes, kiwi fruit, stawberry]
false
Under the covers, Groovy uses Java's ArrayList class for lists. This class supports very fast access and array additions.