Posts by Hubert Klein Ikkink

Groovy Goodness: Using Builder to Create Fluent API for Other Classes

Posted on by  
Hubert Klein Ikkink

In a previous post we learned about the new @Builder AST transformation introduced in Groovy 2.3. We applied to the annotation to our class files and we got a nice fluent API to set property values. But what if we cannot change the class itself, for example if we want to create a fluent API for classes in an external library. Then we can still use the @Builder AST transformation but we use a different strategy. We can define the builder strategy via a annotation parameter.

In the following sample we assume the Message class is from an external library and we cannot or do not want to change the class definition. We create a new Groovy class and set the @Builder annotation on this new class. We use the annotation parameters builderStrategy to indicate the generated code is not for the new class, but for the class set with the annotation parameter forClass.

Continue reading →

Groovy Goodness: Use Builder AST Transformation for Fluent API

Posted on by  
Hubert Klein Ikkink

Since Groovy 2.3 we can easily create a fluent API for our classes with the @Builder AST transformation. We can apply the annotation to our classes and the resulting class file will have all the necessary methods to support a fluent API. We can customize how the fluent API is generated with different annotation parameters. In Groovy code we already can use the with method to have a clean way to set property values or use the named constructor arguments. But if our classes need to be used from Java it is nice to give the Java developers a fluent API for our Groovy classes.

In the following sample we apply the @Builder annotation to a simple class Message with some properties. We leave everything to the default settings and then the resulting Message class file will have a new builder method that return an internal helper class we can use to set our properties. For each property their is a new method with the name of the property so we can set a value. And finally our class contains a build that will return a new instance of the Message class with the correct values for the properties.

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: More Efficient Tail Recursion With TailRecursive Annotation

Posted on by  
Hubert Klein Ikkink

Since Groovy 1.8 we can use the trampoline method for a closure to get better recursive behavior for tail recursion. All closure invocations are then invoked sequentially instead of stacked, so there is no StackOverFlowError. As from Groovy 2.3 we can use this for recursive methods as well with the @TailRecursive AST transformation. If we apply the annotation to our method with tail recursion the method invocations will be sequential and not stacked, like with the closure's trampoline method.

import groovy.transform.TailRecursive

@TailRecursive
long sizeOfList(list, counter = 0) {
    if (list.size() == 0) {
        counter
    } else {
       sizeOfList(list.tail(), counter + 1)
    }
}

// Without @TailRecursive a StackOverFlowError
// is thrown.
assert sizeOfList(1..10000) == 10000

Continue reading →

Awesome Asciidoc: Explain Code with Callouts

Posted on by  
Hubert Klein Ikkink

Writing documentation with Asciidoc is such a treat. We can add markers to our code where we want to explain something in our code. The markers have numbers and are enclosed in < and > brackets. The explanation for the markers follows a code listing in a callout list. Here we use the same marker and add extra text to explain the code. We can put the markers in comments in our code so we can use the markers in existing code.

Suppose we have the following piece of documentation where we add two markers (in comments) to some Groovy source code:

Continue reading →

Grails Goodness: Using Aliases as Command Shortcuts

Posted on by  
Hubert Klein Ikkink

In Grails we can add aliases for standard Grails commands with the alias command. For example we want to use another name for a command or combine a command with arguments to a single alias. With the following command we create a start-app alias for the standard run-app command:

$ grails alias start-app run-app
Alias start-app with value run-app configured
$

Continue reading →

Awesome Asciidoc: Include Partial Parts from Code Samples

Posted on by  
Hubert Klein Ikkink

Writing technical documentation with Asciidoc and Asciidoctor is so much fun. Especially the include macro makes inserting changing content, like source files, a breeze. We only need to maintain the original source file and changes will automatically appear in the generated documentation. We can include only a part of source file using tags. In the source file we add a comment with the following format tag::_tagName_[] to start the section. We end the section with end::_tagName_[]. Now in our Asciidoc document we can indicatie the tags we want to include with include::_sourceFile_[tags=_tagName_].

Suppose we have the following Groovy source file Sample.groovy. We want to include the method hello() in our technical documentation:

Continue reading →

Groovy Goodness: Define Compilation Customizers With Builder Syntax

Posted on by  
Hubert Klein Ikkink

Since Groovy 2.1 we can use a nice builder syntax to define customizers for a CompileConfiguration instance. We must use the static withConfig method of the class CompilerCustomizationBuilder in the package org.codehaus.groovy.control.customizers.builder. We pass a closure with the code to define and register the customizers. For all the different customizers like ImportCustomizer, SecureASTCustomizers and ASTTransformationCustomizer there is a nice compact syntax.

In the following sample we use this builder syntax to define different customizers for a CompileConfiguration instance:

Continue reading →

Groovy Goodness: Restricting Script Syntax With SecureASTCustomizer

Posted on by  
Hubert Klein Ikkink

Running Groovy scripts with GroovyShell is easy. We can for example incorporate a Domain Specific Language (DSL) in our application where the DSL is expressed in Groovy code and executed by GroovyShell. To limit the constructs that can be used in the DSL (which is Groovy code) we can apply a SecureASTCustomizer to the GroovyShell configuration. With the SecureASTCustomizer the Abstract Syntax Tree (AST) is inspected, we cannot define runtime checks here. We can for example disallow the definition of closures and methods in the DSL script. Or we can limit the tokens to be used to just a plus or minus token. To have even more control we can implement the StatementChecker and ExpressionChecker interface to determine if a specific statement or expression is allowed or not.

In the following sample we first use the properties of the SecureASTCustomizer class to define what is possible and not within the script:

Continue reading →

Groovy Goodness: Customize ToString Creation

Posted on by  
Hubert Klein Ikkink

The @ToString AST transformation has several parameters we can define to customize the generated code for the toString method. We have already seen some of the parameters in an earlier blog post, but in new Groovy releases some extra parameters were added.

For example we can leave out the package name of the class with the parameter includePackage. If we set the value to false the package name is not included:

Continue reading →

Grails Goodness: Extending IntegrateWith Command

Posted on by  
Hubert Klein Ikkink

We can extend the integrate-with command in Grails to generate files for a custom IDE or build system. We must add a _Events.groovy file to our Grails projects and then write an implementation for the eventIntegrateWithStart event. Inside the event we must define a new closure with our code to generate files. The name of the closure must have the following pattern: binding.integrate_CustomIdentifier_. The value for CustomIdentifier can be used as an argument for the integrate-with command.

Suppose we want to extend integrate-with to generate a simple Sublime Text project file. First we create a template Sublime Text project file where we define folders for a Grails application. We create the folder src/ide-support/sublimetext and add the file grailsProject.sublimetext-project with the following contents:

Continue reading →

shadow-left