Plugins - Groovy and equivalent Java code examples

This article provides a set of examples of Groovy code and the equivalent Java code and is provided to assist users who are familiar with authoring hook scripts, filters and custom gathers to start writing plugins.

Code examples

List collect()

Groovy
// Takes a list of numbers and returns another
// list with all the numbers doubled
[1, 2, 3].collect() { it * 2 } == [0, 2, 4, 6]
Java
List<Integer> myNumbers = Arrays.asList(1, 2, 3);
List<Integer> myNumbersDoubled = myNumbers
    .stream()
    .map(s -> s * 2)
    .collect(Collectors.toList());

each() over a map

Groovy
def results = transaction?.response?.resultPacket?.results?.find()

result.metaData.each {
    k, v ->
    println "key: ${k} value: ${v}"
}
Java
var results = transaction.getResponse().getResultPacket().getResults().find()

result.metaData.forEach({
    (k, v) ->
     System.out.printf("key: %s value: %s", k, v);
})

find() an item in a list

Groovy
def myNumbers = [1, 2, 3]

// Find the first number which is greater than 1
myNumbers.find { it > 1 } == 2
Java
List<Integer> myNumbers = Arrays.asList(1, 2, 3);

// Find the first number which is greater than 1
int item = myNumbers.stream()
    .filter(s -> s > 1)
    .findFirst()
    .orElse(-1); // Default value. Note: If you exclude this,
                 // you will get an instance of Optional<int> and not an int

item == 2 // True

flatten() nested listss

Groovy
def rndStaff = ["Matthew", "Luke"]
def productionStaff = ["Phil", "Ben"]
def salesStaff = ["Greg", "Ellen"]

def funnelbackStaffNested = [rndStaff, productionStaff, salesStaff];

// We current have a list of lists which looks something like
// [ ["Matthew", "Luke"] ["Phil", "Ben"] ["Greg","Ellen"] ]
// We we actually want is
// ["Matthew", "Luke", "Phil", "Ben", "Greg","Ellen"]
// The line below does that
def funnelbackStaffFlat = funnelbackStaffNested.flatten()
Java
List<String> rndStaff = Arrays.asList("Matthew", "Luke");
List<String> productionStaff = Arrays.asList("Phil", "Ben");
List<String> salesStaff = Arrays.asList("Greg", "Ellen");

List<List<String>> funnelbackStaffNested = new ArrayList<List<String>>();
funnelbackStaffNested.add(rndStaff);
funnelbackStaffNested.add(productionStaff);
funnelbackStaffNested.add(salesStaff);

// We current have a list of lists which looks something like
// [ ["Matthew", "Luke"] ["Phil", "Ben"] ["Greg","Ellen"] ]
// We we actually want is
// ["Matthew", "Luke", "Phil", "Ben", "Greg","Ellen"]
// The lines below does that
List<String> funnelbackStaffFlat = funnelbackStaffNested
    .stream()
    .flatMap(hList -> hList.stream())
    .collect(Collectors.toList());

Defining a new arraylist

Groovy
def myList = ["cat", "dog"]
Java
// Method 1
ArrayList<String> myList = new ArrayList<String>();
myList.add("cat");
myList.add("dog");

// Method 2
ArrayList<String> myList = new ArrayList<String>(Arrays.asList("cat","dog"));

Defining a new map with some initial data

Groovy
def myMap = [name: "Jerry", age: 42, city: "New York"]
Java
// Java 9 way - This works for up to 10 elements:
Map<String, String> myMap = Map.of("name","Jerry", "age", "42", "city", "New York");
// This works for any number of elements
Map<String, String> myMap = Map.ofEntries(
    entry("name", "Jerry"),
    entry("age", "42"),
    entry("city", "New York"),
);

Defining a new map

Groovy
def myMap = [:]
Java
// Untyped way
var myMap = new Hashmap();

// Typed version with generics
// In this case, we want a map with string keys and string values
Map<String, String> myMap = new Hashmap<String, String>()

Defining variables without types

Groovy
def mySpecialInt = 5
def mySpecialString = "testing"
Java
var mySpecialInt = 5;
var mySpecialString = "testing";
It is best practice to type your variables.

Using a map constructor

Groovy
class Sample {
    Integer age
    String name
}

def s1 = new Sample([age: 36, name: 'bob'])
assert 36 == s1.age
assert 'mrhaki' == s1.name
Java
class Sample {
    int age
    String name

    public Sample(int age, String name) {
        this.age = age;
        this.name = name;
    }
}

Sample myNewInstance = new Sample(36, bob);

Safe navigation operator

Groovy
if(transaction?.response?.customData) {
   // Do something
}
Java
if(transaction != null &&
    transaction.getResponse() != null &&
    transaction.getResponse().getCustomData != null) {
   // Do something
}

Ternary operation

Groovy
// booleanExpression ? expression1 : expression2
// Note that groovy treats nulls and empty strings as false; *groovy truth
def displayName = user.name ? user.name : 'Anonymous'

// Elvis operator is the shorthand version of the above
def displayName = user.name ?: 'Anonymous'
Java
// Ternary operator
// booleanExpression ? expression1 : expression2
 var displayName = StringUtils.isEmpty(user.getName()) != null ? user.getName() : "Anonymous";

Using .each() to loop through collections

Groovy
transaction.response.resultPacket.results.each {
    result ->
    result.listMetaData["testing"] = ["something"]
}
Java
transaction.getResponse().getResultPacket().getResults()
    .stream()
    .forEach({
        result ->
        result.getListMetadata().replaceValues("testing", Arrays.asList("something"))
    });
}

// Note that metaData property on results is deprecated
transaction.getResponse().getResultPacket().getResults
    .stream()
    .forEach({
        result ->
        result.getMetaData().put("testing", Arrays.asList("something"));
    });
}

findAll() example

Groovy
def myNumbers = [1, 2, 3]

// Find all numbers which is greater than 1
myNumbers.findAll { it > 1 } == [2, 3]
Java
List<Integer> myNumbers = Arrays.asList(1, 2, 3);

// Find all numbers which is greater than 1
List<Integer> item = myNumbers.stream()
    .filter(s -> s > 1)
    .collect(Collectors.toList()); // [2, 3]

Variable - set default value

Groovy
def type = context.getConfigValue(context.getConfigSetting(PluginUtils.KEY_PREFIX+".color").orElse("blue");
def debug = context.getConfigValue(context.getConfigSetting(PluginUtils.KEY_PREFIX+".debug") ?: false
Java
String color = Optional.ofNullable(context.getConfigSetting(PluginUtils.KEY_PREFIX+".color")).orElse("British Library");
Boolan debug = Boolean.parseBoolean(context.getConfigSetting(PluginUtils.KEY_PREFIX+".debug"));