Since Groovy 2.4.0 we can get the indices from the elements in a collection with the indices method. In addition to this method we can also use the withIndex to combine an Iterable with the indices directly. The output is a List of tuples where the first item is the value of the Iterable and the second the index value. We can pass an optional argument to the withIndex which is the starting point for the index values. Another alternative is the indexed method. The indexed method returns a Map, where the key of the entry is the index value and the entry value is the Iterable value.
In the following example we use the withIndex method. The sample of the alphabet is the same as in the blog post about indices, but rewritten with the withIndex method:
Continue reading →
Groovy already has so many extra methods for working with collections. If we have to need to swap two elements in a collection we can use the swap method. We provide the two index values of the elements we want to swap and Groovy swaps the elements.
In the following sample we have a simple list and swap all elements by invoking the swap method two times:
Continue reading →
In Java 8 we can create a constructor reference. We must use the syntax Class::new and we get a constructor reference. This syntax is not supported in Groovy, but we can use the method pointer or reference syntax .& to turn a method into a closure. We can even turn a constructor into a closure and use it everywhere where closures are allowed.
In the following sample code we have a User class with some properties. Via the User.metaClass we can get a reference to the method invokeConstructor and turn it into a method closure:
Continue reading →
Recently I had to access the XML-RPC WordPress API for a small project. Luckily with Groovy we can access a XML-RPC server in a Groovy way. We need to use the Groovy XML-RPC module, which is a separate dependency. The module provides code to write a XML-RPC server, but also code to access a XML-RPC server as client. We use the class XMLRPCServerProxy in the package groovy.net.xmlrpc to act as a client to a XML-RPC API. The XMLRPCServerProxy class only needs to know the URL to access the API. All API methods are dynamically dispatched to the server, so it is very flexible.
In the following Groovy script we use the WordPress XML-RPC API to access posts:
Continue reading →
Since Groovy 2.4 we can use the indices property on a Collection to get the indices of the elements in the collection. We get an IntRange object as a result.
def list = [3, 20, 10, 2, 1]
assert list.indices == 0..4
// Combine letters in alphabet
// with position (zero-based).
def alphabet = 'a'..'z'
def alphabetIndices = [alphabet, alphabet.indices].transpose()
// alphabetIndices = [['a', 0], ['b', 1], ...]
// Find position of each letter
// from 'groovy' in alphabet.
def positionInAlphabet = 'groovy'.inject([]) { result, value ->
result << alphabetIndices.find { it[0] == value }[1] + 1
result
}
assert positionInAlphabet == [7, 18, 15, 15, 22, 25]
Continue reading →
Groovy adds the pop and push methods to the List class. With the pop method we remove the last element of the list. And with the push method we add an element to the end of the list.
def list = ['Groovy', 'is', 'great!']
// Remove last item from list
// with pop().
assert list.pop() == 'great!'
assert list == ['Groovy', 'is']
// Remove last item
// which is now 'is'.
list.pop()
// Add new item to end of
// the list (equivalent for add()).
list.push('rocks!')
assert list == ['Groovy', 'rocks!']
Continue reading →
In Groovy we can use the head and tail methods for a long time on Collection objects. With head we get the first element and with tail the remaining elements of a collection. Since Groovy 2.4 we have a new method init which returns all elements but the last in a collection.
In the following example we have a simple list and apply the different methods:
Continue reading →
We know Groovy has a lot of nice methods for working with collections. For example in previous blog posts we have seen how to take or drop elements from a list and even with a condition. Since Groovy 2.4 we can now also use the dropRight and takeRight methods to take or drop elements from the end of the list.
In the following example we have a simple list and we use the dropRight and takeRight methods to get elements from the list:
Continue reading →
When we write Groovy code there is a big chance we also write some closures. If we are working with collections for example and use the each, collect or find methods we use closures as arguments for these methods. We can assign closures to variables and use the variable name to reference to closure. But we can also create a subclass of the Closure class to implement a closure. Then we use an instance of the new closure class wherever a closure can be used.
To write a closure as a class we must subclass Closure and implement a method with the name doCall. The method can accept arbitrary arguments and the return type can be defined by us. So we are not overriding a method doCall from the superclass Closure. But Groovy will look for a method with the name doCall to execute the closure logic and internally use methods from the Closure superclass.
Continue reading →
If we write a specification for a specific class we can indicate that class with the @Subject annotation. This annotation is only for informational purposes, but can help in making sure we understand which class we are writing the specifications for. The annotation can either be used at class level or field level. If we use the annotation at class level we must specify the class or classes under test as argument for the annotation. If we apply the annotation to a field, the type of the field is used as the class under test. The field can be part of the class definition, but we can also apply the @Subject annotation to fields inside a feature method.
In the following example Spock specification we write a specification for the class Greet. The definition of the Greet class is also in the code listing. We use the @Subject annotation on the field greet to indicate this instance of the Greet class is the class we are testing here. The code also works with the @Subject annotation, but it adds more clarity to the specification.
Continue reading →
The MarkupTemplateEngine added in Groovy 2.3 is very powerful. We can define layout templates with common markup we want to be used in multiple other templates. In the layout template we define placeholders for variables and content blocks surrounded by shared markup. We define values for these variables and content blocks in the actual template. We even can choose to propagate model attributes from the template to the layout template. Let's first create a layout template with the name main.tpl:
// File: main.tpl
html {
head {
// Use pageTitle layout property.
title(pageTitle)
}
body {
section(id: 'main') {
// Render mainContents layout property.
mainContents()
}
section(id: 'actions') {
// Render actions layout property.
actions()
}
footer {
// A template is also Groovy code, we can
// define new variables or methods.
// pubDate should be set via original template
// model.
def generatedOn = pubDate ?: new Date()
p("Generated on ${dateFormat(generatedOn)}")
}
}
}
def dateFormat(date) {
date.format('dd-MM-yyyy')
}
Continue reading →
Since Groovy 2.3 we can use the MarkupTemplateEngine to generate XML/HTML. We can write our templates using a builder syntax. Inside our templates we can define nested templates. These nested templates contain builder syntax code and can use objects that are passed as attributes to the nested template. To invoke a nested template we must use the fragment method and pass a Map with attributes that is used in the nested template. We can re-use nested templates inside our template.
In the following sample code we define two nested templates: faIcon and list. Inside our template we use the fragment method to call these nested templates and we set values to the attributes that are used in the nested templates:
Continue reading →