Jump to content
We've recently updated our Privacy Statement, available here ×

  • jmacnama
    • Features: Reports Version: v7.9 Product: Jaspersoft® Studio

    Many settings in a report are defined by formulas, such as conditions that can hide an element, special calculations, or text processing that requires knowledge of a scripting language.

    Formulas can be written in at least three languages, two of which (JavaScript and Groovy) can be used without knowledge of programming methods.

    All formulas in JasperReports are defined through expressions. The default expression language is Java, but if you're not a programmer, we recommend JavaScript or Groovy, because those languages hide a lot of the Java complexity. The language is a property of the document. To set it, select the document root node in the Outline view and choose your language in the Language property in the Properties view.

    An expression is a formula that operates on some values and returns a result, like a formula in a spreadsheet cell. A cell can have a simple value or a complex formula that refers to other values. In a spreadsheet you refer to values contained in other cells; in JasperReports you use the report fields, parameters, and variables. Whatever is in your expression, when it's computed, it returns a value (which can be null).

    Expression Types

    An expression's type is determined by the context in which the expression is used. For example, if your expression is used to evaluate a condition, the expression should be Boolean (true or false); if you're creating an expression to display in a text field, it's probably a String or a number (Integer or Double). Using the right type is crucial; JasperReports requires precision when choosing an expression type.

    Some of the most important Java types are:

    java.lang.Boolean

    Defines an Object that represents a Boolean value such as true and false

    java.lang.Byte

    Defines an Object that represents a byte

    java.lang.Short

    Defines an Object that represents an short integer

    java.lang.Integer

    Defines an Object that represents integer numbers

    java.lang.Long

    Defines an Object that represents long integer numbers

    java.lang.Float

    Defines an Object that represents floating point numbers

    java.lang.Double

    Defines an Object that represents real numbers

    java.lang.String

    Defines an Object that represents a text

    java.util.Date

    Defines an Object that represents a date or a timestamp

    java.lang.Object

    A generic java Object

    If an expression is used to determine the value of a condition that determines, for instance, whether an element should be printed, the return type is java.lang.Boolean. To create it, you need an expression that returns an instance of a Boolean object. Similarly, if an expression shows a number in a text field, the return type is java.lang.Integer or java.lang.Double.

    Neither JavaScript nor Groovy is particularly formal about types, since they are not typed languages; the language itself treats a value in the best way by trying to guess the value type or by performing implicit casts (conversion of the type).

    Expression Operators and Object Methods

    Operators in Java, Groovy and JavaScript are similar because these languages share the same basic syntax. Operators can be applied to a single operand (unary operators) or on two operands (binary operators). The following table shows a number of operators, but it is not a complete list. For example, there is a unary operator to add 1 to a variable (++), but it is easier to use x + 1.

    Expression operators

    Operator

    Description

    Example

    +

    Sum (it can be used to sum two numbers or to concatenate two strings)

    A + B

    -

    Subtraction

    A - B

    /

    Division

    A / B

    %

    Rest, it returns the rest of an integer division

    A % B

    ||

    Boolean operator OR

    A || B

    &&

    Boolean operator AND

    A && B

    ==

    Equals

    A == B

    !=

    Not equals

    A != B

    !

    Boolean operator NOT

    !A

    note-icon-ns.png

    Regarding the Equals operator: in Java, the == operator can only be used to compare two primitive values. With objects, you need to use the special method “equals”; for example, you cannot write an expression like "test" == "test", you need to write "test".equals("test").

     

    Regarding the Equals operator: in Java, the != operator can only be used to compare two primitive values.

    Within an expression, you can use the syntax summarized in Syntax for referring to report objects to refer to the parameters, variables, and fields defined in the report.

    Syntax for referring to report objects

    Syntax

    Description

    $F{name_field}

    Specifies the name_field field ("F" means field).

    $V{name_variable}

    Specifies the name_variable variable.

    $P{name_parameter}

    Specifies the name_parameter parameter.

    $P!{name_parameter}

    Special syntax used in the report SQL query to indicate that the parameter does not have to be dealt as a value to transfer to a prepared statement, but that it represents a little piece of the query.

    $R{resource_key}

    Special syntax for localization of strings.

    $X{functionName, col_name, param1,[param2]}

    Syntax for complex queries, such as comparing a column value to a parameter value. Based on the function in the first argument, JasperReports constructs a SQL clause. The following functions are available:

    Functions expecting three arguments for $X{} – EQUAL, NOTEQUAL, LESS, LESS] (less than or equal to), GREATER, [GREATER (greater than or equal to), IN, NOTIN. For example:

    $X{EQUAL, order_date, date_parameter}

    Functions expecting four arguments for $X{} –                                                                                                                                 

    BETWEEN (excludes both endpoints)

    BETWEEN] (includes right endpoint)

    [bETWEEN (includes left endpoint)

    [bETWEEN] (includes both endpoints)

    For example:

    $X{BETWEEN, order_date, start_date_param, end_date_param}

    In summary, fields, variables and parameters represent objects; specify their type when you declare them within a report.

    Although expressions can be complicated, usually it is a simple operation that returns a value. There is a simple if-else expression that is very useful in many situations. An expression is just an arbitrary operation that any stage must represent a value. In Java, these operators can be applied only to primitive values, except for the sum operator (+). The sum operator can be applied to a String expression with the special meaning of concatenate. For example:

    $F{city} + “, ” + $F{state}

    results in a string like:

    San Francisco, California

    Any object in an expression can include methods. A method can accept zero or more arguments, and it can return or not a value. In an expression you can use only methods that return a value; otherwise, you would have nothing to return from your expression. The syntax of a method call is:

    Object.method(argument1, argument2, <etc.>)

    Some examples:

    Expression

    Result

    “test”.length()

    4

    “test”.substring(0, 3)

    “tes”

    “test”.startsWith(“A”)

    false

    “test”.substring(1, 2).startsWith(“e”)

    true

    The methods of each object are usually explained in the JasperReports Library Javadocs, which that are available at http://jasperreports.sourceforge.net/api/.

    You can use parentheses to isolate expressions and make the overall expression more readable.

    Using an If-Else Construct in an Expression

    A way to create an if-else-like expression is by using the special question mark operator. For example:

    (($F{name}.length() > 50) ? $F{name}.substring(0,50) : $F{name})

    The syntax is (<condition>) ? <value on true> : <value on false>. It is extremely useful, and can be recursive, meaning that the value on true and false can be represented by another expression which can be a new condition:

    (($F{name}.length() > 50) ? (($F{name}.startsWidth(“A”)) ? “AAAA” : “BBB”) : $F{name})

    This expression returns the String AAAA when the value of the field name is longer than 50 characters and starts with A, returns BBB if it is longer than 50 characters but does not start with A, and, finally, returns the original field value if neither of these conditions is true.

    Despite the possible complexity of an expression, it can be insufficient to define a needed value. For example, if you want to print a number in Roman numerals or return the name of the weekday of a date, it is possible to transfer the elaborations to an external Java class method, which must be declared as static, as shown in the following example:

    MyFormatter.toRomanNumber( $F{MyInteger}.intValue() )

    The function operand toRomanNumber is a static method of the MyFormatter class, which takes an int as argument (the conversion from Integer to int is done by means of the intValue() method; it is required only when using Java as language) and gives back the Roman version of a number in a lace.

    This technique can be used for many purposes; for example, to read the text from a CLOB field or to add a value into a HashMap (a Java object that represents a set of key/value pairs).

    Using Unicode Characters in Expressions

    You can use Unicode syntax to write non-Latin-based characters (such as Greek, Cyrillic, and Asian characters). For these characters, specify the Unicode code in the expression that identifies the field text. For example, to print the Euro symbol, use the Unicode u20ac character escape. The expression u20ac is not simple text; it is a Java expression that identifies a string containing the € character.

    note-icon-ns.png

    If you use this character in a static text element, “u20ac” will appear. The value of a static field is not interpreted as a Java expression.

     

    Using Java as a Language for Expressions

    Java was the first language supported by JasperReports and is still the most commonly-used language as well as being the default.

    Following are some examples of Java expressions:

    “This is an expression”                                                                                                                                                                                         
    new Boolean(true)                                                                                                                                                                                                 
    new Integer(3)                                                                                                                                                                                                 
    (($P{MyParam}.equals("S")) ? "Yes" : "No")                                                                                                                                             


    new Integer( 5 + 3 )The first thing to note is that each of these expressions represents a Java Object, meaning that the result of each expression is a non-primitive value. The difference between an object and a primitive value makes sense only in Java, but it is very important: a primitive value is a pure value like the number 5 or the Boolean value true.

    Operations between primitive values have as a result a new primitive value, so the expression:

    5+5

    results in the primitive value 10. Objects are complex types that can have methods, can be null, and must be “instanced” with the keyword “new” most of the time. In the second example above, for instance (new Boolean(true)), we must wrap the primitive value true in an object that represents it.

    By contrast, in a scripting language such as Groovy and JavaScript, primitive values are automatically wrapped into objects, so the distinction between primitive values and objects wanes. When using Java, the result of our expression must be an object, which is why the expression 5+3 is not legal as-is but must be fixed with something like this:

    The fix creates a new object of type Integer representing the primitive value 10.

    So, if you use Java as the default language for your expressions, remember that expressions like the following are not valid:

    3 + 2 * 5                                                                                                                                                                                                                                                     
    true                                                                                                                                                                                                                                                         
    (($P{MyParam} == 1) ? "Yes" : "No")                                                                                                                                                                                             

    Groovy is a full language for the Java 2 Platform. Inside the Groovy language you can use all classes and JARs that are available for Java. The following table compares some typical JasperReports expressions written in Java and Groovy:These expressions don’t make the correct use of objects. In particular, the first and the second expressions are not valid because they are of primitive types (integer in the first case and boolean in the second case) which do not produce an object as a result. The third expression is not valid because it assumes that the MyParam parameter is a primitive type and that it can be compared through the == operator with an int, but it cannot. In fact, we said that parameters, variables, and fields are always objects and primitive values cannot be compared or used directly in a mathematical expression with an object.

    Using Groovy as a Language for Expressions

    The modular architecture of JasperReports provides a way to plug in support for languages other than Java. By default, the library supports Groovy and JavaScript.

    Groovy and Java code samples

    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}

    Comparison of numbers

    new Boolean($F{f}.intValue() == 1)

    $F{f} == 1

    Comparison of strings

    new Boolean($F{f} != null && $F{f}.equals("test"))

    $F{f} == "test"

    The following is a correct Groovy expression:

    new JREmptyDataSource($F{num_of_void_records})

    JREmptyDataSource is a class of JasperReports that creates an empty record set (meaning with the all fields set to null). You can see how you can instance this class (a pure Java class) in Groovy without any problem. At the same time, Groovy allows you to use a simple expression like this one:

    5+5

    The language automatically encapsulates the primitive value 10 (the result of that expression) in a proper object. Actually, you can do more: you can treat this value as an object of type String and create an expression such as:

    5 + 5+ ”my value”

    Whether or not such an expression resolves to a rational value, it is still a legal expression and the result is an object of type String with the value:

    10 my value

    Hiding the difference between objects and primitive values, Groovy allows the comparison of different types of objects and primitive values, such as the legal expression:

    $F{Name} == “John”

    This expression returns true or false, or, again:

    $F{Age} > 18

    Returns true if the Age object interpreted as a number is greater than 18.

    “340” < 100

    Always returns false.

    “340”.substring(0,2) < 100

    Always returns true (since the substring method call produces the string “34”, which is less than 100).

    Groovy provides a way to greatly simplify expressions and never complains about null objects that can crash a Java expression throwing a NullPointerException. It really does open the doors of JasperReports to people who don’t know Java.

    Using Javascript as a Language for Expressions

    JavaScript is a popular scripting language with a syntax very similar to Java and Groovy. JavaScript has a set of functions and object methods that in some cases differ from Java and Groovy. For example, the method String.startsWith(...) does not exist in JavaScript. You can still use Java objects in JavaScript. An example is:

    (new java.lang.String("test")).startsWith("t")

    This is a valid JavaScript expression creating a Java object (in this case a java.lang.String) and using its methods.

    JavaScript is the best choice for users who have no knowledge of other languages. The other significant advantage of JavaScript is that it is not interpreted at run time, but instead generates pure Java byte-code. As a result, it offers almost the same performance as Java itself.


    User Feedback

    Recommended Comments

    There are no comments to display.



    Create an account or sign in to comment

    You need to be a member in order to leave a comment

    Create an account

    Sign up for a new account in our community. It's easy!

    Register a new account

    Sign in

    Already have an account? Sign in here.

    Sign In Now

×
×
  • Create New...