Groovy Basics
Scripts in Teneo are written in Groovy or Java code. Apache Groovy is similar to Java but with an easier to learn syntax. More details on Groovy can be found here: http://groovy-lang.org. An overview of the differences between Groovy and Java can be found here: Differences with Java.
This page will provide a quick overview of Groovy snippets and constructs that can come in handy in scripts in Teneo.
Print a line
To print something to the Engine Ouput panel in tryout (and the console.log) use:
groovy
1println "Hello world!"
2
As you can see you don't need semi-colons to end statements in Groovy.
Variables
In Groovy you can use dynamic typing. You use the keyword def to define a variable.
groovy
1def x = true
2println x.getClass()
3
4x = 42
5println x.getClass()
6
7x = "Hello World"
8println x.getClass()
9
Results:
groovy
1class java.lang.Boolean
2class java.lang.Integer
3class java.lang.String
4
Strings
When using single quotes, you will use a standard Java String:
groovy
1def name = 'Dave'
2println 'Hello, ' + name + '. You\'re looking well today.'
3
When using double quotes, you can use interpolation:
groovy
1def name = "Dave"
2println "Hello, ${name}. You're looking well today."
3
Substrings
groovy
1def text = "Hunky dory!"
2def name = text[0..4]
3println name
4
Result:
groovy
1Hunky
2
Other example:
groovy
1def text = "Hunky dory!"
2def name = text[-5..-2]
3println name
4
Result:
groovy
1dory
2
The Groovy Truth
Groovy evaluates every object to a boolean value if required (also know as the Implicit Truth):
groovy
1if ("hunky dory") ...
2if (42) ...
3if (someObject) ...
4
- Strings: If empty false, otherwise true
- Collections and Maps: true if they are not empty
- Numbers: true if non-zero
- Object references: true if they aren't null
For more details: Groovy Truth
Operators
Safe Navigation Operator
The Safe Navigation operator is used to avoid a NullPointerException. Typically when you have a reference to an object you might need to verify that it is not null before accessing methods or properties of the object. In Java it would look something like this:
java
1if (order.getContact() != null && order.getContact().getAddress() != null) {
2 System.out.println(order.getContact().getAddress());
3}
4
In Groovy:
groovy
1println order?.getContact()?.getAddress()
2
Elvis Operator
The "Elvis operator" is a shortening of the ternary operator, often used to assign default values. In Java you would use them like this:
groovy
1displayName = user.name ? user.name : 'Anonymous'
2
Using the Elvis operator in Groovy:
groovy
1displayName = user.name ?: 'Anonymous'
2
(If you are wondering why it is called the Elvis operator, turn your head sideways and look at the smiley's hair.)
More on operators in the Groovy docs: Operators
Collections
Lists
Creating a list:
groovy
1def list = [1,2,2,4,5]
2
Accessing elements in the list:
groovy
1println list[0] // will print out 1
2println list[-1] // use negative indexes for access from the end of the list, will print 5
3
Iterating lists:
groovy
1list.each {
2 println it
3}
4
or
groovy
1list.each { myNumber ->
2 println myNumber
3}
4
With index:
groovy
1list.eachWithIndex { myNumber, index ->
2 println "$index, $myNumber"
3}
4
Will print:
groovy
10, 1
21, 2
32, 2
43, 4
54, 5
6
Quick way of adding something to a list:
groovy
1list << 6 // list will become [1,2,2,4,5,6]
2
Maps
Creating a map:
groovy
1def map = ['key1':'value 1', 'key2':'value 2', 'key3':'value 3']
2
Other options:
groovy
1def key = 'key3'
2def map = [
3 'key1': 'value 1',
4 key2: 'value 2', // skip the quotes, the key will automatically be a String
5 (key): 'value 3' // put the key in parentheses if you want to use the value of a variable
6]
7
Accessing the map:
groovy
1println map['key1']
2println map.key1
3println map[key] // access the entry with the value of key variable
4println map.get(key) // using the get method with a key variable
5
Iterating maps:
groovy
1map.each {
2 println it.key
3 println it.value
4}
5
or:
groovy
1map.each { key, value ->
2 println key
3 println value
4}
5
Adding something to a map:
groovy
1map << ['key4':'value 4']
2
For more information on lists and maps in Groovy: Working with collections
JSON
Groovy's handling of JSON is very powerful.
Parsing JSON
groovy
1def jsonSlurper = new groovy.json.JsonSlurper()
2def object = jsonSlurper.parseText('{"name": "Dave Bowman", "age": 32 }')
3
Producing JSON
Using JsonOuput:
groovy
1def json = new groovy.json.JsonOutput().toJson([name: 'Dave Bowman', age: 32])
2
3// indent nicely
4def pretty = new groovy.json.JsonOutput().prettyPrint(json)
5
Using JsonBuilder:
groovy
1def actionBuilder = new groovy.json.JsonBuilder()
2
3actionBuilder {
4 name "displayCard"
5 parameters {
6 type 'basic'
7 title 'Cappuccino'
8 image 'https://some.url/for/image/cappuccino.png'
9 description 'Try our cappuccino! We love it for its remarkable body of fruit and mocha and its subtle sweet finish.'
10 }
11}
12def json = actionBuilder.toString()
13
14// indent nicely
15def pretty = groovy.json.JsonOutput.prettyPrint(json)
16
17println pretty
18
Result:
groovy
1{
2 "name": "displayCard",
3 "parameters": {
4 "type": "basic",
5 "title": "Cappuccino",
6 "image": "https://some.url/for/image/cappuccino.png",
7 "description": "Try our cappuccino! We love it for its remarkable body of fruit and mocha and its subtle sweet finish."
8 }
9}
10
More on Groovy's way of handling JSON here: Parsing and producing JSON
Reading URL content
Getting a URL
groovy
1def baseUrl = 'https://some/url/'
2def text = baseUrl.toURL().text
3
Getting a URL and parsing the JSON response
groovy
1def baseUrl = 'https://some/url/'
2def result = new groovy.json.JsonSlurper().parseText(baseUrl.toURL().text)
3
Setting a time out on requests
groovy
1def baseUrl = 'https://some/url/'
2def result = new groovy.json.JsonSlurper().parseText(baseUrl.toURL().getText([connectTimeout: 2000, readTimeout: 2000]))
3
If it takes a long time for Teneo to respond and you see an error like this in Tryout: Script action execution failed: Maximum execution time exceeded, but forced script termination failed, the cause is often a call to an online API that is slow or doesn't respond. Setting a timeout will prevent this error. However, you will still need to make sure that your script or flow gracefully handles the fact that it did not receive a response in time.