Loading...

Thursday, May 26, 2016

Groovy Goodness: Make Class Cloneable With @AutoClone

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:

import groovy.transform.AutoClone

@AutoClone
class Course {
    String name
    Date date
    Teacher teacher
}

@AutoClone
class Teacher {
    String name
}

def mrhaki =
    new Teacher(name: 'mrhaki')
    
def course = 
    new Course(
        name: 'Groovy 101',
        date: new Date() + 10,
        teacher: mrhaki)

// We make a deep copy.
def secondCourse = course.clone()
assert secondCourse != course
assert !secondCourse.is(course)
assert secondCourse.teacher != course.teacher

// Change property on cloned instance.
secondCourse.name = 'Groovy 101 2nd edition'

assert secondCourse.name == 'Groovy 101 2nd edition'
assert course.name == 'Groovy 101'

We can use the excludes annotation attribute to give a list of properties that must not be cloned:

import groovy.transform.AutoClone

// Do not clone the teacher property.
@AutoClone(excludes = ['teacher'])
class Course {
    String name
    Date date
    Teacher teacher
}

@AutoClone()
class Teacher {
    String name
}

def mrhaki =
    new Teacher(name: 'mrhaki')
    
def course = 
    new Course(
        name: 'Groovy 101',
        date: new Date() + 10,
        teacher: mrhaki)

// We make a deep copy.
def secondCourse = course.clone()
assert secondCourse != course
assert !secondCourse.is(course)
// Only the teacher property is
// a shallow copy.
assert secondCourse.teacher == mrhaki
assert secondCourse.teacher.is(mrhaki)

// Change property on teacher property on cloned instance.
secondCourse.teacher.name = 'hubert'

assert secondCourse.teacher.name == 'hubert'
assert course.teacher.name == 'hubert'

To include fields as well as properties we must set the annotation attribute includeFields to true.

If we want to invoke the default constructor of our class in the clone method we must use the clone style AutoCloneStyle.SIMPLE. In the generated clone method the constructor is invoked followed by copying the properties:

import groovy.transform.AutoClone
import static groovy.transform.AutoCloneStyle.SIMPLE

@AutoClone(style = SIMPLE)
class Course {
    String name
    Date date
    Teacher teacher
    
    static int counter
    
    Course() {
        counter++
    }
}

@AutoClone(style = SIMPLE)
class Teacher {
    String name
    
    static int counter
    
    Teacher() {
        counter++
    }
}

def mrhaki =
    new Teacher(name: 'mrhaki')
    
def course = 
    new Course(
        name: 'Groovy 101',
        date: new Date() + 10,
        teacher: mrhaki)
        
def otherCourse = course.clone()

// Constructor is invoked twice:
// once by ourselves to create a 
// course, the other by the clone()
// method added by @AutoClone.
assert course.counter == 2
assert course.teacher.counter == 2

The last clone style we can choose is AutoCloneStyle.COPY_CONSTRUCTOR. This time the annotation will add a protected constructor that takes another object of the same type as argument. This new constructor is used in the generated clone method. This style is useful if we have final read-only properties that can only be set via the constructor:

import groovy.transform.AutoClone
import static groovy.transform.AutoCloneStyle.COPY_CONSTRUCTOR

@AutoClone(style = COPY_CONSTRUCTOR)
class Course {
    final String name
    final Date date
    final Teacher teacher
    
    Course(
        final String name,
        final Date date,
        final Teacher teacher) {
        
        this.name = name
        this.date = date
        this.teacher = teacher
    }
}

@AutoClone(style = COPY_CONSTRUCTOR)
class Teacher {
    final String name
    
    Teacher(final String name) {
        this.name = name
    }
}

def mrhaki =
    new Teacher('mrhaki')
    
def course = 
    new Course(
        'Groovy 101',
        new Date() + 10,
        mrhaki)
        
def secondCourse = course.clone()
assert secondCourse != course
assert !secondCourse.is(course)
assert secondCourse.teacher != mrhaki
assert !secondCourse.teacher.is(mrhaki)

This annotation was already available since Groovy 1.8.

Written with Groovy 2.4.6.

Tuesday, May 17, 2016

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

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:

// Create new FileTreeBuilder. Default the current
// directory is the base directory for creating new
// files and directories.
// We can pas another directory in the constructor as
// the base directory.
final FileTreeBuilder treeBuilder = new FileTreeBuilder(new File('tree'))

// Add a file and set the contents using
// a closure. The delegate of the closure
// is the File object.
treeBuilder.file('README.adoc') {
    write '''\
        = Groovy rocks!

        Hidden features in Groovy are also cool.

        '''.stripIndent()
}

// Append to file contents with a String argument.
treeBuilder.file('README.adoc', '== Extra heading')

final File sample = new File('sample')
sample.text = '''\
= Another sample

Testing the Groovy FileTreeBuilder.
'''

// Or we use another File's contents to append to a file.
treeBuilder.file('README1.adoc', sample)

// Create a new directory.
treeBuilder.dir('out')

// Create subdirectories and files
// using a closure. The delegate is
// is FileTreeBuilder again.
treeBuilder.dir('src') {
    dir('docs') {
        file('manuscript.adoc') {
            // Another way to write file contents.
            withWriter('UTF-8') { writer ->
                writer.write '= Building Apps With Grails 3'
            }
        }
    }
}

assert new File('tree/README.adoc').exists()
assert new File('tree/src/docs/manuscript.adoc').exists()
assert new File('tree/src/docs/manuscript.adoc').text == '= Building Apps With Grails 3'

We can achieve the same result using a more compact DSL. The FileTreeBuilder will determine if a directory or file needs to be created. Notice that contents is always append to a file:

// We can even use a shorter syntax with the
// FileTreeBuilder where the node names are the name
// of a directory to be created (argument is a closure),
// or the name of a file and some contents.
// Notice that with the DSL all file contents is
// appended to existing file contents.
// We need to delete an existing file first if we
// don't want to append the contents.

final File newDir = new File('dsl')

// Remove existing dir, so file contents is
// only set by the FileTreeBuilder DSL,
// otherwise content is added to the existing files.
if (newDir.exists()) {
    newDir.deleteDir()
}

newDir.mkdirs()
final FileTreeBuilder dir = new FileTreeBuilder(newDir)

dir {
    // Node name is the file name, followed by the contents.
    'README.adoc'('''\
        = Groovy rocks!

        Hidden features in Groovy are also cool.

        '''.stripIndent())

    'README.adoc'('== Extra heading')

     // We cannot use a closure argument with this DSL,
     // like with the builder. The DSL assume that a node with a
     // closure is a directory.
     // But we can use the File object argument to set
     // the file contents.
    'README1.adoc'(sample)
}

// If name is follwed by closure than a directory
// name is assumed and created.
dir.out {}

// Created directory with subdirectories.
dir.src {
    // The name of the node is the directory name.
    docs {
        // And create file in the src/docs directory.
        'manuscript.adoc'('= Building Apps With Grails 3')
    }
}

assert new File('dsl/README.adoc').exists()
assert new File('dsl/src/docs/manuscript.adoc').exists()
assert new File('dsl/src/docs/manuscript.adoc').text == '= Building Apps With Grails 3'

Written with Groovy 2.4.6.

Thursday, May 12, 2016

Grails Goodness: Running Tests Continuously

When we write software it is good practice to also write tests. Either before writing actual code or after, we still need to write tests. In Grails we can use the test-app command to execute our tests. If we specify the extra option -continuous Grails will monitor the file system for changes in class files and automatically compiles the code and executes the tests again. This way we only have to start this command once and start writing our code with tests. If we save our files, our code gets compiled and tested automatically. We can see the output in the generated HTML report or on the console.

Suppose we have our Grails interactive shell open and we type the following command:

grails> test-app -continuous
| Started continuous test runner. Monitoring files for changes...
grails>

Written with Grails 3.1.6.

Wednesday, May 11, 2016

Grails Goodness: Use Random Server Port In Integration Tests

Because Grails 3 is based on Spring Boot we can use a lot of the functionality of Spring Boot in our Grails applications. For example we can start Grails 3 with a random available port number, which is useful in integration testing scenario's. To use a random port we must set the application property server.port to the value 0. If we want to use the random port number in our code we can access it via the @Value annotation with the expression ${local.server.port}.

Let's create a very simple controller with a corresponding integration test. The controller is called Sample:

// File: grails-app/controllers/mrhaki/SampleController.groovy
package mrhaki

class SampleController {

    def index() { 
        respond([message: 'Grails 3 is awesome!'])
    }
}

We write a Spock integration test that will start Grails and we use the HTTP Requests library to access the /sample endpoint of our application.

// File: src/integration-test/groovy/mrhaki/SampleControllerIntSpec.groovy
package mrhaki

import com.budjb.httprequests.HttpClient
import com.budjb.httprequests.HttpClientFactory
import grails.test.mixin.integration.Integration
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.beans.factory.annotation.Value
import spock.lang.Specification

@Integration
class SampleControllerIntSpec extends Specification {
    
    /**
     * Server port configuration for Grails test 
     * environment is set to server.port = 0, which
     * means a random available port is used each time
     * the application starts.
     * The value for the port number is accessible
     * via ${local.server.port} in our integration test.
     */
    @Value('${local.server.port}')
    Integer serverPort

    /**
     * HTTP test client from the HTTP Requests library:
     * http://budjb.github.io/http-requests/latest
     */
    @Autowired
    HttpClientFactory httpClientFactory

    private HttpClient client

    def setup() {
        // Create HTTP client for testing controller.
        client = httpClientFactory.createHttpClient()
    }

    void "sample should return JSON response"() {
        when:
        // Nice DSL to build a request.
        def response = client.get {
            // Here we use the serverPort variable.
            uri = "http://localhost:${serverPort}/sample"
            accept = 'application/json'
        }
        
        then:
        response.status == 200
        
        and:
        final Map responseData = response.getEntity(Map)
        responseData.message == 'Grails 3 is awesome!'
    }
}

Finally we add the server.port to the application configuration:

# File: grails-app/conf/application.yml
...
environments:
    test:
        server:
            port: 0 # Random available port
...

Let's run the integration test: $ grails test-app mrhaki.SampleControllerIntSpec -integration. When we open the test report and look at the standard output we can see that a random port is used:

Written with Grails 3.1.6.

Gradle Goodness: Get Property Value With findProperty

Gradle 2.13 added a new method to get a property value: findProperty. This method will return a property value if the property exists or null if the property cannot be found. Gradle also has the property method to return a property value, but this method will throw an exception if the property is missing. With the new findProperty method and the Groovy elvis operator (?:) we can try to get a property value and if not found return a default value.

In the following example we have a task that tries to print the value of the properties sampleOld and sampleNew. We use the findProperty for sampleNew and the property method for sampleOld:

// File: build.gradle
task resolveProperties << {
    println "sampleOld -> ${project.hasProperty('sampleOld') ? project.property('sampleOld') : 'default value for sampleOld'}"
    println "sampleNew -> ${project.findProperty('sampleNew') ?: 'default value for sampleNew'}"
}

First run the task and not set the project properties sampleOld and sampleNew:

$ gradle -q resolveProperties
sampleOld -> default value for sampleOld
sampleNew -> default value for sampleNew
$

Next we use the -P command line option to set a value for the properties:

$ gradle -q -PsampleOld="Value sampleOld" -PsampleNew="Value sampleNew" resolveProperties
sampleOld -> Value sampleOld
sampleNew -> Value sampleNew
$

Written with Gradle 2.13.

Grails Goodness: Change Version For Dependency Defined By BOM

Since Grails 3 we use Gradle as the build system. This means we also use Gradle to define dependencies we need. The default Gradle build file that is created when we create a new Grails application contains the Gradle dependency management plugin via the Gradle Grails plugin. With the dependency management plugin we can import a Maven Bill Of Materials (BOM) file. And that is exactly what Grails does by importing a BOM with Grails dependencies. A lot of the versions of these dependencies can be overridden via Gradle project properties.

To get the list of version properties we write a simple Gradle task to print out the values:

// File: build.gradle
...
task dependencyManagementProperties << {
    description = 'Print all BOM properties to the console'

    // Sort properties and print to console.
    dependencyManagement
        .importedProperties
        .toSorted()
        .each { property -> println property }
}
...

When we run the task we get an overview of the properties:

$ gradle dependencyManagementProperties
:dependencyManagementProperties
activemq.version=5.12.3
antlr2.version=2.7.7
artemis.version=1.1.0
aspectj.version=1.8.8
atomikos.version=3.9.3
bitronix.version=2.1.4
cassandra-driver.version=2.1.9
commons-beanutils.version=1.9.2
commons-collections.version=3.2.2
commons-dbcp.version=1.4
commons-dbcp2.version=2.1.1
commons-digester.version=2.1
commons-pool.version=1.6
commons-pool2.version=2.4.2
crashub.version=1.3.2
derby.version=10.12.1.1
dropwizard-metrics.version=3.1.2
ehcache.version=2.10.1
elasticsearch.version=1.5.2
embedded-mongo.version=1.50.2
flyway.version=3.2.1
freemarker.version=2.3.23
gemfire.version=8.1.0
glassfish-el.version=3.0.0
gradle.version=1.12
groovy.version=2.4.6
gson.version=2.3.1
h2.version=1.4.191
...
BUILD SUCCESSFUL

Total time: 1.316 secs

For example if we want to change the version of the PostgreSQL JDBC driver that is provided by the BOM we only have to set the Gradle project property postgresql.version either in our build file or in the properties file gradle.properties:

// File: build.gradle
...
// Change version of PostgreSQL driver
// defined in the BOM.
ext['postgresql.version'] = '9.4.1208'
...
dependencies {
    ...
    // We don't have to specify the version
    // of the dependency, because it is 
    // resolved via the dependency management
    // plugin.
    runtime 'org.postgresql:postgresql'
}
...

Another way to change the version for a dependency defined in the BOM is to include a dependency definition in the dependencyManagement configuration block. Let's see what it looks like for our example:

// File: build.gradle
...
dependencyManagement {
    imports {
        mavenBom "org.grails:grails-bom:$grailsVersion"
    }
    dependencies {
        // Dependencies defined here overrule the
        // dependency definition from the BOM.
        dependency 'org.postgresql:postgresql:9.4.1208'
    }
    applyMavenExclusions false
}

dependencies {
    ...
    // We don't have to specify the version
    // of the dependency, because it is 
    // resolved via the dependency management
    // plugin.
    runtime 'org.postgresql:postgresql'
}
...

To see the actual version that is used we can run the task dependencyInsight:

$ gradle dependencyInsight --dependency postgres --configuration runtime
:dependencyInsight
org.postgresql:postgresql:9.4.1208 (selected by rule)

org.postgresql:postgresql: -> 9.4.1208
\--- runtime

BUILD SUCCESSFUL

Total time: 1.312 secs

This is just another nice example of the good choice of the Grails team to use Gradle as the build system.

Written with Grails 3.1.6

Friday, March 18, 2016

Gradle Goodness: Source Sets As IntelliJ IDEA Modules

IntelliJ IDEA 2016.1 introduced better support for Gradle source sets. Each source set in our project becomes a module in the IntelliJ IDEA project. And each module has it's own dependencies, also between source sets. For example if we simply apply the java plugin in our project we already get two source sets: main and test. For compiling the test sources there is a dependency to the main source set. IntelliJ now knows how to handle this.

Let's create a sample Gradle build file with an extra custom source set and see what we get in IntelliJ IDEA. In the following example build file we add the source set api. This source set contains interfaces without implementations. The implementations for the interfaces are in the default main source set. Finally we have some tests in the test source set that depend on the classes generated by the api and main source sets.

apply plugin: 'groovy'
apply plugin: 'idea'

sourceSets {
    // Define new source set
    // with the name api. This 
    // source set contains interfaces,
    // implementation classes are in
    // the main source set.
    api
}

repositories {
    jcenter()
}

dependencies {

    // The default source set main
    // has a compile dependency on the 
    // output of the api source set.
    // Gradle will invoke the apiClasses
    // task automatically if we compile
    // the sources in the main source set.
    compile sourceSets.api.output
    
    testCompile 'org.spockframework:spock-core:1.0-groovy-2.4'
}

When we invoke the idea task to generate the IntelliJ IDEA project files or we import the build.gradle file into IDEA we can see in the Gradle tool window a new element: Source Sets. When we open the node we see all the source sets in our project with their dependencies:

When we right click on the project and select Open Module Settings we get a new dialog window. All source sets are separate modules grouped into a single module. In our example the module group is idea-sourcesets and it has three modules. If we click on the idea-sourcesets_test and select the Dependencies tab we see a list of dependencies for the source set:

Written with Gradle 2.12 and IntelliJ IDEA 2016.1.

Wednesday, March 16, 2016

Gradle Goodness: Enable Compiler Annotation Processing For IntelliJ IDEA

Suppose we have a project where we use Lombok annotations. To use it we must change the compiler configuration for our project and enable annotation processing. We can find this in the Preferences or Settings window under Build, Execution, Deployment | Compiler | Annotation Processors. Here we have a checkbox Enable annotation processing that we must check to use the annotations from IntelliJ IDEA. We can automate this setting with some configuration in our Gradle build file.

In the next example build file we alter the generated IntelliJ IDEA project file using the withXml hook. We can access the generated XML as a groovy.util.Node and change the XML.

// File: build.gradle
apply plugin: 'groovy'
apply plugin: 'idea'

repositories {
    jcenter()
}

dependencies {
    compile('org.projectlombok:lombok:1.16.6')
}

idea {
    project {
        ipr {
            withXml { provider ->
                // Get XML as groovy.util.Node to work with.
                def projectXml = provider.asNode()
                
                // Find compiler configuration component.
                def compilerConfiguration = projectXml.component.find { component ->
                    component.'@name' == 'CompilerConfiguration'
                }
                
                // Replace current annotationProcessing
                // that is part of the compiler configuration.
                def currentAnnotationProcessing = compilerConfiguration.annotationProcessing
                currentAnnotationProcessing.replaceNode {
                    annotationProcessing {
                        profile(name: 'Default', default: true, enabled: true) {
                            processorPath(useClasspath: true)
                        }
                    }
                }
            }
        }
    }
}

Written with Gradle 2.12 and IntelliJ IDEA 15.

Gradle Goodness: Add Spring Facet To IntelliJ IDEA Module

To create IntelliJ IDEA project files with Gradle we first need to apply the idea plugin. We can then further customise the created files. In this blog post we will add a Spring facet to the generated module file. By adding the Spring facet IntelliJ IDEA can automatically search for Spring configuration files. We can then use the Spring view to see which beans are configured in our project.

In the following example build file we use the withXml hook. This method is invoked just before the XML file is generated. We get an argument of type XmlProvider. From the XmlProvider we can access the XML as org.w3c.dom.Element, StringBuilder or groovy.util.Node. We use Node to alter the XML. We check if a FacetManager component is available. We need this to add a facet of type Spring.

// File: build.gradle
apply plugin: 'groovy'
apply plugin: 'idea'

idea {
    module {
        iml {
            withXml { 
                // Get root of module as groovy.util.Node.
                def moduleRoot = it.asNode()
                
                // Find if component with name 'FacetManager'
                // is already set.
                def facetManager = moduleRoot.component.find { component -> component.'@name' == 'FacetManager'}
                if (!facetManager) {
                    // Create new component with name 'FacetManager'
                    facetManager = moduleRoot.appendNode('component', [name: 'FacetManager'])
                }
                
                // Find Spring facet it might already be there.
                def springFacet = facetManager.facet.find { facet -> facet.'@type' == 'Spring' && facet.'@name' == 'Spring' }
                if (!springFacet) {
                    // If not set create new facet node with name 'Spring'
                    // and type 'Spring' and apply a default configuration.
                    springFacet = facetManager.appendNode('facet', [type: 'Spring', name: 'Spring'])
                    springFacet.appendNode('configuration')
                }
            }
        }
    }
}

Written with Gradle 2.12 and IntelliJ IDEA 15.

Gradle Goodness: Set VCS For IntelliJ IDEA In Build File

When we use the IDEA plugin in Gradle we can generate IntelliJ IDEA project files. We can customise the generated files in different ways. One of them is using a simple DSL to configure certain parts of the project file. With the DSL it is easy to set the version control system (VCS) used in our project.

In the next example build file we customise the generated IDEA project file and set Git as the version control system. The property is still incubating, but we can use it to have a proper configuration.

// File: build.gradle
apply plugin: 'groovy'
apply plugin: 'idea'

idea {
    project {
        // Set the version control system
        // to Git for this project.
        // All values IntelliJ IDEA supports
        // can be used. E.g. Subversion, Mercurial.
        vcs = 'Git'
    }
}

Written with Gradle 2.12 and IntelliJ IDEA 15.