The MarkupTemplateEngine
added in Groovy 2.3 is very powerful. We can define layout templates with common markup we want to be used in multiple other templates. In the layout template we define placeholders for variables and content blocks surrounded by shared markup. We define values for these variables and content blocks in the actual template. We even can choose to propagate model attributes from the template to the layout template. Let's first create a layout template with the name main.tpl
:
// File: main.tpl
html {
head {
// Use pageTitle layout property.
title(pageTitle)
}
body {
section(id: 'main') {
// Render mainContents layout property.
mainContents()
}
section(id: 'actions') {
// Render actions layout property.
actions()
}
footer {
// A template is also Groovy code, we can
// define new variables or methods.
// pubDate should be set via original template
// model.
def generatedOn = pubDate ?: new Date()
p("Generated on ${dateFormat(generatedOn)}")
}
}
}
def dateFormat(date) {
date.format('dd-MM-yyyy')
}
Continue reading →
In most of our projects we have dependencies on other code, like libraries or other projects. Gradle has a nice DSL to define dependencies. Dependencies are grouped in dependency configurations. These configuration can be created by ourselves or added via a plugin. Once we have defined our dependencies we get a nice overview of all dependencies in our project with the dependencies
task. We can add the optional argument --configuration
to only see dependencies for the given configuration. But we can even check for a specific dependency where it is used, any transitive dependencies and how the version is resolved.
In the following sample build we define a compile dependency on Spring Boot and SLF4J API. The SLF4J API is also a transitive dependency for the Spring Boot dependency, so we can see how the dependencyInsight
tasks shows a version conflict.
Continue reading →
Since Groovy 2.3 we can use the MarkupTemplateEngine
to generate XML/HTML. We can write our templates using a builder syntax. Inside our templates we can define nested templates. These nested templates contain builder syntax code and can use objects that are passed as attributes to the nested template. To invoke a nested template we must use the fragment
method and pass a Map
with attributes that is used in the nested template. We can re-use nested templates inside our template.
In the following sample code we define two nested templates: faIcon
and list
. Inside our template we use the fragment
method to call these nested templates and we set values to the attributes that are used in the nested templates:
Continue reading →
Since Groovy 2.3 we can use the new MarkupTemplateEngine
to generate XML/HTML content. The engine compiles the template for better performance and optionally provides type checking on model attributes used in the template. We can configure the template engine to use a custom base template class instead of the default BaseTemplate
. In our custom template class we can add new methods that can be invoked from our template content.
Let's create a new base template class with an icon
method to output valid FontAwesome markup:
Continue reading →
Since Groovy 2.3 the JSON parser has improved and is really a performant parser for JSON payload. JSON must be formatted in a strict way, for example all keys must be enclosed in double quotes. But what if we have JSON which not applies to the strict specification? For example a configuration file written in JSON and we want to add comments to this file. Or use single quotes for keys, or just leave all the quotes out. We can now specify the type JsonParseType.LAX
for our JSON parser and we can now parse JSON which doesn't apply to the strict specification.
import groovy.json.*
import static groovy.json.JsonParserType.LAX as RELAX
def jsonText = '''
{
message: {
/* Set header of message */
header: {
"from": 'mrhaki',
'to': ["Groovy Users", "Java Users"]
}
# Include a little body for the message.
'body': "Check out Groovy's gr8 JSON support."
}
}
'''
def json = new JsonSlurper().setType(RELAX).parseText(jsonText)
def header = json.message.header
assert header.from == 'mrhaki'
assert header.to[0] == 'Groovy Users'
assert header.to[1] == 'Java Users'
assert json.message.body == "Check out Groovy's gr8 JSON support."
Continue reading →
In Asciidoc markup we can include or exclude text based on the existence of document attributes or based on the value of a document attribute. Therefore we use the macros ifdef
, ifndef
and ifeval
. If we want to include some content if the document attribute sample is set we can use the following syntax:
ifdef::sample[Content is shown when sample attribute is set]
ifdef::sample[]
Content is shown when sample attribute is set
endif::sample[]
Continue reading →
In a previous post we learned how to include partial content from included files. We needed to enclose the content we want to include between start and end tags and reference those tags in our documentation markup. But Andres Almiray already mentioned in a tweet we can use line numbers as well:
@marcovermeulen @rfletcherew @mrhaki you can also use -1 in the include range, like this https://raw.githubusercontent.com/griffon/griffon/master/docs/griffon-guide/src/asciidoc/appendix-sample-applications.adoc
— Andres Almiray (@aalmiray) June 6, 2014
Continue reading →
Bintray JCenter is the next generation (Maven) repository. The repository is already a superset of Maven Central, so it can be used as a drop-in replacement for Maven Central. To use Bintray JCenter we only use jcenter()
in our repositories
configuration block in BuildConfig.groovy
. This is the same as we would use in a Gradle build.
// File: grails-app/conf/BuildConfig.groovy
...
repositories {
...
// Configure Bintray JCenter as repo.
jcenter()
...
}
...
Continue reading →
In a previous post we saw that we can use Spring's Java configuration feature to load beans in our Grails application. We can use the @Profile
annotation to conditionally load beans based on the currently active Spring profile. We can for example use the Java system property spring.profiles.active
when we start the Grails application to make a profile active. But wouldn't it be nice if we could use the Grails environment setting to conditionally load beans from a Java configuration? As it turns out Grails already set the current Grails environment name as the active profile for the Grails application. So we can simply use @Profile
in our configuration or component classes, like in a non-Grails Spring application.
We can use the @Profile
annotation in a Spring Java configuration class. The following sample shows different values for the @Profile
annotation. The annotation is applied to methods in the sample code, but can also be applied to a class.
Continue reading →
A Grails application uses Spring under the hood, which means we can also use all of Spring's features in a Grails application. For example we can use the Spring Java configuration feature with our Grails application. The Java configuration feature allows us to write a Java or Groovy class to define beans for our application. Of course in Grails we have the nice bean builder syntax when we define beans in the grails-app/conf/spring/resources.groovy
file, but maybe we must include a Java configuration from an external library or we just want to write a configuration class ourselves.
This post is very much inspired by this blog post by Andres Steingress.
Continue reading →
Sometimes we want to support in our RESTful API a different level of detail in the output for the same resource. For example a default output with the basic fields and a more detailed output with all fields for a resource. The client of our API can then choose if the default or detailed output is needed. One of the ways to implement this in Grails is using converter named configurations.
Grails converters, like JSON
and XML
, support named configurations. First we need to register a named configuration with the converter. Then we can invoke the use
method of the converter with the name of the configuration and a closure with statements to generate output. The code in the closure is executed in the context of the named configuration.
Continue reading →
In Grails we can apply the @Resource
AST (Abstract Syntax Tree) annotation to a domain class. Grails will generate a complete new controller which by default extends grails.rest.RestfulController
. We can use our own controller class that will be extended by the @Resource
transformation. For example we might want to disable the delete
action, but still want to use the @Resource
transformation. We simply write a new RestfulController
implementation and use the superClass
attribute for the annotation to assign our custom controller as the value.
First we write a new RestfulController
and we override the delete
action. We return a HTTP status code 405 Method not allowed:
Continue reading →