Posts by Hubert Klein Ikkink

Grails Goodness: Change Response Formats in RestfulController

Posted on by  
Hubert Klein Ikkink

We can write a RESTful application with Grails and define our API in different ways. One of them is to subclass the grails.rest.RestfulController. The RestfulController already contains a lot of useful methods to work with resources. For example all CRUD methods (save/show/update/delete) are available and are mapped to the correct HTTP verbs using a URL mapping with the resource(s) attribute.

We can define which content types are supported with the static variable responseFormats in our controller. The variable should be a list of String values with the supported formats. The list of supported formats applies to all methods in our controller. The names of the formats are defined in the configuration property grails.mime.types. We can also use a Map notation with the supportedFormats variable. The key of the map is the method name and the value is a list of formats.

Continue reading →

Grails Goodness: Enable Accept Header for User Agent Requests

Posted on by  
Hubert Klein Ikkink

Especially when we use Grails to create a RESTful API we want to enable the request header Accept, so Grails can do content negotiation based on the value in the header. For example we could use the request header Accept: application/json to get a JSON response. Grails will look at the boolean configuration property grails.mime.use.accept.header to see if the Accept header must be parsed. The default value is true so the Accept header is used. But there is another property which determines if the Accept header is used: grails.mime.disable.accept.header.userAgents. The value must contain a list or a regular expression pattern of user agents which are ignored for the Accept header. The default value is ~/(Gecko(?i)|WebKit(?i)|Presto(?i)|Trident(?i))/. So for any request from these user agents, mostly our web browser, the Accept header is ignored.

If we use REST web services test tools from our browser, for example Postman, then any Accept header we set in the tool is ignored by Grails. We must change the value of the configuration property grails.mime.disable.accept.header.userAgents to for example an empty list. Then we know for every request send to our Grails application, either from a web browser or command-line tool like curl, the Accept header is interpreted by Grails.

Continue reading →

Spocklight: Write Our Own Data Provider

Posted on by  
Hubert Klein Ikkink

We can use data pipes to write data driven tests in Spock. A data pipe (<<) is fed by a data provider. We can use Collection objects as data provider, but also String objects and any class that implements the Iterable interface. We can write our own data provider class if we implement the Iterable interface.

In the following sample code we want to test the female property of the User class. We have the class MultilineProvider that implements the Iterable interface. The provider class accepts a multiline String value and returns the tokenized result of each line in each iteration.

Continue reading →

Spocklight: Assign Multiple Data Variables from Provider

Posted on by  
Hubert Klein Ikkink

We can write data driven tests with Spock. We can specify for example a data table or data pipes in a where: block. If we use a data pipe we can specify a data provider that will return the values that are used on each iteration. If our data provider returns multiple results for each row we can assign them immediately to multiple variables. We must use the syntax [var1, var2, var3] << providerImpl to assign values to the data variables var1, var2 and var3. We know from Groovy the multiple assignment syntax with parenthesis ((var1, var2, var3)), but with Spock we use square brackets.

In the following sample specification we have a simple feature method. The where: block shows how we can assign the values from the provider to multiple data variables. Notice we can skip values from the provider by using a _ to ignore the value.

Continue reading →

Spocklight: Ignore Specifications Based On Conditions

Posted on by  
Hubert Klein Ikkink

We can use the @Ignore and @IgnoreRest annotation in our Spock specifications to not run the annotated specifications or features. With the @IgnoreIf annotation we can specify a condition that needs to evaluate to true to not run the feature or specification. The argument of the annotation is a closure. Inside the closure we can access three extra variables: properties (Java system properties), env (environment variables) and javaVersion.

In the following Spock specification we have a couple of features. Each feature has the @IgnoreIf annotation with different checks. We can use the extra variables, but we can also invoke our own methods in the closure argument for the annotation:

Continue reading →

Spocklight: Extra Data Variables for Unroll Description

Posted on by  
Hubert Klein Ikkink

Spock's unroll feature is very powerful. The provider data variables can be used in the method description of our specification features with placeholders. For each iteration the placeholders are replaced with correct values. This way we get a nice output where we immediately can see the values that were used to run the code. Placeholders are denoted by a hash sign (#) followed by the variable name. We can even invoke no-argument methods on the variable values or access properties. For example if we have a String value we could get the upper case value with #variableName.toUpperCase(). If we want to use more complex expressions we must introduce a new data variable in the where block. The value of the variable will be determined for each test invocation and we can use the result as a value in the method description.

package com.mrhaki.spock

import spock.lang.*

class SampleSpec extends Specification {

    @Unroll
    def "check if '#value' is lower case"() {
        expect:
        value.every { (it as char).isLowerCase() } == result

        where:
        value || result
        'A'   || false
        'Ab'  || false
        'aB'  || false
        'a'   || true
        'ab'  || true
    }

}

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 →

Easy Editing ResourceBundle Property Files in IntelliJ IDEA

Posted on by  
Hubert Klein Ikkink

We can add a resourcebundle property file to our application to support internationalization (i18n). The file contains key-value pairs where the value is a localized value per supported language or locale. In IntelliJ IDEA we can easily see which keys are not yet translated. We open a resourcebundle property file and click on the ResourceBundle tab at the bottom of the editor. We get a list of all available keys on the left and on the right a text area per supported language with the translated values. If a key is not translated for all supported languages it will be colored in red. We only have to select the keys in red and fill in the values on the right for the given languages.

Continue reading →

Grails Goodness: Run Groovy Scripts in Grails Context

Posted on by  
Hubert Klein Ikkink

We can use the run-script command to run Groovy scripts within the context of a Grails application. We can pass one or more Groovy scripts as argument to the run-script command. The Grails environment will be configured and we can access the Spring application context, domain classes, Grails services and more. Basically everything we can do in the Grails console or shell can be saved as a Groovy script and run with the run-script command.

The following Groovy script shows some stats for a Grails application:

Continue reading →

Groovy Goodness: BaseScript with Abstract Run Script Method

Posted on by  
Hubert Klein Ikkink

In a previous blog post we have seen how we can use a BaseScript AST transformation to set a base script class for running scripts. Since Groovy 2.3 we can apply the @BaseScript annotation on package and import statements. Also we can implement a run method in our Script class in which we call an abstract method. The abstract method will actually run the script, so we can execute code before and after the script code runs by implementing logic in the run method.

In the following sample we create a Script class CustomScript. We implement the run method and add the abstract method runCode:

Continue reading →

Groovy Goodness: Use Sortable Annotation to Make Classes Comparable

Posted on by  
Hubert Klein Ikkink

Since Groovy 2.3 we can use the @Sortable annotation to make a class implement the Comparable interface. Also new comparator methods are added. All properties of a class are used to implement the compareTo method. The order of the properties determines the priority used when sorting. With the annotation parameters includes and excludes we can define which properties of the class need to be used to implement the compareTo method.

In the following class with the name Course we define three properties title, beginDate and maxAttendees. We also apply the @Sortable annotation. Notice we cannot use int as a type, because it doesn't implement the Comparable interface. The class Integer does.

Continue reading →

Groovy Goodness: @Builder Definition with Extra Type Checks

Posted on by  
Hubert Klein Ikkink

We have seen some features of the @Builder AST transformation in previous and other blog post. We can use another strategy to let the AST transformation generate a class where the class only has a constructor that accepts a builder class. And with @CompileStatic we can even make sure that all required properties must have a value set by the builder before the constructor accepts the argument. We use the builderStrategy annotation parameter and set it to InitializerStrategy:

import groovy.transform.builder.Builder
import groovy.transform.builder.InitializerStrategy

@Builder(builderStrategy = InitializerStrategy)
class Message {
    String from, to, subject, body
}

def message = Message.createInitializer()
        .from('mrhaki@mrhaki.com')
        .subject('Groovy 2.3 is released')

// Returned object is not Message, but
// internal class Message$MessageInitializer
assert !(message instanceof Message)

// Now we can use the initializer in the
// only constructor of Message.
def messageInstance = new Message(message)

assert messageInstance instanceof Message
assert messageInstance.from == 'mrhaki@mrhaki.com'
assert messageInstance.subject == 'Groovy 2.3 is released'

Continue reading →

shadow-left