Archive for the ‘Groovy’ Category

Grails easy JSON DTO’s

May 25th, 2013 No comments

Some JSON is only used in specific places. For these occurrences I use extension methods / meta methods to easily convert my classes into the required JSON without the need for a specific mapping/dto class. To do this I declare a Markup interface (called Mappable) on which the method can be invoked.

I put the following interface in src/groovy:

package com.example.json
 * Markup interface so we can add extension methods to convert objects to maps.
 * @see MetaMethods.groovy
interface Mappable {}

I then add the following to my MetaMethods class in src/groovy:

package com.example.json;
class MetaMethods {
    static void register() {
        Mappable.metaClass.toMap { whitelist, blacklist ->
            /* metaClass, class */
            def map = [:];
            /* id seems to be a special case */
            if (("id" in whitelist) || (!"id" in blacklist)) {
                map["id"] = delegate["id"];
            if (whitelist) {
                whitelist.each {
                    map[it] = delegate[it]
            } else if (blacklist) {
       { prop, val ->
                    if (!(prop in blacklist)) {
                        map[prop] = val;
            return map;

I register the metamethods in my Bootstrap.groovy

class BootStrap {
    def init = { servletContext ->
        /* Register our own Meta Methods/Extension Methods */

Now we can create easy JSON dto’s based on our domain (don’t forget to add the Mappable interface to your domain classes).

Usage example:

        def jsonMap = myDomainClass.toMap(["id", "propertyX", "propertyZ"], []); // 1st level properties
        jsonMap["customer"] = myDomainClass.customer ? myDomainClass.customer.toMap(["id", "fullName", "firstName", "insertion", "lastName"], []) : null; // 2nd level properties
        render jsonMap as JSON; // or as XML

Happy Grailing!

Grails cheatsheet

September 26th, 2011 No comments

This is supposed to be a cheatsheet for some common elements in Grails.
It’s a little bare at the moment but I hope that in time it will be a nice mashup of different Grails elements.

Grails Cheatsheet


static constraints = {
        blank: false,
        nullable: false,
        inList: ['a', 'b'], //Or reference property here
        matches: '[0-9]+',
        minSize: 1,
        maxSize: 10,
        min: 1,
        max: 10,
        range: 1..10,
        unique: true,
        url: true,
        email: true,
        notEqual: "passwd", //Or reference property here
        validator: { val, obj ->
            return val != obj.propertyName
        /* Display Options */
        attributes: [year: 2000..2011], //Adds extra attributes to item when rendered.
        password: true, //Indicate that this is a password field
        widget: 'textarea', //Choose what widget will be used to render this item.
                //textField, hiddenField, submitButton, field, textArea, form, actionSubmit, actionSubmitImage, datePicker, renderNoSelectionOption, timeZoneSelect, localeSelect, currencySelect, select, checkBox, radio
        display: false //Hide this item when scaffolding

Persistence Callbacks

  • beforeInsert – Executed before an object is initially persisted to the database
  • beforeUpdate – Executed before an object is updated
  • beforeDelete – Executed before an object is deleted
  • beforeValidate – Executed before an object is validated
  • afterInsert – Executed after an object is persisted to the database
  • afterUpdate – Executed after an object has been updated
  • afterDelete – Executed after an object has been deleted
  • onLoad – Executed when an object is loaded from the database


def beforeInsert() {
def beforeUpdate() {
	if (isDirty('fieldName')) {

Showing SQL-queries

Edit the DataSource.groovy file in the Configuration directory and add the following to the hibernate section (preferably in non-production environments):

hibernate {
	show_sql = true
Categories: Groovy Tags:

Configuring Tomcat, PostgreSQL and Grails on Ubuntu

September 18th, 2011 1 comment

First install tomcat and tomcat on your ubuntu machine if you have not already done so.

sudo apt-get install openjdk-7-jdk tomcat7 postgresql

Setup the required PostgreSQL database on ubuntu. We will connect to it as a JNDI DataSource later on.
Usually I create a new superuser to do maintenance tasks.

CREATE USER <role_name> superuser login encrypted password '<password>';
-- Connect to the database from command line
psql -d postgres
CREATE USER userName WITH PASSWORD 'yourPassword';

Get the postgreSQL JDBC driver.

cd /usr/share/tomcat7/lib
sudo wget

Create a Tomcat Context configuration for your grails webapp.

sudo vi /etc/tomcat7/Catalina/localhost/yourappname.xml

Fill it with something like the following, (adapted to your webapps name / context root of course)

<Context path="/yourContextPath" reloadable="false">
          <Resource name="jdbc/yourName" auth="Container"
                    type="javax.sql.DataSource" driverClassName="org.postgresql.Driver"
                    username="myuser" password="mypasswd" maxActive="20" maxIdle="10"

We’re almost there. Update DataSource.groovy

    production {
        dataSource {
            dbCreate = "update"
            jndiName = "java:comp/env/jdbc/yourName"

Awesome! Restart tomcat (sudo /etc/init.d/tomcat7 restart). Build (grails prod war) and deploy (copy file to /var/lib/tomcat7/webapps) your grails webapp and go bananas!


I got an “Unsupported major.minor version 51.0” error. This was because by default java 6 was used instead of java 7 on my machine.

Caused by: java.lang.UnsupportedClassVersionError: org/codehaus/groovy/grails/scaffolding/GrailsTemplateGenerator : Unsupported major.minor version 51.0 (unable to load class org.codehaus.groovy.grails.scaffolding.GrailsTemplateGenerator)

My default-java was set wrong in the /usr/lib/jvm directory. (ls -l /usr/lib/jvm) default-java was pointing to the java 6 version.

cd /usr/lib/jvm
sudo rm default-java
sudo ln -s java-1.7.0-openjdk-amd64 default-java
Categories: Groovy Tags: