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 →
One of the great features of Gradle is incremental build support. With incremental build support a task is only executed if it is really necessary. For example if a task generates files and the files have not changed than Gradle can skip the task. This speeds up the build process, which is good. If we write our own tasks we can use annotations for properties and methods to make them behave correctly for incremental build support. The @OutputDirectory
annotation for example can be used for a property or method that defines a directory that is used by the task to put files in. The nice thing is that once we have designated such a directory as the output directory we don't have to write code to create the directory if it doesn't exist. Gradle will automatically create the directory if it doesn't exist yet. If we use the @OutputFile
or @OutputFiles
annotation the directory part of the file name is created if it doesn't exist.
In the following example build file we create a new task SplitXmlTask with the property destinationDir
and we apply the @OutputDirectory
annotation. If the directory doesn't exist Gradle will create it when we execute the task.
Continue reading →
Gradle is very flexible. One of the ways to alter the build configuration is with initialization or init scripts. These are like other Gradle scripts but are executed before the build. We can use different ways to add the init script to a build. For example we can use the command-line option -I
or --init-script
, place the script in the init.d
directory of our GRADLE_HOME
directory or USER_HOME/.gradle
directory or place a file init.gradle
in our USER_HOME/.gradle
directory.
We can also use the apply(from:)
method to include such a script in our build file. We can reference a file location, but also a URL. Imagine we place an init script on our company intranet to be shared by all developers, then we can include the script with the apply(from:)
method. In the following build file we use this syntax to include the script:
Continue reading →
We can exclude transitive dependencies easily from specific configurations. To exclude them from all configurations we can use Groovy's spread-dot operator and invoke the exclude()
method on each configuration. We can only define the group, module or both as arguments for the exclude()
method.
The following part of a build file shows how we can exclude a dependency from all configurations:
Continue reading →
With Gradle we can execute Java applications using the JavaExec
task or the javaexec()
method. If we want to run Java code from an external dependency we must first pull in the dependency with the Java application code. The best way to do this is to create a new dependency configuration. When we configure a task with type JavaExec
we can set the classpath to the external dependency. Notice we cannot use the buildscript{}
script block to set the classpath. A JavaExec
task will fork a new Java process so any classpath settings via buildscript{}
are ignored.
In the following example build script we want to execute the Java class org.apache.cxf.tools.wsdlto.WSDLToJava
from Apache CXF to generate Java classes from a given WSDL. We define a new dependency configuration with the name cxf
and use it to assign the CXF dependencies to it. We use the classpath
property of the JavaExec
task to assign the configuration dependency.
Continue reading →
We can introduce Groovy into our Java projects at grassroots level. Even if we aren't allowed to run the Groovy compiler we can use other ways to run Groovy code. As long as we can include the Groovy libraries as a compile dependency than we can already use Groovy from Java. In this post we see how we can use the power of XmlSlurper
to parse XML from our Java code.
To execute a Groovy script from we can use a GroovyShell
object and invoke the evaluate()
method. The evaluate()
method can parse a Groovy script as File
or Reader
object. We can also use a String
value to be evaluated. The last statement of the script that is evaluated can be assigned to a Java variable. To pass variables to the script we use the Binding
object. This is a map of variables and their values. We assign values to the variables in the Java code and in the Groovy script we can use the variable values.
Continue reading →
Since Groovy 1.8.7 we can create a list and use the withDefault()
method to define a default value for elements that are not yet in the list. We use a closure as argument of the method, which returns the default value. We can even access the index of the element in the closure as an argument.
Besides the withDefault()
method we can use the withLazyDefault()
which is just another name for the same functionality. If we request a value for an index that is greater or equal to the size of the list, the list will automatically grow up to the specified index. Any gaps are filled with the value null
.
Continue reading →
Since Groovy 1.8.7 we can use the first()
and last()
methods on Iterable
objects. With the first()
method we get the first element and with the last()
method we get the last element:
def list = 0..100
assert list.first() == 0
assert list.last() == 100
def abc = 'abc' as Character[]
assert abc.first() == 'a'
assert abc.last() == 'c'
def s = ['Groovy', 'Gradle', 'Grails', 'Rocks'] as Set
assert s.first() == 'Groovy'
assert s.last() == 'Rocks'
Continue reading →