Groovy

Groovy Goodness: Using The Call Operator ()

Posted on by  
Hubert Klein Ikkink

In Groovy we can add a method named call to a class and then invoke the method without using the name call. We would simply just type the parentheses and optional arguments on an object instance. Groovy calls this the call operator: (). This can be especially useful in for example a DSL written with Groovy. We can add multiple call methods to our class each with different arguments. The correct method is invoked at runtime based on the arguments.

In the following example we have User class with three call method implementations. Next we see how we invoke the call methods, but without typing the method name and just use the parenthesis and arguments:

Continue reading →

Groovy Goodness: Creating Root JSON Array With JsonBuilder

Posted on by  
Hubert Klein Ikkink

To create JSON output with Groovy is easy using JsonBuilder and StreamingJsonBuilder. In the samples mentioned in the links we create a JSON object with a key and values. But what if we want to create JSON with a root JSON array using JsonBuilder or StreamingJsonBuilder? It turns out to be very simple by passing a list of values using the constructor or using the implicit method call.

In the following example we use JsonBuilder to create a root JSON array:

Continue reading →

Groovy Goodness: Identity Closure

Posted on by  
Hubert Klein Ikkink

In functional programming we have the concept of an identity function. An identity function returns the same result as the input of the function. Groovy has a lot of functional paradigms including a identity function. Of course in Groovy's case it is an identity closure. It is defined as a constant in the Closure class: Closure.IDENTITY. If we use this closure we get the same result as the argument we provide.

In the following example we first create our own identity closure. Next we use the built-in Closure.IDENTITY closure:

Continue reading →

Groovy Goodness: Interrupted Sleeping

Posted on by  
Hubert Klein Ikkink

Groovy adds a lot of useful methods to the Java JDK classes. One of them is the sleep method that is added to all objects. With the sleep method we can add a pause to our code. The sleep method accepts a sleep time in milli seconds. The implementation of the method will always wait for he given amount of milli seconds even if interrupted. But we can add a closure as extra argument, which is invoked when the sleep method is interrupted. We should return true for the closure to really interrupt, otherwise we use false.

In the following example we use the sleep method to pause the bedtime method of the User class. We run the bedtime method in a thread and after 2000 milli seconds we intercept the thread. The sleep method still wait for 5 seconds, before ending:

Continue reading →

Groovy Goodness: Direct Field Access In (Super) Classes

Posted on by  
Hubert Klein Ikkink

When we use the property syntax of Groovy to get the value for a property, Groovy will actually try to invoke a get method for that property if it is available. So for example if we have the statement user.name actually user.getName() is invoked. If we want to reference a property field directly, so bypassing the get method, we must place an @ in front of the property field name. In the previous example we would write user.@name to get the field value directly. The same rules apply for setting a value for a property with the Groovy syntax. If we write user.name = 'mrhaki' then actually user.setName('mrhaki') is invoked. We can use the @ prefix also to set a value without invoking the set method for that property. So in our example it would be user.@name = 'mrhaki' and the setName method is not used.

In the following example we have a class Person with a name property. We add a getName method which formats the name field and returns the value. In a subclass User we access the name property from the super class using the Groovy property syntax and with the @ prefix:

Continue reading →

Spicy Spring: Using Groovy Configuration As PropertySource

Posted on by  
Hubert Klein Ikkink

We have many ways to provide configuration properties to a Spring (Boot) application. We can add our own custom configuration properties format. For example we can use Groovy's ConfigObject object to set configuration properties. We need to read a configuration file using ConfigSlurper and make it available as a property source for Spring. We need to implement two classes and add configuration file to support a Groovy configuration file in a Spring application.

First we need to write a class that extends the PropertySource in the package org.springframework.core.env. This class has methods to get property values based on a given key. There are already some subclasses for specific property sources. There is for example also a MapPropertySource class. We will extend that class for our implementation, because we can pass our flattened ConfigObject and rely on all existing functionality of the MapPropertySource class:

Continue reading →

Groovy Goodness: Customise Log AST Annotations

Posted on by  
Hubert Klein Ikkink

Adding logging support to a class in Groovy is easy. We can choose to add SLF4J, Log4j, Log4j2, Apache Commons or Java Util Logging to our class. The default implementation of the Abstract Syntax Tree (AST) transformation is to add a log field of the correct type. As category name the complete class name (including the package) is used. We can change the name of the field with the value attribute. To alter the category name we use the attribute category.

In the following example snippet we change the log field name to LOGGER and set a custom category name:

Continue reading →

Groovy Goodness: Represent Map As String

Posted on by  
Hubert Klein Ikkink

Groovy adds to Map objects the toMapString method. With this method we can have a String representation of our Map. We can specify an argument for the maximum width of the generated String. Groovy will make sure at least the key/value pairs are added as a pair, before adding three dots (...) if the maximum size is exceeded.

def course = [
    name: 'Groovy 101',
    teacher: 'mrhaki',
    location: 'The Netherlands']

assert course.toMapString(15) == '[name:Groovy 101, ...]'
assert course.toMapString(25) == '[name:Groovy 101, teacher:mrhaki, ...]'

Continue reading →

Groovy Goodness: Make Class Cloneable With @AutoClone

Posted on by  
Hubert Klein Ikkink

Groovy has many AST annotations that add code to our class (the Abstract Syntax Tree - AST) before it is compiled. So the compiled class file contains the code added by the AST annotation. With the @AutoClone annotation a clone method is added and the class implements the Cloneable interface. We have different strategies to choose from to support cloning for our class.

The default strategy is to invoke super.clone() in the generated clone method. The next statements will deep copy the properties (and optional fields) from our class. If one of the properties cannot be cloned an exception is thrown. In the following example code snippet we apply the @AutoClone annotation to the classes Course and Teacher:

Continue reading →

shadow-left