Skip to main content

1) String Usage

String usage in Groovy is similar to many programming languages, but Groovy has some unique features. Here are the basics of String usage:
String s1 = 'Single-quoted string'
String s2 = "Double-quoted string"
String s3 = '''Triple-quoted 
multi-line 
string'''
In Groovy, you can directly add variable values in double-quoted strings. This feature is called “String interpolation” or “GString”.
String ad = "Ali"
String selam = "Merhaba, ${ad}!"
println(selam) // Output: Merhaba, Ali!

2) Differences Between Single, Double, and Triple Quote Usage in Strings

In Groovy, you can use single quote ('), double quote ("), and triple quote (''' or """) to define String. The differences in their usage are: Single Quote (’ ’):
  • Single-quoted strings are plain strings.
  • String interpolation (variable insertion) cannot be done within them.
String s1 = 'Merhaba, ${isim}!'
println(s1) // Output: Merhaba, ${isim}!
Double Quote (”):
  • Double-quoted strings are known as “GString”.
  • String interpolation (variable insertion) can be done within them.
String isim = "Ali"
String s2 = "Merhaba, ${isim}!"
println(s2) // Output: Merhaba, Ali!
Triple Quote('''):
  • Used to define multi-line strings.
  • String interpolation can be done within them.
String isim = "Ali"
String s3 = '''Merhaba,  
${isim}!  
Nasılsın?'''
println(s3)
// Output:  
// Merhaba,  
// Ali!  
// Nasılsın?

3) Checking if String is Empty in Groovy

In Groovy, you can use the isEmpty() method to check if a string is empty.
String s = ""
if(s.isEmpty()) {
    println("String is empty!")
} else {
    println("String is not empty!")
}

4) Checking if Object is Empty in Groovy

In Groovy, you can use == null or != null expressions to check if an object is empty.
def obj = null
if(obj) {
    println("Object is not empty!")
} else {
    println("Object is empty!")
}
Output: "Object is empty!" 

5) For Loop in Groovy

A for loop in Groovy is written as in Java. A basic example:
def toplam = 0
for(int i = 0; i < 10; i++) {
   toplam +=i
   responseBodyTextToClient = "toplam: ${toplam}"
}

//Output : "toplam: 45"

6) While Loop in Groovy

The while loop in Groovy is used as in other programming languages. Here is a basic example:
int sayi = 0
while(sayi < 10) {
    sayi++
    
}
responseBodyTextToClient = sayi

//Output:  "10"

7) Function (Method) Definition in Groovy

In Groovy, functions are usually called “methods” and are defined similar to Java. However, Groovy offers a more flexible syntax.
def fonksiyonAdi(parametre1, parametre2, ...) {
    // Function content
    return sonuc
}
def topla(a, b) {
    return a + b
}


//After defining the function, you can call it by name to use it.

def sonuc = topla(5, 3)
responseBodyTextToClient =sonuc  // Output: 8

8) Try-Catch Usage in Groovy

The try-catch structure in Groovy is used for catching and handling exceptions, similar to Java. The syntax and usage are very similar to Java.
try {
    // Code that may cause errors
    int sonuc = 10 / 0  // This line will produce an ArithmeticException error.
} 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

There are several methods for string concatenation (concatenation) in Groovy. Here are some examples of these methods:

1. Simple Concatenation with + Operator:

String ad = "Ali"
String mesaj = "Merhaba, " + ad + "!"

2. GString (Parameterized String) Usage:

Groovy supports GString, a string type that can use the ${...} structure to directly add values into strings.
String ad = "Ali"
String mesaj = "Merhaba, ${ad}!"
println(mesaj) // Output: Merhaba, Ali!

3. Concatenation with << Operator:

This method is more performant for string concatenation operations on large data sets.
def sb = new StringBuilder()
sb << "Merhaba, "
sb << "Ali"
sb << "!"
println(sb.toString()) // Output: Merhaba, Ali!

4. join() Method:

Used to join elements in lists.
def kelimeler = ["Merhaba", "Ali"]
String mesaj = kelimeler.join(", ") + "!"
println(mesaj) // Output: Merhaba, Ali!

10) Escaping Special Characters in Strings in Groovy

def mesaj = 'Merhaba, \'Ali\'. Bugün nasılsın?'
println(mesaj) // Output: Merhaba, 'Ali'. Bugün nasılsın?

11) Using Apache StringUtils in Groovy

In Groovy, you can use the import keyword to use Java libraries.
// Import StringUtils class
import org.apache.commons.lang3.StringUtils

// Simple Groovy script
def mainString = "Hello, Groovy!"
def searchString = "Groovy"

// Check if a string contains another string 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 using the Apache Commons Codec library in Java. This library provides the Base64 class for Base64 operations.
// Import Base64 class
import org.apache.commons.codec.binary.Base64

def originalString = "Merhaba, Groovy!"

// Encode string with Base64
byte[] encodedBytes = Base64.encodeBase64(originalString.getBytes())
String encodedString = new String(encodedBytes)

// Decode Base64 encoded string
byte[] decodedBytes = Base64.decodeBase64(encodedString.getBytes())
String decodedString = new String(decodedBytes)

responseBodyTextToClient = "Original String: $originalString" + ' ' +"Base64 Encoded String: $encodedString"+ ' ' +"Base64 Decoded String: $decodedString"

//Output : "Original String: Merhaba, Groovy! Base64 Encoded String: TWVyaGFiYSwgR3Jvb3Z5IQ== Base64 Decoded String: Merhaba, Groovy!"

13) Using XmlUtil Class with Java Import in Groovy

Groovy is a very powerful language for XML operations and has many built-in features that facilitate operations such as reading, creating, and editing XML content. The XmlUtil class is used to write XML content in a formatted way (pretty-print).
// Import 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 offers a very powerful and flexible language for reading XML content. You can generally use XmlSlurper or XmlParser classes to read XML content in Groovy.
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)

// Read first person's name
def firstName = xml.person[0].name.text()
println("First person's name: $firstName")

// Read second person's age
def secondPersonAge = xml.person[1].age.text()
responseBodyTextToClient = "Second person's age: ${secondPersonAge}"

15) Adding Element to XML in Groovy

Groovy offers very useful tools for adding a new element to XML content. You can generally use XmlParser or XmlSlurper classes for this operation.
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)

// Add a new 'address' element to 'person' element
parsedXML.person.appendNode('address', '123 Main St')

// Write XML content in formatted way
def prettyXml = XmlUtil.serialize(parsedXML)
responseBodyTextToClient = prettyXml

16) Deleting Element from XML in Groovy

Of course, you can use XmlParser or XmlSlurper classes in Groovy 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)

// Find and delete 'address' element under 'person' element
parsedXML.person.address[0].replaceNode {}

// Write XML content in formatted way
def prettyXml = XmlUtil.serialize(parsedXML)
responseBodyTextToClient = prettyXml

17) Editing Element in XML in Groovy

You can use XmlParser or XmlSlurper classes in Groovy to edit an element in 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)

// Change value of 'address' element under 'person' element
parsedXML.person.address[0].value = '456 Elm St'

// Write XML content in formatted way
def prettyXml = XmlUtil.serialize(parsedXML)
responseBodyTextToClient = prettyXml

18) Navigating XML with For in Groovy

You can use XmlParser or XmlSlurper classes in Groovy to edit an element in XML content.
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)

// Get 'person' elements under 'people' into an array
def personsList = []
for (person in parsedXML.people.person) {
    def personMap = [
        name: person.name,
        age: person.age
    ]
    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 facilitate operations such as reading, creating, and editing 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)

// Read 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 provides built-in classes such as 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

// Content to create JSON
def nameValue = "John"
def surnameValue = "Doe"

def builder = new JsonBuilder()

// Block where JSON structure is defined
def jsonRequestBodyExample = builder {
    name nameValue
    surname surnameValue
}

// Convert JSON object to JSON format string
responseBodyTextToClient = JsonOutput.toJson(jsonRequestBodyExample)

/* Output: 

{
    "name" : "John",
    "surname" : "Doe",
}

*/

21) Adding Element to JSON Content in Groovy

Groovy provides built-in classes such as JsonSlurper and JsonBuilder for JSON operations. Thanks to these classes, you can easily parse, edit, and add new elements to JSON content.
import groovy.json.JsonSlurper
import groovy.json.JsonBuilder

// Sample JSON content
def jsonString = '''
{
    "name": "John Doe",
    "age": 30
}
'''

def json = new JsonSlurper().parseText(jsonString)

// Add a new element to JSON content
json.address = "123 Main St"

// Convert 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 Element from JSON Content in Groovy

Groovy provides built-in classes such as JsonSlurper and JsonBuilder for JSON operations. These classes are very useful for easily parsing, editing, and deleting elements from JSON content.
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)

// Delete 'address' element from JSON content
json.remove('address')

// Convert 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 provides built-in classes such as JsonSlurper and JsonBuilder for JSON operations. These classes are very useful for easily parsing, editing, and changing element values in JSON content.
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)

// Change value of 'address' element in JSON content
json.address = "456 Elm St"

// Convert 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 Array in JSON Content with For in Groovy

Groovy provides built-in classes such as JsonSlurper and JsonBuilder for JSON operations. These classes are very useful for easily parsing, editing, and changing element values in JSON content.
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)

// Navigate 'people' array in JSON content with 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 script policy, header (header), parameter (parameter), body (body), and error message (error message) contents in messages can be processed with the selected script language. The original incoming request message and the original returning response message cannot be modified, only reading can be done on this data. Both reading and modification can be done on the request to be sent to the Backend API and the response to be returned to the client. The reading and modification operations include the header, parameter, and body sections of the message. Various keywords are used to access these areas via script. These keywords vary depending on the region to be accessed.
  • To access headers → <request|response>HeaderMap<From|To><Client|TargetAPI>
  • To access URL parameters → <request>UrlParamMap<From|To><Client|TargetAPI>
  • To access 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> expression should be used.
  • To change status code →statusCode<From|To><Client|TargetAPI>
/* Request
{
  "data": {
    "alan": "1"
  }
}
*/   

//Script

import groovy.json.JsonSlurper


def jsonSlurper = new JsonSlurper()
def jsonMessage = jsonSlurper.parseText(requestBodyTextFromClient)

requestErrorMessageToTargetAPI = jsonMessages
statusCodeToTargetAPI = 500


//Result: 

//{data={alan=1}} seklinde client'a dönülür.


//The requestHeaderMapFromClient variable in the script holds Headers coming from Client as 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