Groovy Library

Updated 

Overview

When developing Guided workflows, configurators need to execute certain groovy operations. In order to assist them with performing these groovy operations more easily, a groovy library has been created. This library explains all the functions that one may come across while working with groovy.

One easy way to test out the Groovy scripts is by using the online Groovy compiler available at https://www.tutorialspoint.com/execute_groovy_online.php.

Fetching/ Modifying Date Variables

Convert from Date to String

You can use this code in scenarios where you need to display date and time information in a specific format, such as logging or displaying in a Screen.

For example, if you are building a flow that processes transactions and need to display the transaction date and time in a specific format in the user interface, you can use this code to convert the date object to a string and display it as needed.

The format string in the example "yyyy-MM-dd HH:mm:ss" specifies that the output string should have year, month, day, hour, minute, and second values separated by dashes and colons. You can modify this format string to match the specific format required in your application.

Replace date field with the field which stores in transaction date in the flow.

Refer to other Timezone Format here: https://mkyong.com/java/java-display-list-of-timezone-with-gmt/

Date date = new Date();

String dateString = date.format("yyyy-MM-dd HH:mm:ss");

return dateString;

Convert Date String Format

This code snippet can be used when you need to convert a string representation of a date and time into a Date object in your flow. It is particularly useful when you have a date string in a specific format, and you need to convert it to a Date object to perform further operations on it.

In the code, the variable dateString represents the date string that needs to be converted to a Date object. You can replace this with the name of the field that contains the date string in your flow.

The Date.parse() method is used to parse the date string into a Date object. The first argument specifies the format of the date string, and the second argument is the actual date string. In this case, the format of the date string is "yyyy/MM/dd HH:mm:ss", which means that the date string should have the format "year/month/day hour:minute:second".

After the date string is parsed into a Date object, it is stored in the date variable. This Date object can then be used in your flow for further processing.

String dateString = "2022/03/01 12:00:00";

Date date = Date.parse("yyyy/MM/dd HH:mm:ss", dateString);

return date;

Convert date to epoch

This code is used to convert the current date and time into Unix epoch time. Unix epoch time is the number of seconds that have elapsed since January 1, 1970, at 00:00:00 UTC.

In this code, we create a new Date object which represents the current date and time. Then, we use the time method of the Date object to get the number of milliseconds since January 1, 1970, at 00:00:00 UTC. We divide this number by 1000 to convert it into seconds and store it in the epoch variable. Finally, we return the epoch value.

This code can be useful when you need to work with time-based calculations or when you need to communicate with systems that require Unix epoch time. You can replace the new Date() with a specific date object to convert any specific date and time to Unix epoch time. 

Date date = new Date();

long epoch = date.time / 1000;

return epoch;

Convert Date to different time zones

Use this code when you need to convert a date into a formatted string representation, including the time zone. The code uses the Date class to get the current date and time, and then passes it to the  DATE_UTIL.EPOCH_TO_DATE() function along with the desired format "dd-MM-yyyy", time zone "Asia/Kolkata", and language "en". The function converts the date to the specified time zone, formats it according to the specified format, and returns the resulting string. You should replace the date variable with the actual date object you want to convert, and adjust the format, time zone, and language parameters as needed.

Date date = new Date();

return DATE_UTIL.EPOCH_TO_DATE(date,"dd-MM-yyyy","Asia/Kolkata","en")

Difference between two dates

Use this code when you need to calculate the difference between two dates in milliseconds. Make sure to replace date1 and date2 with the names of the variables you want to compare.

Date date1 = new Date();

Date date2 = new Date();

long diffInMilliseconds = date1.time - date2.time;

return diffInMilliseconds;

Adding days to a given date

This code can be useful when you need to calculate a future date by adding a certain number of days to the current date. For example, if you have a task that is due in a week's time, you can use this code to calculate the due date. You can also use this code to schedule events or tasks that occur a certain number of days from the current date.

Make sure to replace daysToAdd with the actual number of days you want to add and also replace date with the name of the variable representing the date in your code.

Date date = new Date();

int daysToAdd = 7;

date = date + (daysToAdd * 24 * 60 * 60 * 1000);

return date;

Fetch the current time and date

This code returns the current date and time. It is useful when you need to get the current date and time in your code. The returned value is an object of the Date class, which represents a specific instant in time. You can use this object to perform various operations such as date formatting, time zone conversions, and date arithmetic.

Date date = new Date();

return date;

String Functions

Adding a few characters to a string

This code can be used whenever there is a need to combine two or more strings into a single string. It can be useful in scenarios such as displaying messages or creating dynamic file names where a combination of text is required.

String str = "Hello";

String newStr = str + " World!";

return newStr;

Capitalization

This code can be used when you need to format a string in a specific way. For example, you may want to capitalize the first letter of a user's name when displaying it on a webpage or in an email. By using the capitalize() method, you can easily achieve this formatting without having to manually manipulate the string.

String str = "hello world";

String capitalizedStr = str.capitalize();

return capitalizedStr;

To Lower Case

The toLowerCase() method returns a new string with all the characters converted to lowercase. This method can be useful when dealing with strings that have inconsistent casing or when we want to make sure that all the characters in a string are in lowercase.

Use this code when you need to convert a string to lowercase. For example, when comparing two strings, it is often useful to convert both strings to lowercase before comparing them. This ensures that the comparison is case-insensitive and will work correctly regardless of the casing of the input strings.

String str = "Hello World";

String lowerCaseStr = str.toLowerCase();

return lowerCaseStr;

String Contains

String str = "Hello World";

boolean containsStr = str.contains("World");

return containsStr;

Split/Substring

  1. String str = "Hello, World";: creates a string variable str and initializes it with the value "Hello, World".

  2. String[] parts = str.split(",");: splits the string at the comma and creates an array of strings called parts containing two elements - "Hello" and " World" (with a leading space).

  3. String firstPart = parts[0];: assigns the first element of the parts array to a new variable called firstPart - in this case, "Hello".

  4. String secondPart = parts[1].trim();: assigns the second element of the parts array (with leading and trailing spaces removed) to a new variable called secondPart - in this case, "World".

  5. String subStr = str.substring(7);: creates a substring of str starting at index 7 (i.e. the eighth character) and assigns it to a new variable called subStr - in this case, "World".

These string operations can be useful for manipulating and extracting information from strings in various ways. For example, splitting a string at a delimiter (like a comma) can be useful for parsing data or extracting specific parts of a string. Trimming a string can be useful for removing leading or trailing whitespace. And creating a substring can be useful for extracting a specific portion of a longer string.

String str = "Hello, World";

String[] parts = str.split(",");

String firstPart = parts[0];

String secondPart = parts[1].trim();

String subStr = str.substring(7);

return subStr;

Number Formatting

Modifying the number of decimal places in a double variable

In this example, the number 1234.5678 is stored in the variable num. The String.format() method is then used to convert the number to a string with two decimal places, which is stored in the variable formattedNum. The format string "%.2f" specifies that the argument should be formatted as a floating-point number with two decimal places.

You can use this code when you need to display a floating-point number to a user or write it to a file in a specific format. For example, you might use this code to format a monetary value to display as a currency, with two decimal places. 

For example, if the value of num was 1234.5678, using "%.2f" format specifier will return 1234.57.

You can replace the 2 with any number to control the number of decimal places in the formatted string. For example, "%.3f" will display the number with 3 decimal places.

double num = 1234.5678;

String formattedNum = String.format("%.2f", num);

return formattedNum;

Class Type Conversion

Converting a String to an Integer

For example, if we have a text input field on a form that is supposed to take a number, it will store the input as a string. When we want to perform any calculation with that number, we need to convert it to a numerical value. This is where the above code can be useful.

Note that the code assumes that the string contains only digits. If the string contains non-digit characters, the code will throw a NumberFormatException. Therefore, it is important to ensure that the string input contains only valid characters before converting it to an integer.

String str = "123";

int num = Integer.parseInt(str);

return num;

Loop Functions

For Loop

This is for loop in Groovy that will execute a block of code for a certain number of times. In this example, the loop will run five times since the condition is i < 5.

To use this loop, replace the comment with the code that needs to be executed. The variable i is initialized to 0 and incremented by 1 after each iteration until the condition i < 5 is no longer true.

for (int i = 0; i < 5; i++) {

   // Write the code

}

While Loop

int i = 0;

while (i < 5) {

   // Write the code


    i++;

}

Map Functions

Convert from an array to a map in a specific format

This code creates a map by iterating over an array. The array contains alternating keys and values, and the code uses a for loop to process each key-value pair and add them to the map. The map is created using the Groovy syntax [:], which creates an empty map.

Here's how it works:

  1. An empty array is created using the syntax array = [];

  2. The array is then populated with alternating keys and values using the syntax array = ["key1", "value1", "key2", "value2"];

  3. An empty map is created using the syntax map = [:];

  4. A for loop is used to iterate over the array. The loop variable i is initialized to 0, and the loop continues as long as i is less than the length of the array. The loop increments i by 2 on each iteration to ensure that it processes key-value pairs.

  5. Inside the loop, the code assigns the current key to the array[i] element and the current value to the array[i+1] element.

  6. The key-value pair is then added to the map using the syntax  map[array[i]] = array[i+1];

This code is useful when you have data in an array and need to convert it to a map for easier processing. For example, you might have an array of data from a field in a API response, where each row is represented as an array of values. By converting this data to a map, you can more easily access individual fields by their column names.

array = [];

array = ["key1", "value1", "key2", "value2"];

map = [:];

for (int i = 0; i < array.length; i += 2) {

    map[array[i]] = array[i+1];

}

return map;

Convert from a map to an array

  1. map = ["key1": "value1", "key2": "value2"]; - This line creates a map object with two key-value pairs.

  2. array = []; - This line creates an empty array.

  3. int i = 0;- This line initializes a variable i to 0, which will be used in the loop.

  4. for (String key : map.keySet()) {- This line starts a for loop that iterates over the keys in the map.

  5.  array.add(key + ":" + map.get(key)); - This line retrieves the value for the current key in the map, concatenates the key and value strings with a colon, and adds the resulting string to the array.

  6. i++;- This line increments the value of i by 1.

  7. return array;- This line returns the array of concatenated key-value strings.

This code takes a map object with key-value pairs and creates an array of concatenated strings in the format "key:value". It uses a for loop to iterate over the keys in the map and retrieve the corresponding values, and then adds the concatenated strings to an array. The resulting array is returned as the output of the function.

Note: map can be replaced by any variable which already exists in the Guided Workflow

map = ["key1": "value1", "key2": "value2"];

array = [];

int i = 0;

for (String key : map.keySet()) {

    array.add(key + ":" + map.get(key));

    i++;

}

return array;

Fetch data from an existing map

Assuming a map already exists, This code is an example of how to use a map in Groovy.

wwe access the value associated with the key "name" using the syntax map.name, which is shorthand for "map.get(“name”)". This assigns the value "John" to the variable "value", which is returned by the code.

So essentially, this code is demonstrating how to use a map to store and retrieve key-value pairs in Groovy, and specifically shows how to retrieve a value associated with a specific key.

def map = [name: "John", age: 30, city: "New York"];

def value = map.name;

return value;

Array Functions

Adding items to an array

In the given code, myArray is an example variable that holds a list of items. You can replace myArray with the name of any existing variable that holds a list, and the << operator can be used to add new items to the list.

def myArray = ['apple', 'banana', 'cherry']

myArray << 'orange';

return myArray;

Removing items from an array

This code is an example of removing an item from a list in Groovy.

def myArray = ['apple', 'banana', 'cherry']

myArray.remove('banana');

return myArray;

Sorting an array

This code sorts an array of integers in ascending order using the built-in sort() method in Groovy. The sorted array is returned at the end. 

def myArray = [5, 2, 7, 3, 1, 4]

myArray.sort();

return myArray;

Sets

Adding items to an array

This code creates a new HashSet object called set, adds some strings to it, and returns the resulting set. The HashSet is a collection that does not allow duplicates, so when the code tries to add "apple" a second time, it will not be added to the set. The order of the elements in the set is not guaranteed to be the same as the order in which they were added.

This code could be used when you want to create a collection of unique items, such as a set of usernames or email addresses.

Set set = new HashSet();

set.add("apple");

set.add("banana");

set.add("cherry");

set.add("apple"); 

return set;