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 →
We can configure Spring beans using several methods in Grails. We can for example add them to grails-app/conf/spring/resources.xml
using Spring’s XML syntax. But we can also use a more Groovy way with grails-app/conf/spring/resources.groovy
. We can use a DSL to define or configure Spring beans that we want to use in our Grails application. Grails uses BeanBuilder to parse the DSL and populate the Spring application context. To define a bean we use the following syntax beanName(BeanClass)
. If we want to set a property value for the bean we use a closure and in the closure we set the property values. Let’s first create a simple class we want to configure in the Spring application context:
// File: src/groovy/com/mrhaki/spring/Person.groovy
package com.mrhaki.spring
import groovy.transform.ToString
@ToString
class Person {
String name
Date birthDate
}
Continue reading →
One of the underlying frameworks of Grails is Spring. A lot of the Grails components are Spring beans and they all live in the Spring application context. Every Grails service we create is also a Spring bean and in this blog post we see how we can inject a Grails service into a Spring bean we have written ourselves. The following code sample shows a simple Grails service we will inject into a Spring bean:
// File: grails-app/services/com/mrhaki/sample/LanguageService.groovy
package com.mrhaki.sample
class LanguageService {
List<String> languages() {
['Groovy', 'Java', 'Clojure', 'Scala']
}
}
Continue reading →
We can use the tel:
URL scheme for phone numbers in HTML. Just like the mailto:
URL scheme will open the default mail application will the tel:
start a telephone call. If the HTML page is viewed on a mobile phone and we select a link with the tel:
scheme we can immediately call the number following the scheme. On a desktop computer a VOIP call will be initiated.
We can use hyphens in the phone number for readability, they will be ignored when the call is made. For example the imaginary phone number 123456789 in the Netherlands can be used as shown in the following HTML snippet:
Continue reading →
The Gradle wrapper allows us to let developers use Gradle without the need for every developer to install Gradle. We can add the output of the Gradle wrapper task to version control. Developers only need to checkout the source for a project and invoke the gradlew
or gradlew.bat
scripts. The scripts will look for a Gradle distribution and download it to the local computer of a developer. We can customize the Gradle wrapper and provide a different source for the Gradle distribution. For example we can add the Gradle distribution ZIP file on our company intranet. We then use the distributionUrl
property of the Wrapper
task to reference the intranet location where we place the Gradle distribution ZIP file.
In the following sample file we use the distributionUrl
property to reference our company intranet:
Continue reading →
The easiest way to pretty print an XML structure is with the [XmlUtil](http://groovy.codehaus.org/api/groovy/xml/XmlUtil.html)
class. The class has a serialize()
method which is overloaded for several parameter types like String
, GPathResult
and Node
. We can pass an OutputSteam
or Writer
object as argument to write the pretty formatted XML to. If we don't specify these the serialize()
method return a String
value.
import groovy.xml.*
def prettyXml = '''
<?xml version="1.0" encoding="UTF-8"?>
<languages>
<language id="1">Groovy</language>
<language id="2">Java</language>
<language id="3">Scala</language>
</languages>
'''
// Pretty print a non-formatted XML String.
def xmlString = '<languages><language id="1">Groovy</language><language id="2">Java</language><language id="3">Scala</language></languages>'
assert XmlUtil.serialize(xmlString) == prettyXml
// Use Writer object as extra argument.
def xmlOutput = new StringWriter()
XmlUtil.serialize xmlString, xmlOutput
assert xmlOutput.toString() == prettyXml
// Pretty print a Node.
Node languagesNode = new XmlParser().parseText(xmlString)
assert XmlUtil.serialize(languagesNode) == prettyXml
// Pretty print a GPathResult.
def langagesResult = new XmlSlurper().parseText(xmlString)
assert XmlUtil.serialize(langagesResult) == prettyXml
// Pretty print org.w3c.dom.Element.
org.w3c.dom.Document doc = DOMBuilder.newInstance().parseText(xmlString)
org.w3c.dom.Element root = doc.documentElement
assert XmlUtil.serialize(root) == prettyXml
// Little trick to pretty format
// the result of StreamingMarkupBuilder.bind().
def languagesXml = {
languages {
language id: 1, 'Groovy'
language id: 2, 'Java'
language id: 3, 'Scala'
}
}
def languagesBuilder = new StreamingMarkupBuilder()
assert XmlUtil.serialize(languagesBuilder.bind(languagesXml)) == prettyXml
Continue reading →