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 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 →
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 →
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 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 →
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 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 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 →
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 →
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 →
Willem Cheizoo already wrote an blog post about How to test for an exception with JUnit and this inspired me to write the same sample with Spock. In Spock we can use the thrown()
method to check for exceptions. We can use it in a then:
block of our test.
import spock.lang.*
public class JDrivenServiceSpecification extends Specification {
private JDrivenService service = new JDrivenService()
def "publishArticle throws ArticleNotFoundException() {
when:
service.publishArticle null
then:
final ArticleNotFoundException exception = thrown()
// Alternate syntax: def exception = thrown(ArticleNotFoundException)
exception.message == 'Article not found please provide an article to publish'
}
}
Continue reading →
Since Grails 2.1 we can create a Grails wrapper. The wrapper allows developer to run Grails commands in a project without installing Grails first. The wrapper concept is also available in other projects from the Groovy ecosystem like Gradle or Griffon. A wrapper is a shell script for Windows, OSX or Linux named grailsw.bat
or grailsw
and a couple of JAR files to automatically download a specific version of Grails. We can check in the shell scripts and supporting files into a version control system and make it part of the project. Developers working on the project simply check out the code and execute the shell script. If there is no Grails installation available then it will be downloaded. To create the shell scripts and supporting files someone on the project must run the wrapper command for the first time. This developer must have a valid Grails installation. The files that are generated can then be added to version control and from then one developers can use the grailsw
or grailsw.bat
shell scripts.
$ grails wrapper
| Wrapper installed successfully
$
Continue reading →