Basic Examples of Groovy
1) Usage of Strings
String
usage in Groovy is similar to many programming languages, but Groovy has some unique features. Here are the basic details regarding String usage:
String s1 = 'A string defined with single quotes'
String s2 = "A string defined with double quotes"
String s3 = '''A multi-line
string
defined with
triple quotes'''
In Groovy, with strings defined using double quotes, you can directly embed variable values. This feature is called "String interpolation" or "GString."
String name = "John"
String hello = "Hello, ${ad}!"
println(hello) // Output: Hello, John!
2) Differences in the Usage of Single, Double, and Triple Quotes in Strings
In Groovy, single quotes ('), double quotes ("), and triple quotes (''' or """) can be used to define String
. The differences in the use of these quotes are as follows:
Single Quotes(' '):
- Strings defined with single quotes are plain strings.
- String interpolation (variable embedding) cannot be done within single-quoted strings.
String s1 = 'Hello, ${name}!' println(s1) // Output: Hello, ${name}!
GROOVY
- Strings defined with single quotes are plain strings.
- String interpolation (variable embedding) cannot be done within single-quoted strings.
String s1 = 'Hello, ${name}!' println(s1) // Output: Hello, ${name}!
GROOVY
Double Quotes("):
- Strings defined with double quotes are known as "GString" in Groovy.
- String interpolation (variable embedding) can be done within double-quoted strings.
String name = "John" String s2 = "Hello, ${name}!" println(s2) // Output: Hello, John!
GROOVY
Triple Quotes('''):
- Triple quotes are used to define multi-line strings.
- String interpolation can be done within triple-quoted strings.
String name = "John" String s3 = '''Hello, ${name}! How are you?''' println(s3) // Output: // Hello, // John! // How are you?
GROOVY
3) Checking if a String is Empty in Groovy
In Groovy, the isEmpty()
method can be used to check if a string is empty.
String s = ""
if(s.isEmpty()) {
println("The string is empty!")
} else {
println("The string is not empty!")
}
4) Checking if an Object is Empty in Groovy
In Groovy, to check if an object is empty, you can use the expressions == null
or != null
.
def obj = null
if(obj) {
println("The object is not empty!")
} else {
println("The object is empty!")
}
Output: "The object is empty!"
5) For Loop in Groovy
A for
loop in Groovy is written similar to Java. Here's a basic example:
def sum = 0
for(int i = 0; i < 10; i++) {
sum +=i
responseBodyTextToClient = "sum: ${sum}"
}
//Output: "sum: 45"
6) While Loop in Groovy
while
loop in Groovy is used similarly to other programming languages. Here's a basic example:
int num = 0
while(num < 10) {
num++
}
responseBodyTextToClient = num
//Output: "10"
7) Defining a Function (Method) in Groovy
In Groovy, functions are commonly referred to as "methods" and are typically defined similar to Java. However, Groovy provides a more flexible syntax.
def functionName(parameter1, parameter2, ...) {
// Function body
return result
}
def add(a, b) {
return a + b
}
// After defining the function, you can use it by calling it with its name.
def result= add(5, 3)
responseBodyTextToClient = result// Output: 8
8) Try-Catch Usage in Groovy
The try-catch
structure in Groovy is used, like in Java, for catching and handling errors (exceptions). The syntax and usage are very similar to Java.
try {
// Code that may generate an error
int result = 10 / 0 // This line will throw an ArithmeticException.
} catch (ArithmeticException e) {
responseBodyTextToClient = "An arithmetic error occurred: " + e.getMessage()
} catch (Exception e) {
responseBodyTextToClient = "An error occurred: " + e.getMessage()
}
// Output: "An arithmetic error occurred: divide by zero"
9) Concatenation in Groovy
String concatenation in Groovy can be achieved through several methods. Here are some examples of these methods:
1. Concatenation with the Basic+ Operator:
String name = "John"
String message = "Hello, " + name + "!"
2. Usage of GString (Parameter String) :
Groovy supports GString, a string type that can directly embed values using the ${...}
syntax for concatenation.
String name = "John"
String message = "Hello, ${name}!"
println(message) // Output : Hello, John!
3. Concatenation with <<
Operator:
This method is more performant for string concatenation operations on large data sets.
def sb = new StringBuilder()
sb << "Hello, "
sb << "John"
sb << "!"
println(sb.toString()) // Output: Hello, John!
4. join()
Method:
It is used to combine elements in lists.
def words = ["Hello", "John"]
String message = words.join(", ") + "!"
println(message) // Output: Hello, John!
10) Escaping Special Characters in Strings in Groovy
def message = 'Hello, \'John\'. How are you today?'
println(message) // Output: Hello, 'John'. How are you today?
11) Usage of Apache StringUtils in Groovy
You can use the import
keyword to use Java libraries in Groovy.
// Importing the StringUtils class
import org.apache.commons.lang3.StringUtils
// Simple Groovy script
def mainString = "Hello, Groovy!"
def searchString = "Groovy"
// Checking if one string is contained within another using StringUtils
if (StringUtils.contains(mainString, searchString)) {
responseBodyTextToClient = "$searchString is found in $mainString"
} else {
responseBodyTextToClient = "$searchString is not found in $mainString"
}
12) Base64 Encoding and Decoding with Apache Commons Codec in Java
You can perform Base64 encoding and decoding operations in Java using the Apache Commons Codec library. This library provides the Base64
class for Base64 operations.
// Importing the Base64 class
import org.apache.commons.codec.binary.Base64;
// Defining the original string
String originalString = "Hello, Groovy!";
// Encoding the string with Base64
byte[] encodedBytes = Base64.encodeBase64(originalString.getBytes());
String encodedString = new String(encodedBytes);
// Decoding the Base64 encoded string
byte[] decodedBytes = Base64.decodeBase64(encodedString.getBytes());
String decodedString = new String(decodedBytes);
// Creating the response text for the client
responseBodyTextToClient = "Original String: " + originalString + ' ' + "Base64 Encoded String: " + encodedString + ' ' + "Decoded String: " + decodedString;
// Output: "Original String: Hello, Groovy! Base64 Encoded String: TWVyaGFiYSwgR3Jvb3Z5IQ== Decoded String: Hello, Groovy!"
13) Usage of the XmlUtil Class with Java Import in Groovy
Groovy is a powerful language for XML processing, providing numerous built-in features that facilitate tasks such as reading, creating, and editing XML content. The XmlUtil
class is used for printing XML content in a structured (pretty-print) manner.
// Importing the XmlUtil class
import groovy.xml.XmlUtil
def xmlContent = '''
<root>
<element1>Value1</element1>
<element2>Value2</element2>
</root>
'''
def parsedXml = new XmlParser().parseText(xmlContent)
String prettyXml = XmlUtil.serialize(parsedXml)
responseBodyTextToClient = prettyXml
/*
<?xml version="1.0" encoding="UTF-8"?>
<root>
<element1>Value1</element1>
<element2>Value2</element2>
</root>
*/
14) Reading Data from XML in Groovy
Groovy provides a powerful and flexible language for reading XML content. In Groovy, you typically use the XmlSlurper
or XmlParser
classes to read XML content.
import groovy.xml.XmlSlurper
def xmlContent = '''
<root>
<person>
<name>John Doe</name>
<age>30</age>
</person>
<person>
<name>Jane Smith</name>
<age>25</age>
</person>
</root>
'''
def xml = new XmlSlurper().parseText(xmlContent)
// Reading the name of the first person
def firstName = xml.person[0].name.text()
println "First person's name: $firstName"
// Reading the age of the second person
def secondPersonAge = xml.person[1].age.text()
responseBodyTextToClient = "Second person's age: $secondPersonAge"
15) Adding an Element to XML in Groovy
Groovy provides useful tools for adding a new element to XML content. For this task, you typically use the XmlParser
or XmlSlurper
classes.
import groovy.xml.XmlParser
import groovy.xml.XmlUtil
// Sample XML content
def xmlContent = '''
<root>
<person>
<name>John Doe</name>
<age>30</age>
</person>
</root>
'''
def parsedXML = new XmlParser().parseText(xmlContent)
// Adding a new 'address' element to the 'person' element
parsedXML.person.appendNode('address', '123 Main St')
// Writing the XML content
def prettyXml = XmlUtil.serialize(parsedXML)
responseBodyTextToClient = prettyXml
16) Deleting an Element in XML in Groovy
Certainly, in Groovy, you can use the XmlParser
or XmlSlurper
classes to delete an element from XML content.
import groovy.xml.XmlParser
import groovy.xml.XmlUtil
// Sample XML content
def xmlContent = '''
<root>
<person>
<name>John Doe</name>
<age>30</age>
<address>123 Main St</address>
</person>
</root>
'''
def parsedXML = new XmlParser().parseText(xmlContent)
// Finding and deleting the 'address' element under the 'person' element
parsedXML.person.address[0].replaceNode {}
// Printing the XML content in a structured manner
def prettyXml = XmlUtil.serialize(parsedXML)
responseBodyTextToClient = prettyXml
17) Editing an Element in XML in Groovy
To edit an element in XML content in Groovy, you can use the XmlParser
or XmlSlurper
classes.
import groovy.xml.XmlParser
import groovy.xml.XmlUtil
// Sample XML content
def xmlContent = '''
<root>
<person>
<name>John Doe</name>
<age>30</age>
<address>123 Main St</address>
</person>
</root>
'''
def parsedXML = new XmlParser().parseText(xmlContent)
// Changing the value of the 'address' element under the 'person' element
parsedXML.person.address[0].value = '456 Elm St'
// Printing the XML content in a structured manner
def prettyXml = XmlUtil.serialize(parsedXML)
responseBodyTextToClient = prettyXml
18) Iterating through XML using a loop in Groovy
To edit an element in XML content in Groovy, you can use the XmlParser
or XmlSlurper
classes.
import groovy.xml.XmlParser
// Sample XML content
def xmlContent = '''
<root>
<people>
<person>
<name>John Doe</name>
<age>30</age>
</person>
<person>
<name>Jane Smith</name>
<age>25</age>
</person>
<person>
<name>Bob Johnson</name>
<age>40</age>
</person>
</people>
</root>
'''
def parsedXML = new XmlParser().parseText(xmlContent)
// We are collecting 'person' elements under 'people' into an array. def personsList = []
for (person in parsedXML.people.person) {
def personMap = [
name: person.name.text(),
age: person.age.text().toInteger()
]
personsList << personMap
}
// Result
responseBodyTextToClient = personsList
/* Output:
[
[name: "John Doe", age: 30],
[name: "Jane Smith", age: 25],
[name: "Bob Johnson", age: 40]
]
*/
19) Reading Value from JSON Content in Groovy
Groovy is a very powerful language for JSON operations and has many built-in features that make it easy to read, create and edit JSON content. The JsonSlurper
class is used to parse and read JSON content.
import groovy.json.JsonSlurper
// Sample JSON content
def jsonString = '''
{
"name": "John Doe",
"age": 30,
"address": {
"street": "123 Main St",
"city": "Springfield"
}
}
'''
def json = new JsonSlurper().parseText(jsonString)
// Reading values from JSON content
def name = json.name
def age = json.age
def street = json.address.street
responseBodyTextToClient = "Name: $name Age: $age Street: $street"
//Output: "Name: John Doe Age: 30 Street: 123 Main St"
20) Creating JSON Content in Groovy
Groovy offers built-in classes like JsonBuilder
and JsonOutput
to easily create and edit JSON data. These classes are very useful for creating data in JSON format.
import groovy.json.JsonBuilder
import groovy.json.JsonOutput
// Json content to be generated
def nameValue = "John"
def surnameValue = "Doe"
def builder = new JsonBuilder()
// Block defining the JSON structure
def jsonRequestBodyExample = builder {
name nameValue
surname surnameValue
}
// Convert a JSON object to a string in JSON format
responseBodyTextToClient = JsonOutput.toJson(jsonRequestBodyExample)
/*
{
"name" : "John",
"surname" : "Doe",
}
*/
21) Adding Elements to JSON Content in Groovy
Groovy offers built-in classes for JSON operations, such as JsonSlurper
and JsonBuilder
. Thanks to these classes, you can easily parse JSON content, edit it and add new elements.
import groovy.json.JsonSlurper
import groovy.json.JsonBuilder
// Sample JSON content
def jsonString = '''
{
"name": "John Doe",
"age": 30
}
'''
def json = new JsonSlurper().parseText(jsonString)
// Adding a new element to the JSON content
json.address = "123 Main St"
// Converting JSON content back to string format
def updatedJsonString = new JsonBuilder(json).toPrettyString()
responseBodyTextToClient = updatedJsonString
/* Output:
{
"name" : "John Doe",
"age" : 30,
"address" : "123 Main St"
}
*/
22) Deleting Elements from JSON Content in Groovy
Groovy offers built-in classes for JSON operations, such as JsonSlurper
and JsonBuilder
. These classes are very useful for easily parsing JSON content, editing and deleting elements.
import groovy.json.JsonSlurper
import groovy.json.JsonBuilder
// Sample JSON content
def jsonString = '''
{
"name": "John Doe",
"age": 30,
"address": "123 Main St"
}
'''
def json = new JsonSlurper().parseText(jsonString)
// Deleting the 'address' element from the JSON content
json.remove('address')
// Converting JSON content back to string format
def updatedJsonString = new JsonBuilder(json).toPrettyString()
responseBodyTextToClient = updatedJsonString
/* Output:
{
"name" : "John Doe",
"age" : 30
}
*/
23) Editing Element in JSON Content in Groovy
Groovy offers built-in classes for JSON operations, such as JsonSlurper
and JsonBuilder
. These classes are very useful for easily parsing JSON content, editing it and changing the values of elements.
import groovy.json.JsonSlurper
import groovy.json.JsonBuilder
// Sample JSON content
def jsonString = '''
{
"name": "John Doe",
"age": 30,
"address": "123 Main St"
}
'''
def json = new JsonSlurper().parseText(jsonString)
// Changing the value of the 'address' element in the JSON content
json.address = "456 Elm St"
// Converting JSON content back to string format
def updatedJsonString = new JsonBuilder(json).toPrettyString()
responseBodyTextToClient = updatedJsonString
/* Output:
{
"name" : "John Doe",
"age" : 30,
"address": "456 Elm St"
}
*/
24) Navigating a JSON Array with For in Groovy
Groovy offers built-in classes for JSON operations, such as JsonSlurper
and JsonBuilder
. These classes are very useful to easily parse JSON content, edit it and change the values of elements.
import groovy.json.JsonSlurper
// Sample JSON content
def jsonString = '''
{
"people": [
{"name": "John Doe", "age": 30},
{"name": "Jane Smith", "age": 25},
{"name": "Bob Johnson", "age": 40}
]
}
'''
def json = new JsonSlurper().parseText(jsonString)
// Navigating the 'people' array in JSON content with a for loop
def personsList = []
for (person in json.people) {
def personMap = [
name: person.name,
age: person.age
]
personsList << personMap
}
responseBodyTextToClient = personsList
/* Output:
[{name=John Doe, age=30}, {name=Jane Smith, age=25}, {name=Bob Johnson, age=40}]
*/
25) Apinizer Variables
With the script policy, the header, parameter, body and error message contents of the messages can be processed with the selected script language.
The original version of the incoming request message and the original version of the returned response message cannot be changed; only reading can be done on these data.
The request sent to the Backend API and the response returned to the client can be both read and modified.
The reading and modification operations to be performed include the header, parameter and body parts of the message. Various keywords were used to access these fields on the script. These keywords vary depending on the region you want to reach.
- To access titles → <request|response>HeaderMap<From|To><Client|TargetAPI>
- To access URL parameters → <request>UrlParamMap<From|To><Client|TargetAPI>
- To access the body → <request|response>BodyText<From|To><Client|TargetAPI>
- To terminate the policy and return a customized error message → <request|response>ErrorMessage<From|To><Client|TargetAPI> you must use this notation.
- To change the status code → statusCode<From|To><Client|TargetAPI>
/* Request
{
"data": {
"field": "1"
}
}
*/
//Script
import groovy.json.JsonSlurper
def jsonSlurper = new JsonSlurper()
def jsonMessage = jsonSlurper.parseText(requestBodyTextFromClient)
requestErrorMessageToTargetAPI = jsonMessages
statusCodeToTargetAPI = 500
//Result:
//It is returned to the client as {data={field=1}}
//In the script, the requestHeaderMapFromClient variable holds the Headers coming from the Client as a Map. The variable can be used as Read only.
/* Request Header
userId : 123456
*/
//Script
def userID = requestHeaderMapFromClient.get('userId')
if(userID =='123456'){
requestErrorMessageToTargetAPI = userID
statusCodeToTargetAPI = 401
}
//Output:
// 123456 - statusCode = 401