Groovy

Ratpacked: Using Spring As Component Registry

Posted on by  
Hubert Klein Ikkink

Usually in our Ratpack application we use a registry to store components that we want to use in our application code. The calling code for the registry doesn't need to know how the registry is implemented. Ratpack support Google Guice for example, but Spring is also supported. This means we can define the components for our registry using Spring and we only have to tell Ratpack where to look for the Spring configuration files. Ratpack provides for us the ratpack.spring.Spring class with the static method spring. This method returns a Ratpack registry implementation we can use in our application.

To enable Spring support we must add the Ratpack spring-boot dependency to our build file:

Continue reading →

Groovy Goodness: Creating Files And Directories With Nice DSL Using FileTreeBuilder

Posted on by  
Hubert Klein Ikkink

Groovy has a lot of nice and useful gems. One of them is the FileTreeBuilder class. With this class we can create directories and files using a nice DSL with a builder syntax. The code already reflects the hierarchy of the directory structure, which makes it so more readable. We can use an explicit way of referring to methods in the FileTreeBuilder class, but there is also support for a more dynamic version, where Groovy's dynamic nature comes to play.

In the first example we use the explicit method names. We can use the method dir to create directories and the method file to create a file. We can specify a name for the file and also contents:

Continue reading →

Groovy Goodness: Using Tuples

Posted on by  
Hubert Klein Ikkink

A tuple is an ordered, immutable list of elements. Groovy has it's own groovy.lang.Tuple class. We can create an instance of a Tuple by providing all elements that need to be in the Tuple via the constructor. We cannot add new elements to a Tuple instance or remove elements. We cannot even change elements in a tuple, so it is completely immutable. This makes it very useable as return value for a method where we need to return multiple values. Groovy also provides a Tuple2 class that can be used for tuple instance of only two elements. The elements are typed in a Tuple2 instance.

In the following example we see different uses of the Tuple and Tuple2 classes:

Continue reading →

Groovy Goodness: New Methods to Sort and Remove Duplicates From Collection

Posted on by  
Hubert Klein Ikkink

In Groovy we can use the sort and unique methods to sort a collection or remove duplicates from a collection. These methods alter the collection on which they are invoked. This is a side effect we might want to avoid. Therefore the sort and unique methods where changed and we could pass a boolean argument to indicate if the original collection should be changed or that we must have a new collection as the result of the methods, leaving the original collection untouched. Since Groovy 2.4 we have two new methods which by default return a new collection: toSorted and toUnique.

In the following sample we see the new methods in action:

Continue reading →

Gr8Conf 2014 Europe Conference Report

Posted on by  
Hubert Klein Ikkink

Gr8Conf 2014 in Copenhagen has been great. Three days filled with very informative talks, learning the latest from the Groovy community and mostly meeting all the people involved with the Groovy community, both project leads, members and users.

As always the first day of the conference is a university day with workshops that take 3 hours. This format is more of a hands-on experience. The day started with a Getting Groovy workshop to learn Groovy and play around with the language given by myself (Hubert Klein Ikkink).  Notes and the presentation can be found at Github. The following session we attended was Creating RESTful API's with Grails and Spring Security by Alvaro Sanchez-Mariscal.  After some startup problems, we were running out of time, so he did a live coding session. Where a rest service was created and login functionality added. I got some good ideas for our upcoming rest workshop. The final session of the day was really about playing: Getting Groovy With Lego Mindstorms EV3 by Ryan Vanderwerf. Ryan gave a small introduction about leJOS as an operating system for the Mindstorm computers, capable of running Java code. But we can also use Groovy and run the compiled classes on a Mindstorm computer. It is good to use the @CompileStatic annotation, because otherwise the application will be to slow to run. After the introduction Ryan had five Mindstorm sets we could play with. It was fun to write little code snippets with actions for the Mindstorm 'robot' to execute and then upload them to the Mindstorm computer and see the results. This was really fun and the Groovy support can be even extended by including builders for instruction. The project is open source and we can all contribute. Code from the talk is available at Github. At the same time the workshop about Unleashing the power of AST transformations by Cédric Champeau started.  The great thing about AST transformations is that you can change the bytecode, so non-groovy languages can use it. There are multiple phases where you can use your transformation, depending on what you want. These were some hard exercises. Homework! The workshop is also available online.

Continue reading →

Groovy Goodness: Extra Methods for NIO Path

Posted on by  
Hubert Klein Ikkink

Groovy adds a lot of extra methods to the File object to work with the contents or find and filter files in a directory. These methods are now also added to the java.nio.file.Path class since Groovy 2.3.

import java.nio.file.*

final Path newFile = Paths.get('output.txt')
if (Files.exists(newFile)) {
    Files.delete(newFile)
}


// Different ways to add content.
newFile.write 'START'
newFile.write System.getProperty('line.separator')
newFile << 'Just a line of text'
newFile.withWriterAppend { writer ->
    writer.println()
    writer.println 'END'
}


// Read contents.
final Path readFilePath = Paths.get('output.txt')

assert readFilePath.readLines().join(';') == 'START;Just a line of text;END'
assert readFilePath.filterLine { it.contains('text') }.toString().normalize() == 'Just a line of text\n'


// Work with Path objects,
// like with File GDK extensions with
// eachFile, eachDir, eachFileRecursive...
final Path root = Paths.get('.')
def paths = root.eachFileMatch(~/.*\.txt$/) {
    assert it.toFile().name == 'output.txt'
}

Continue reading →

Groovy Goodness: @DelegatesTo For Type Checking DSL

Posted on by  
Hubert Klein Ikkink

Groovy 2.1 introduced the @DelegatesTo annotation. With this annotation we can document a method and tell which class is responsible for executing the code we pass into the method. If we use @TypeChecked or @CompileStatic then the static type checker of the compiler will use this information to check at compile-time if the code is correct. And finally this annotation allows an IDE to give extra support like code completion.

Suppose we have the following class Reservation with the method submit(). The method accepts a closure with methods that need to be applied with the instance of the Reservation class. This is a very common pattern for writing simple DSLs in Groovy.

Continue reading →

Checking Parameters Mock Method Invocation in Spock

Posted on by  
Hubert Klein Ikkink

Arthur Arts wrote an blog post about Using ArgumentCaptor for generic collections with Mockito. With the ArgumentCaptor in Mockito the parameters of a method call to a mock are captured and can be verified with assertions. In Spock we can also get a hold on the arguments that are passed to a method call of a mock and we can write assertions to check the parameters for certain conditions. When we create a mock in Spock and invoke a method on the mock the arguments are matched using the equals() implementation of the argument type. If they are not equal Spock will tell us by showing a message that there are too few invocations of the method call. Let’s show this with an example. First we create some classes we want to test:

package com.jdriven.spock

class ClassUnderTest {

    private final Greeting greeting

    ClassUnderTest(final Greeting greeting) {
        this.greeting = greeting
    }

    String greeting(final List<Person> people) {
        greeting.sayHello(people)
    }
}

package com.jdriven.spock

interface Greeting {
    String sayHello(final List<Person> people)
}

package com.jdriven.spock

@groovy.transform.Canonical
class Person {
    String name
}

Continue reading →

Change return value of mocked or stubbed service based on argument value with Spock

Posted on by  
Hubert Klein Ikkink

Albert van Veen wrote a blog post about Using ArgumentMatchers with Mockito. The idea is to let a mocked or stubbed service return a different value based on the argument passed into the service. This is inspired me to write the same sample with Spock. Spock already has built-in mock and stub support, so first of all we don’t need an extra library to support mocking and stubbing. We can easily create a mock or stub with the Mock() and Stub() methods. We will see usage of both in the following examples. In the first example we simply return true or false for ChocolateService.doesCustomerLikesChocolate() in the separate test methods.

import spock.lang.*

public class CandyServiceSpecification extends Specification {

    private ChocolateService chocolateService = Mock()
    private CandyService candyService = new CandyServiceImpl()

    def setup() {
        candyService.chocolateService = chocolateService
    }

    def "Customer Albert really likes chocolate"() {
        given:
        final Customer customer = new Customer(firstName: 'Albert')

        and: 'Mock returns true'
        1 * chocolateService.doesCustomerLikesChocolate(customer) >> true

        expect: 'Albert likes chocolate'
        candyService.getCandiesLikeByCustomer(customer).contains Candy.CHOCOLATE
    }

    def "Other customer do not like chocolate"() {
        given:
        final Customer customer = new Customer(firstName: 'Any other firstname')

        and: 'Mock returns false'
        1 * chocolateService.doesCustomerLikesChocolate(customer) >> false

        expect: 'Customer does not like chocolate'
        !candyService.getCandiesLikeByCustomer(customer).contains(Candy.CHOCOLATE)
    }

}

Continue reading →

Groovy Goodness: Pretty Print XML

Posted on by  
Hubert Klein Ikkink

The easiest way to pretty print an XML structure is with the [XmlUtil](http://groovy.codehaus.org/api/groovy/xml/XmlUtil.html) class. The class has a serialize() method which is overloaded for several parameter types like String, GPathResult and Node. We can pass an OutputSteam or Writer object as argument to write the pretty formatted XML to. If we don't specify these the serialize() method return a String value.

import groovy.xml.*

def prettyXml = '''
<?xml version="1.0" encoding="UTF-8"?>
<languages>
  <language id="1">Groovy</language>
  <language id="2">Java</language>
  <language id="3">Scala</language>
</languages>
'''


// Pretty print a non-formatted XML String.
def xmlString = '<languages><language id="1">Groovy</language><language id="2">Java</language><language id="3">Scala</language></languages>'
assert XmlUtil.serialize(xmlString) == prettyXml

// Use Writer object as extra argument.
def xmlOutput = new StringWriter()
XmlUtil.serialize xmlString, xmlOutput
assert xmlOutput.toString() == prettyXml

// Pretty print a Node.
Node languagesNode = new XmlParser().parseText(xmlString)
assert XmlUtil.serialize(languagesNode) == prettyXml


// Pretty print a GPathResult.
def langagesResult = new XmlSlurper().parseText(xmlString)
assert XmlUtil.serialize(langagesResult) == prettyXml


// Pretty print org.w3c.dom.Element.
org.w3c.dom.Document doc = DOMBuilder.newInstance().parseText(xmlString)
org.w3c.dom.Element root = doc.documentElement
assert XmlUtil.serialize(root) == prettyXml


// Little trick to pretty format
// the result of StreamingMarkupBuilder.bind().
def languagesXml = {
    languages {
        language id: 1, 'Groovy'
        language id: 2, 'Java'
        language id: 3, 'Scala'
    }
}
def languagesBuilder = new StreamingMarkupBuilder()
assert XmlUtil.serialize(languagesBuilder.bind(languagesXml)) == prettyXml

Continue reading →

Grassroots Groovy: Parse XML with XmlSlurper from Java

Posted on by  
Hubert Klein Ikkink

We can introduce Groovy into our Java projects at grassroots level. Even if we aren't allowed to run the Groovy compiler we can use other ways to run Groovy code. As long as we can include the Groovy libraries as a compile dependency than we can already use Groovy from Java. In this post we see how we can use the power of XmlSlurper to parse XML from our Java code.

To execute a Groovy script from we can use a GroovyShell object and invoke the evaluate() method. The evaluate() method can parse a Groovy script as File or Reader object. We can also use a String value to be evaluated. The last statement of the script that is evaluated can be assigned to a Java variable. To pass variables to the script we use the Binding object. This is a map of variables and their values. We assign values to the variables in the Java code and in the Groovy script we can use the variable values.

Continue reading →

Groovy Goodness: Create a List with Default Values

Posted on by  
Hubert Klein Ikkink

Since Groovy 1.8.7 we can create a list and use the withDefault() method to define a default value for elements that are not yet in the list. We use a closure as argument of the method, which returns the default value. We can even access the index of the element in the closure as an argument.

Besides the withDefault() method we can use the withLazyDefault() which is just another name for the same functionality. If we request a value for an index that is greater or equal to the size of the list, the list will automatically grow up to the specified index. Any gaps are filled with the value null.

Continue reading →

shadow-left