Posts by Hubert Klein Ikkink

Grails Goodness: Add Extra Valid Domains and Authorities for URL Validation

Posted on by  
Hubert Klein Ikkink

Grails has a built-in URL constraint to check if a String value is a valid URL. We can use the constraint in our code to check for example that the user input http://www.mrhaki.com is valid and http://www.invalid.url is not. The basic URL validation checks the value according to standards RFC1034 and RFC1123. If want to allow other domain names, for example server names found in our internal network, we can add an extra parameter to the URL constraint. We can pass a regular expressions or a list of regular expressions for patterns that we want to allow to pass the validation. This way we can add IP addresses, domain names and even port values that are all considered valid. The regular expression is matched against the so called authority part of the URL. The authority part is a hostname, colon (:) and port number.

In the following sample code we define a simple command object with a String property address. In the constraints block we use the URL constraint. We assign a list of regular expression String values to the URL constraint. Each of the given expressions are valid authorities, we want the validation to be valid. Instead of a list of values we can also assign one value if needed. If we don't want to add extra valid authorities we can simple use the parameter true.

Continue reading →

Grails Goodness: Setting Property Values through Configuration

Posted on by  
Hubert Klein Ikkink

In Grails we can define properties for services, controller, taglibs, Spring components and other components in the Spring application context through configuration. This is called property overriding in Spring terminology. This feature is very useful to define or override property values on components in the application context. We can define the property values in a beans{} block in Config.groovy. We can also load external configuration files, like property files and define property values in those.

With property overriding we don't have to look for property values via an injected GrailsApplication object and the config property of GrailsApplication. The code using the property value is now much cleaner and easier to test.

Continue reading →

Spocklight: Using Mock Method Arguments in Response

Posted on by  
Hubert Klein Ikkink

When we mock or stub methods we can use the method arguments passed to the method in the response for the mocked or stubbed method. We must write a closure after the rightShift operator (>>) and the closure arguments will resemble the arguments of the mocked or stubbed method. Alternatively we can use a single non-typed argument in the closure and this will contains the method argument list.

Let's create a specification where we use this feature. In the following sample we use a mock for the AgeService used in the class under test. The method allowedMaxTime() is invoked by the class under test and basically should return the maximum hour of the day a show can be broadcasted. In our specification we use the name of the show to return different values during the test.

Continue reading →

Grails Goodness: Unit Testing Render Templates from Controller

Posted on by  
Hubert Klein Ikkink

In a previous blog post we learned how we can unit test a template or view independently. But what if we want to unit test a controller that uses the render() method and a template with the template key instead of a view? Normally the view and model are stored in the modelAndView property of the response. We can even use shortcuts in our test code like view and model to check the result. But a render() method invocation with a template key will simply execute the template (also in test code) and the result is put in the response. With the text property of the response we can check the result.

In the following sample controller we use the header template and pass a username model property to render output.

Continue reading →

Grails Goodness: Render Binary Output with the File Attribute

Posted on by  
Hubert Klein Ikkink

Since Grails 2 we can render binary output with the render() method and the file attribute. The file attribute can be assigned a byte[], File, InputStream or String value. Grails will try to determine the content type for files, but we can also use the contentType attribute to set the content type.

In the following controller we find an image in our application using grailsResourceLocator. Then we use the render() method and the file and contenType attributes to render the image in a browser:

Continue reading →

Grails Goodness: Accessing Resources with Resource and ResourceLocator

Posted on by  
Hubert Klein Ikkink

Grails uses Spring and we can piggyback on the Spring support for resource loading to find for examples files in the classpath of our application. We can use the Spring org.springframework.core.io.Resource or org.springframework.core.io.ResourceLoader interface to find resources in our application.

And since Grails 2.0 we can also use the org.codehaus.groovy.grails.core.io.ResourceLocator interface. In our code we can use the grailsResourceLocator service which implements the ResourceLocator interface. We must inject the grailsResourceLocator service into our code and we use the method findResourceForURI(String) to find a resource. The advantage of the grailsResourceLocator service is that it knows about a Grails application. For example resources in plugins can also be accessed.

Continue reading →

Spocklight: Using the Old Method

Posted on by  
Hubert Klein Ikkink

Spock has some great features to write specifications or tests that are short and compact. One of them is the old() method. The old() method can only be used in a then: block. With this method we get the value a statement had before the when: block is executed.

Let's see this with a simple example. In the following specification we create a StringBuilder with an initial value. In the then: block we use the same initial value for the assertion:

Continue reading →

Grails Goodness: Set Request Locale in Unit Tests

Posted on by  
Hubert Klein Ikkink

There is really no excuse to not write unit tests in Grails. The support for writing tests is excellent, also for testing code that has to deal with the locale set in a user's request. For example we could have a controller or taglib that needs to access the locale. In a unit test we can invoke the addPreferredLocale() method on the mocked request object and assign a locale. The code under test uses the custom locale we set via this method.

In the following controller we create a NumberFormat object based on the locale in the request.

Continue reading →

Grails Goodness: Using the header Method to Set Response Headers

Posted on by  
Hubert Klein Ikkink

Grails adds a couple of methods and properties to our controller classes automatically. One of the methods is the header() method. With this method we can set a response header with a name and value. The methods accepts two arguments: the first argument is the header name and the second argument is the header value.

In the following controller we invoke the header() method to set the header X-Powered-By with the Grails and Groovy version.

Continue reading →

Groovy Goodness: Customize Log Variable Name with Log AST Annotations

Posted on by  
Hubert Klein Ikkink

To add logging to a class with Groovy is easy. We apply one of the logging AST transformations and we get a variable in our class named log. We can invoke methods on the variable and the AST transformation will also automatically wrap those statement in a "if-logging-level-is-enabled" block. The transformation is even intelligent enough to do this only if Strings are added or a GString is used. If we want to use a different name than log we simply use the value parameter of the annotation. We assign the name we want to use and then we can use it in our code.

import groovy.util.logging.*

@Log(value = 'LOGGER')
class Event {
    String name
    Boolean started

    void start() {
        LOGGER.info "Event $name is started"
        started = true
    }
}

final Event event = new Event(name: 'gr8Conf')
event.start()

Continue reading →

Gradle Goodness: Extending DSL

Posted on by  
Hubert Klein Ikkink

Gradle already has a powerful DSL, but Gradle wouldn't be Gradle if we couldn't extend the DSL ourselves. Maybe we have our own naming conventions in our company or we have a special problem domain we want to express in a Gradle build script. We can use the ExtensionContainer, available via project.extensions, to add new concepts to our build scripts. In the Standardizing your enterprise build environment webinar by Luke Daley some examples are shown on how to extend the DSL. Also in the samples folder of the Gradle distribution are examples on how to create a custom DSL.

Let's first create a simple DSL extension. We first define a new class CommonDependencies with methods to define dependencies in a Java project. We want to use these methods with descriptive names in our build scripts. To add the class we use the create() method of the ExtensionContainer. The first argument is a name that needs to be unique within the build. The name can be used together with a configuration block in the script to invoke methods on the class we pass as the second argument. Finally we can pass constructor arguments for the class as last arguments of the create() method.

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 →

shadow-left