Skip to main content

Groovy Basics

How To

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: Groovy. An overview of the differences between Groovy and Java can be found here: Differences with Java.

The following section provides a quick overview of Groovy snippets and constructs that can come in handy in scripts in Teneo.

To print something to the Engine Output panel in Tryout (and the console.log) use:

println "Hello world!"

As you can see, semi-colons are not needed to end statements in Groovy.

Variables

In Groovy you can use dynamic typing. You use the keyword def to define a variable.

def x = true
println x.getClass()

x = 42
println x.getClass()

x = "Hello World"
println x.getClass()

Results:

class java.lang.Boolean
class java.lang.Integer
class java.lang.String

Strings

When using single quotes, you will use a standard Java String:

def name = 'Dave'
println 'Hello, ' + name + '. You\'re looking well today.'

When using double quotes, you can use interpolation:

def name = "Dave"
println "Hello, ${name}. You're looking well today."

Substrings

Use the following syntax to get a substring:

def text = "Hunky dory!"
def name = text[0..4]
println name

Result:

Hunky

Other example:

def text = "Hunky dory!"
def name = text[-5..-2]
println name

Result:

dory

Groovy Classes

Sometimes you may want to add a Groovyclass to your solution, which you can then call in your Integrations or Scripts.

Add a Class via a .groovy file

One way of adding the class to the solution is to save it as a text file with the name of the class and the extension .groovy. This file is then uploaded to the Resource file manager to make it available in the solution.

First, save the following code in a text file called TeneoTextUtils.groovy

public class TeneoTextUtils {
/**
* Takes a String input, and returns it with the the first letter of
* each word capitalized and all other letters lower case
*/
public static String capitalizeFirstLetters(String input) {
input.toLowerCase().tokenize().collect { it.capitalize() }.join(' ')
}

}

Next, add the file to your solution and set the path to /script_lib (If you need guidance on how to add the file to the solution, please check Add files to your solution).

Now the class 'TeneoTextUtils' can be used in your Scripts and Integrations.

Add a Class to a Global Script

The other way of adding a class is by adding it to the global script On Solution loaded. This script is compiled and loaded each time a solution is loaded into memory, which happens when you publish your solution, for example.

To add it, proceed as follows:

  1. Click on the 'Solutions' tab.

  2. Select 'Globals' on the left.

  3. Select the 'Scripts' tab.

  4. Add a new 'Solution Loaded' script.

  5. Paste the following groovy class into the editing window:

    public class TeneoTextUtils {
    /**
    * Takes a String input, and returns it with the the first letter of
    * each word capitalized and all other letters lower case
    */
    public static String capitalizeFirstLetters(String input) {
    input.toLowerCase().tokenize().collect { it.capitalize() }.join(' ')
    }

    }
    1. Name the script Capitalize first letters.

    2. Hit 'Save'.

    The class 'TeneoTextUtils' can now be used in your scripts and integrations.

The Groovy Truth

Groovy evaluates every object to a Boolean value if required (also know as the Implicit Truth):

if ("hunky dory") ...
if (42) ...
if (someObject) ...
  • 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:

if (order.getContact() != null && order.getContact().getAddress() != null) { 
System.out.println(order.getContact().getAddress());
}

In Groovy:

println  order?.getContact()?.getAddress()

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:

displayName = user.name ? user.name : 'Anonymous' 

Using the Elvis operator in Groovy:

displayName = user.name ?: 'Anonymous'

(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:

def list = [1,2,2,4,5]

Accessing elements in the list:

println list[0] // will print out 1 
println list[-1] // use negative indexes for access from the end of the list, will print 5

Iterating lists:

list.each {
println it
}

or

list.each { myNumber ->
println myNumber
}

With index:

list.eachWithIndex { myNumber,  index ->
println "$index, $myNumber"
}

Will print:

0, 1
1, 2
2, 2
3, 4
4, 5

Quick way of adding something to a list:

list << 6 // list will become [1,2,2,4,5,6]

Maps

Creating a map:

def map = ['key1':'value 1', 'key2':'value 2', 'key3':'value 3']

Other options:

def key = 'key3'
def map = [
'key1': 'value 1',
key2: 'value 2', // skip the quotes, the key will automatically be a String
(key): 'value 3' // put the key in parentheses if you want to use the value of a variable
]

Accessing the map:

println map['key1']
println map.key1
println map[key] // access the entry with the value of key variable
println map.get(key) // using the get method with a key variable

Iterating maps:

map.each {
println it.key
println it.value
}

or:

map.each { key, value ->
println key
println value
}

Adding something to a map:

map << ['key4':'value 4']

For more information on lists and maps in Groovy: Working with collections

JSON

Parsing JSON

def jsonSlurper = new groovy.json.JsonSlurper()
def object = jsonSlurper.parseText('{"name": "Dave Bowman", "age": 32 }')

Producing JSON

Using JsonOutput:

def json = new groovy.json.JsonOutput().toJson([name: 'Dave Bowman', age: 32])

// indent nicely
def pretty = new groovy.json.JsonOutput().prettyPrint(json)

Using JsonBuilder:

def actionBuilder = new groovy.json.JsonBuilder()

actionBuilder {
name "displayCard"
parameters {
type 'basic'
title 'Cappuccino'
image 'https://some.url/for/image/cappuccino.png'
description 'Try our cappuccino! We love it for its remarkable body of fruit and mocha and its subtle sweet finish.'
}
}
def json = actionBuilder.toString()

// indent nicely
def pretty = groovy.json.JsonOutput.prettyPrint(json)

println pretty

Result:

{
"name": "displayCard",
"parameters": {
"type": "basic",
"title": "Cappuccino",
"image": "https://some.url/for/image/cappuccino.png",
"description": "Try our cappuccino! We love it for its remarkable body of fruit and mocha and its subtle sweet finish."
}
}

More on Groovy's way of handling JSON here: Parsing and producing JSON

Reading URL content

Getting a URL

def baseUrl = 'https://some/url/'
def text = baseUrl.toURL().text

Getting a URL and parsing the JSON response

def baseUrl = 'https://some/url/'
def result = new groovy.json.JsonSlurper().parseText(baseUrl.toURL().text)

Setting a time out on requests

def baseUrl = 'https://some/url/'
def result = new groovy.json.JsonSlurper().parseText(baseUrl.toURL().getText([connectTimeout: 2000, readTimeout: 2000]))