Groovy

Groovy Goodness: Using NullCheck Annotation To Prevent NullPointerException

Posted on by  
Hubert Klein Ikkink

In Groovy we can apply the @NullCheck annotation to a class, constructor or method. The annotation is an AST (Abstract Syntax Tree) transformation and will insert code that checks for null values in methods or constructors. If a null value is passed to an annotated method or constructor, it will throw an IllegalArgumentException. Without the annotation we could have a NullPointerException if we try to invoke a method on the value we pass as argument. The annotation has an optional property includeGenerated which by default is false. If we set it to true then the null checks are also applied to generated methods and constructors. This is very useful if we apply other AST transformations to our class that generates additional code.

Continue reading →

Groovy Goodness: Sorting Data With GINQ

Posted on by  
Hubert Klein Ikkink

GINQ (Groovy-INtegerate Query) is part of Groovy since version 4. With GINQ we can use SQL-like queries to work with in-memory data collections. If we want to sort the data we can use orderby followed by the property of the data we want to sort just like in SQL we can use order by. By default the sort ordering is ascending and null values are put last. We can change the sort ordering by specifying in desc with the orderby clause. Or to make the ascending order explicitly we use the statement in asc. Each of asc and desc also can take an argument to specify how we want null values to be sorted. The default way is to keep null values last in the ordering. If we want to make this explicit we use nullslast as argument to asc or desc. To have null values in the sorted result first we use the argument nullsfirst.

Continue reading →

Groovy Goodness: Using Tuples

Posted on by  
Hubert Klein Ikkink

Groovy supports a tuple type. A tuple is an immutable object to store elements of potentially different types. In Groovy there is a separate Tuple class based on how many elements we want to store in the tuple. The range starts at Tuple0 and ends with Tuple16. So we can store a maximum of 16 elements in a Groovy tuple.
Each of the classes has a constructor that takes all elements we want to store. But the Tuple class also has static factory methods to create those classes. We can use the tuple method and based on how many elements we provide to this method we get the corresponding Tuple object.

Continue reading →

Groovy Goodness: Using Subscript Operator With Multiple Fields On Date Related Objects

Posted on by  
Hubert Klein Ikkink

Since Groovy 4.0.5 we can use a subscript operator that accepts multiple fields on a java.util.Date and java.util.Calendar objects. And Groovy 4.0.6 extended this subscript operator to any java.time.TemporalAccessor instance. Before these Groovy version we could already use the subscript operator, but we could provide only one field we wanted to access. In a previous post we already have seen this. But now we can use multiple fields to get their values with one statement. We simply define the fields we want as arguments to the subscript operator. Under the hood the subscript operator is implemented by a getAt method that is added as an extension to the Date, Calendar and TemporalAccess classes. The return type is java.util.List and we can combine this with the multiple assignment support in Groovy. In other languages it is also called destructurizing. With multiple assignments we can assign the values from a java.util.List directly to variables.

Continue reading →

Groovy Goodness: Using Macros For Getting More Information About Variables

Posted on by  
Hubert Klein Ikkink

In a previous post we learned about the macros SV, SVI and SVD that return a string representation of variables with their name and value. Groovy 4 also added the NP and NPL macros that we can use to inspect variables. Instead of returning a GString instance these macros return a NamedValue instance or a list of NamedValue value instances. The NamedValue class is a simple class with a property name, containing the name of the variable, and property val with the value of the variable. The macro NP can be used when we have a single variable and result is a single NamedValue instance. An the macro NVL can be used with multiple variables. The result is a list of NamedValue instances where each instance represent a variable passed as argument to NVL.

Continue reading →

Groovy Goodness: Using Macros For Getting String Representation Of Variables

Posted on by  
Hubert Klein Ikkink

Groovy 4 added some built-in macros that we can use in our code. A macro is code that will create new code. It does this by manipulating the Abstract Syntax Tree (AST) before the code is compiled. So when we use a macro, the macro will change the AST and those changes will be compiled. The three built-in macros SV, SVI and SVD can create a GString instance with the names and values of the variables that are passed as argument. This can be very useful to create some meaningful debugging statements. Normally we would have to type in the variable name ourselves followed by the value. Now with these macros we don’t have to type the variable as the macro will add that to the AST for us.

Continue reading →

Groovy Goodness: Closed And Open Ranges

Posted on by  
Hubert Klein Ikkink

Groovy supports ranges for a long time. But Groovy 4 adds a new feature for ranges and that is the support for open (exclusive) ranges at the beginning of a range. Open means the number that defines the range is not part of the actual range result and we must use the less-than character (<). This is also referred to as exclusive, where the value is excluded from the range. When a range is closed the value is included, also called inclusive. Before Groovy 4 we could already define the end of the range to be exclusive or inclusive, but now we can also define the beginning of the range to be exclusive.

Continue reading →

Groovy Goodness: Creating TOML Configuration With TomlBuilder

Posted on by  
Hubert Klein Ikkink

Groovy 4 introduced support for TOML configuration file. In a previous post we already learned how we can parse TOML content. In this post we will see we can use a builder syntax to create TOML content. We need the class TomlBuilder and then define our structure using a nice builder DSL. The DSL is comparable to create JSON using the JsonBuilder. The names of the nodes in the DSL structure will be the names of the properties. Nodes within nodes will result in concatenated property names with the name of each node separated by a dot (.). We can also use collections as arguments and those will translated to TOML arrays. A collection can optionally be followed by a closure that processes each item in the collection to generate the content for the TOML array.

Continue reading →

Groovy Goodness: Reading TOML Configuration

Posted on by  
Hubert Klein Ikkink

Since Groovy 4 we can parse TOML configuration data into a Map. Once the TOML data is transformed into the Map we can use all possibilities in Groovy to lookup keys and their values in maps. For example we can use GPath expressions to easily get the value of a (nested) key. To parse TOML configuration data we must use the TomlSlurper class that is in the groovy.toml package. We can use the parse method when we have a file, reader or stream with our configuration. To parse a String value with TOML configuration we use the parseText method.

Continue reading →

Groovy Goodness: Get Row Number In GINQ Result Set

Posted on by  
Hubert Klein Ikkink

GINQ (Groovy-INtegrated Query) is added since Groovy 4. With GINQ we can query in-memory collections with SQL like statements. If we want to get the row numbers for each row in the query result set we can use the implicit variable _rn. We must specify _rn in the select expression of our GINQ query. We can even use as to give it a meaningful name in the result set.

Continue reading →

Groovy Goodness: Using The Switch Expression

Posted on by  
Hubert Klein Ikkink

Groovy supports more classifiers for a switch case statement than Java. Since Groovy 4 we can use switch also as an expression. This means the switch statement returns a value without having to use return. Instead of using a colon (:) and break we use the notation for a case. We specify the value that the switch expressions returns after . When we need a code block we simply put the code between curly braces ({…​}).

Continue reading →

Groovy Goodness: Getting Parts Of A String Enclosed By Strings

Posted on by  
Hubert Klein Ikkink

Groovy 3 adds the takeBetween method to the String class. With this method we can get all the characters that are enclosed by string values. We can specify one enclosed string value and then all text between the the first occurrence of the string and the second occurrence is returned. If multiple parts are enclosed by the string values we can also specify which occurrence we want. If the text is enclosed by different string values we can use a variant of takeBetween that takes two string values to indicate the boundaries of the text we want. Also with two different enclosed string values we can use an argument to get the n-th occurrence of the string that is found.
Since Groovy 3 we can also use takeBefore and takeAfter to get the string before or after a given string value. All three methods will return an empty string if no text can be found.

In the following example we use the takeBefore, takeAfter and takeBetween methods with different arguments:

Continue reading →

shadow-left