Creating expressions using Groovy

JasperReports supports scripting languages to define expressions (included Groovy and JavaScript), avoiding the complexity experienced by report writers that don't know Java, which has been for a long time the default language used to define the expressions (like calculations and text elaborations).

Groovy is probably the best choice for several reasons:

  • it is fully Java-compatible scripting language
  • it is extremely flexible (it is not strongly typed like Java)
  • the Groovy language is converted in Java byte code, avoiding performance issues typical of interpreted languages (like JavaScript)

Groovy simplifies the report designer's life, and it leaves to skilled developers all the power of the Java language.

Here are some examples, that show how simple and elegant Groovy is when compared to Java:

Expression Java Groovy
Field $F{field_name} $F{field_name}
Sum of two double fields new Double($F{f1}.doubleValue() + $F{f2}.doubleValue()) $F{f1} + $F{f2}
Comparision of numbers new Boolean($F{f}.intValue() == 1) $F{f} == 1
Comparision of strings new Boolean($F{f} != null && $F{f}.equals("test")) $F{f} == "test"

Groovy is fully Java-compatible. This means that we we can reference pur Java clases in Groovy expressions. The following is a correct Groovy expression:

new JREmptyDataSource($F{num_of_void_records})

JREmptyDataSource is a class of JasperReports that generates a set of empty records (meaning with all fields set to null). It is possible to instance this pure Java class in Groovy without any problem.

Thanks to the compatibility it's then possible to convert Java based reports in Groovy just changing the language property of the reports.

Groovy is a great example of a scripting language that opens the doors of JasperReports to all people (report designers) that don't know Java.

Using Groovy in iReport

iReport provides full support for Groovy. To set "Groovy" as default language in a report, select the root node of the report structure in the report inspector and set the Language property in the property sheet to Groovy.

When the report language is set to Groovy, JasperReports automatically uses the Groovy compiler to generate the Jasper file. Groovy is the language set by default in all the templates shipped with iReport.

Deploy Reports that Use Groovy

If you use Groovy as a scripting language for expressions, you have to add the groovy-all-1.5.5.jar into your application classpath in order to run your reports succesfully.