If a class implements the Closeable
interface Groovy adds the withCloseable
method to the class.
The withCloseable
method has a closure as argument.
The code in the closure is executed and then the implementation of the close
method of the Closeable
interface is invoked.
The Closeable
object is passed as argument to the closure, so we can refer to it inside the closure.
In the following example we have two objects that implement the Closeable
interface.
By using withCloseable
we know for sure the close
method is invoked after all the code in the closure is executed:
Continue reading →
Since the introduction of the Jenkins Declarative Pipeline syntax (as opposed to the Scripted Pipeline syntax) the concept of a shared library has become more important as we are otherwise restricted to the sections of the pipeline model.
So we’ll make a basic set-up with a call to a defined step in a shared library.
A shared library called "jdriven" is configured globally in Jenkins (see link to jenkins.io at the end on how to do that).
It has a defined step showQuote
defined in it’s own file on branch "blog/shared-lib-example"
Continue reading →
With Groovy we can configure the compiler for our source files just like we can configure the Groovy compilation unit when we use GroovyShell
to execute scripts. We can for example add annotations to source files, before they are compiled, without adding them to the actual source code ourselves. Suppose we want to apply the TypeChecked
or CompileStatic
AST transformation annotation to all source files in our project. We only have to write a configuration file and specify the name of the configuration file with the --configscript
option of the Groovy compiler. If we use Gradle to build our Groovy project we can also customise the GroovyCompile
task to set the configuration file.
The configuration file has an implicit object with the name configuration
of type CompilerConfiguration
. Also there is a builder syntax available via the CompilerCustomizationBuilder
class. Let's look at both ways to define our custom configuration. We want to add the CompileStatic
annotation to all classes, together with the ToString
AST transformation annotation. Next we also want to add the package java.time
as implicit import for our source files. This means we don't have to write an import
statement in our code to include classes from this package. Finally we add a ExpressionChecker
that will fail the compilation of our project if a variable name is only 1 character. We assume we use Gradle to build our project and we place the file groovycConfig.groovy
in the directory src/groovyCompile
. We must not name the file configuration.groovy
, because there is already a variable with the name configuration
in the script and this will confuse the compiler.
Continue reading →
A very useful feature in Groovy is the use of named arguments. Instead of a list of arguments for a method or constructor we can use a Map
argument. If the argument is the first in the list of arguments then Groovy allows use to use named arguments when we invoke the method or constructor. This means all key/value arguments are gathered together and assigned to the Map
argument. Inside our method or constructor we can then access the Map
argument and get the values for the keys. This leads to better readable code and that is very useful. IntelliJ IDEA has a Groovy intention to turn method parameters into a Map
parameter for named arguments with a few mouse clicks.
Suppose we have the following source code with a simple
method definition, 2 arguments, and the invocation of the method:
Continue reading →
IntelliJ IDEA has very good Groovy support. It also provides some intentions especially for the Groovy language. For example we can turn a map definition into a Groovy class definition with a few simple clicks.
The following screenshot shows a simple map declaration with two keys: username
and alias
. If we use the shortcut for intentions (Alt+Enter on my computer) we can choose the Convert to Class option:
Continue reading →
There is a catch when we define a constant field in Groovy. Rob Fletcher blogged about this in the post Groovy the public keyword a while ago. When we omit the public
keyword for a method then the method is still accessible as public method, because Groovy makes the method public when the class is compiled. When we leave out the public
keyword for fields Groovy creates a getter and setter method for the field at compile time and turns it into a property that applies to the Java Bean specification. This is also true if the field is static. So if we define a constant value as static final
we must keep in mind that Groovy will generate a getter method so the constant value is a read only property according to Java Bean specification.
Let's create a simple class with a constant field DEFAULT
, a property message
and a message
method. We leave out any public
keyword:
Continue reading →
The best IDE to use when developing Groovy code is IntelliJ IDEA. The Groovy plugin has some nice intentions for us that we can use to optimise and refactor our code. We will look at some of the intentions that deal with String values in this blog post. The intentions shown here work in the free Community Edition as well in the paid Ultimate Edition. To see the possible intentions in IDEA we must select the Show Intentions Action. We need to check our shortcut keys to see the assigned shortcut. On my Mac it is for example Alt+Enter. Alternatively we can press the Shift key twice and type in Show intentions. IDEA will show the action with the shortcut key for us.
Suppose we have assigned a String value to a variable in our code. We used the double quoted syntax to do so, like in Java. But we want to change it to a single quoted String value, so to make it explicit the value cannot be a GString implementation. In the following screenshot we see our variable s
with a value. We use our shortcut key to open the suggested intentions. We type convert to shorten the list with only conversion options. We see that we can change our String value to dollar slashy, regular expression, multiline or plain String syntax:
Continue reading →
The built-in dependency mechanism in Groovy is Grape. With Grape we can define dependencies in our code and Groovy will download them and make them available when we run our Groovy application. The easiest way to use it is with the @Grab
annotation with a dependency as the value. If we want to exclude a transitive dependency we use the @GrabExclude
annotation. We must specify the attributes group
and module
of the annotation with the dependency we want to exclude. An alternative syntax is a shorthand version where the group
and module
are combined into a single String value separated by a colon (:
).
In the following Groovy script we have a very simple Spring application with Java (Groovy) based configuration. So we need a dependency on the spring-context module. But we don't want to use the standard Spring logging. Spring used Apache Commons logging and we want to replace it with an SLF4J API implementation: Logback. So we use the @GrabExclude
annotation to exclude the commons logging dependency. And we add two extra dependencies to replace it: org.slf4j:jcl-over-slf4j
and ch.qos.logback:logback-classic
.
Continue reading →
Groovy has a advanced feature to define and download dependencies automatically for our code: grape. To get more information about the progress of the dependency resolution and downloading of the dependencies we must use the Java system property groovy.grape.report.downloads
and set it to true
. Groovy uses Ivy under the hood to handle the dependency management. We can get Ivy logging messages by setting the system property ivy.message.logger.level
to a numeric value. The value 4 gives the most logging and value 0 only shows error messages.
In the following example code we use -Dgroovy.grape.report.downloads=true
when we invoke a simple Groovy script with a dependency on Apache Commons library:
Continue reading →
With Grape in Groovy we can add dependency management for our code. Especially the @Grab
annotation is very useful to specify dependencies directly in our code. Groovy will download the dependencies if needed and store them in the USER_HOME/.groovy/grapes
directory. If we want to change this directory we must set the Java system property grape.root
. We specify the new directory to store the downloaded dependencies as a value.
In the following example we have a simple script with a dependency on the Apache Commons library. We use the -Dgrape.root
command line option when we run the script and specify the directory deps
. After we have run the script we can see the contents of the deps
directory to see the downloaded files.
Continue reading →
One of the very nice features of Groovy is that we can implement operator overloading. This blog post is not about how to implement operator overloading, but Groovy's operator overloading also means that operators we know in Java have corresponding methods, which are not available in Java. So instead of using operators in our code we can use the corresponding methods.
The following sample code shows some operators we know in Java and the corresponding methods in Groovy:
Continue reading →
Groovy adds the inspect
method to the Object
. This means it is available on all objects in our application. It is like the toString
method, but adds some extra formatting. The most notable is the addition of single quotes to String values.
In the following example we see the output of the inspect
method on different objects:
Continue reading →