Groovy Scripting / Groovy Sample scripts

Groovy does not require the end of a statement to be a semicolon, but it speeds up processing if they are included.

$ is a Groovy reserved word and will conflict with strings manipulation and regexp. In Groovy it is used to reference a variable within a string. If you need to use $ within a regular expression, use 'single quotes' around your regular expression.


BeanShell allows a character to be added to a string, Groovy does not. You need to convert the character to a string, one method is

newString = Character.toString(aCharacter) + aString;

For string replacement, such as to strip the trailing text off a string, escape the $ e.g.

stringS = stringS.replaceAll("last words\$", "");


BeanShell allowed the use of class imports directly, but Groovy does not - it reports 'No such property'. For example in BeanShell

java.text.DecimalFormat df = new java.text.DecimalFormat("#.##");

Groovy however requires

import java.text.DecimalFormat;
DecimalFormat df = new java.text.DecimalFormat("#.##");


Checking for the existence of a variable (void check). Use in init.groovy to access anywhere.

if (binding.variables.containsKey("variableName") { ... }

A shortcut method, that does not test for null i.e. returns false for null value as well as missing variable

Map exists = binding.variables;
if (exists.variableName) { ... }


File references (ignoring the need for File.separator if an OS file) are, using an actual file object

File f = new File(rootImageDirectory, "somedir/somefile");

and using a path

File f =new File(pathToDir + "somedir/somefile");


Lists are a simple

list = [];

A populated list is now

list = ["do", "re", "mi", "fa", "so", "la", "ti"];


A method can use either the 'def' or, for example, 'public String' format. The code below replaces single quotes with the html entity for a single quote

def aposSwap(String s) {
   if(s == null || s.equals("")) return null;
   return s.replaceAll("'","&#39 ;").trim();
}


Calls to setAccessible(true) and/or setAccessibility(true) are no longer required to access jAlbum's private fields


Staments in Groovy requires an expression to be an on the same line before an operator ( +, - etc.)