Java 7 Code Coverage with Gradle and Jacoco

Thanks

Steven Dicks’ post on Jacoco and Gradle is a great start to integrating Jacoco and Gradle, this is a small iteration on top of that work.

Java 7 Code Coverage

The state of Code Coverage took a serious turn for the worst when Java 7 came out. The byte-code changes in Java 7 effectively made Emma and Cobertura defunct. They will not work with Java 7 constructs. Fortunately there is a new player in town called JaCoCo (for Java Code Coverage). JaCoCo is the successor to Emma which is being built on the knowledge gained over the years by the Eclipse and Emma teams on how best to do code coverage. And works with Java 7 out-of-the-box.

The advantage of using established tools is that they generally are well supported across your toolchain. JaCoCo is fairly new and so support in Gradle isn’t so smooth. Fortunately Steven’s post got me started down the right path. The one thing that I wanted to improve right away was to use transitive dependency declarations as opposed to having local jar files in my source repository. JaCoCo is now available in the Maven repos so we can do that. One thing to note is that the default files build in the Maven repo are Eclipse plugins, so we need to reference the “runtime” classifier in our dependency

The Gradle Script

configurations {
    codeCoverage
    codeCoverageAnt
}
dependencies {
    codeCoverage 'org.jacoco:org.jacoco.agent:0.5.10.201208310627:runtime@jar'
    codeCoverageAnt 'org.jacoco:org.jacoco.ant:0.5.10.201208310627'
}
test {
    systemProperties = System.properties
    jvmArgs "-javaagent:${configurations.codeCoverage.asPath}=destfile=${project.buildDir.path}/coverage-results/jacoco.exec,sessionid=HSServ,append=false",
            '-Djacoco=true',
            '-Xms128m',
            '-Xmx512m',
            '-XX:MaxPermSize=128m'
}
task generateCoverageReport << {
    ant {
        taskdef(name:'jacocoreport', classname: 'org.jacoco.ant.ReportTask', classpath: configurations.codeCoverageAnt.asPath)
 
        mkdir dir: "build/reports/coverage"
 
        jacocoreport {
            executiondata {
                fileset(dir: "build/coverage-results") {
                    include name: 'jacoco.exec'
                }
            }
            structure(name: project.name) {
                classfiles {
                    fileset(dir: "build/classes/main") {
                        exclude name: 'org/ifxforum/**/*'
                        exclude name: 'org/gca/euronet/generated**/*'
                    }
                }
                sourcefiles(encoding: 'CP1252') {
                    fileset dir: "src/main/java"
                }
            }
 
            xml  destfile: "build/reports/coverage/jacoco.xml"
            html destdir:  "build/reports/coverage"
        }
    }
}

A Few Details

The magic is in the jvmArgs of the test block. JaCoCo is run as a Java Agent which uses the runtime instrumentation feature added in Java 6 to be able to inspect the running code. Extra arguments can be added to JaCoCo there including things like excludes to exclude specific classes from coverage. The available parameters are the same as the maven JaCoCo parameters.

The generateCoverageReport task converts the jacoco.exec binary into html files for human consumption. If you’re just integrating with a CI tool, like Jenkins, then you probably don’t need this, but it’s handy for local use and to dig into the details of what’s covered.

Loose Ends

One problem that I ran into was referencing project paths like the project.buildDir from within an Ant task. Hopefully someone will come along and let me know how that’s done.

Groovy Mocking a Method That Exists on Object

In Groovy, the find method exists on Object. The find method is also an instance method on EntityManager which is commonly used in JPA to get an instance based on a database id. I was trying to create a Mock of EntityManager like:

def emMock = new MockFor(EntityManager)
emMock.demand.find { Class clazz, Object rquid -> return new Request(rqUID: rquid) }
def em = emMock.proxyDelegateInstance()

This gave me an error though:

groovy.lang.MissingMethodException: No signature of method: com.onelinefix.services.RequestRepositoryImplTest$_2_get_closure1.doCall() is applicable for argument types: (groovy.mock.interceptor.Demand) values: [groovy.mock.interceptor.Demand@a27ebd9]
Possible solutions: doCall(java.lang.Class, java.lang.Object), findAll(), findAll(), isCase(java.lang.Object), isCase(java.lang.Object)
at org.codehaus.groovy.runtime.metaclass.ClosureMetaClass.invokeMethod(ClosureMetaClass.java:264) ~[groovy-all-1.8.6.jar:1.8.6]
at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:877) ~[groovy-all-1.8.6.jar:1.8.6]
at groovy.lang.Closure.call(Closure.java:412) ~[groovy-all-1.8.6.jar:1.8.6]
at groovy.lang.Closure.call(Closure.java:425) ~[groovy-all-1.8.6.jar:1.8.6]

It ends up that find is a DefaultGroovyMethod that’s added to all Objects and this was causing the mock.demand to get confused because it thought I was trying to call the Object.find.

Luckily there is a workaround and that’s to use the ordinal argument for find.

emMock.demand.find(1) { Class clazz, Object rquid -> return new Request(rqUID: rquid) }

That’s enough of a change to invoke mock version instead of the DefaultGroovyMethod version.
Now if I only knew why….

Using Groovy AST to Add Common Properties to Grails Domain Classes

Groovy offers a lot of runtime meta-programming capabilities that allow you to add reusable functionality in a shared fashion. Grails plugins make use of this ability to enhance your project. One of the things that you can’t do with runtime meta-programming in Grails is to add persistent Hibernate properties to your domain classes. If you want to add a persistent property in a plugin (or otherwise using meta-programming) for your Grails project you have to make use of “compile-time” meta-programming. In Groovy this is done with AST Transformations.

(If you are unfamiliar with the concept of the Abstract Syntax Tree, see the Wikipedia article on Abstract Syntax Tree.)

AST Transformations are made up of two parts: (1) An annotation and (2) an ASTTransformation implementation. During compilation the Groovy compiler finds all of the Annotations and calls the ASTTransformation implementation for the annotation passing in information about.

To create your own Transformation you start by creating an Annotation. The key to the annotation working is that your annotation has to itself be annotated with @GroovyASTTransformationClass. The values passed to the GroovyASTTransformationClass define the Transformation that will be called on classes, methods or other code prior to it being compiled.

Example Annotation

package net.zorched.grails.effectivity;
 
import org.codehaus.groovy.transform.GroovyASTTransformationClass;
import java.lang.annotation.*;
 
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@GroovyASTTransformationClass({"net.zorched.grails.effectivity.EffectivizeASTTransformation"})
public @interface Effectivize {
}

Notice the reference to net.zorched.grails.effectivity.EffectivizeASTTransformation. That’s the important part because it defines the class that will be used to perform the transformation.

Example Transformation

package net.zorched.grails.effectivity;
 
import org.codehaus.groovy.ast.*;
import org.codehaus.groovy.ast.builder.AstBuilder;
import org.codehaus.groovy.ast.expr.*;
import org.codehaus.groovy.ast.stmt.*;
import org.codehaus.groovy.control.*;
import org.codehaus.groovy.transform.*;
import java.util.*;
import static org.springframework.asm.Opcodes.*;
 
@GroovyASTTransformation(phase = CompilePhase.CANONICALIZATION)
public class EffectivizeASTTransformation implements ASTTransformation {
 
    // This is the main method to implement from ASTTransformation that is called by the compiler
    public void visit(ASTNode[] nodes, SourceUnit sourceUnit) {
        if (null == nodes) return;
        if (null == nodes[0]) return;
        if (null == nodes[1]) return;
        if (!(nodes[0] instanceof AnnotationNode)) return;
 
        ClassNode cNode = (ClassNode) nodes[1];
        addProperty(cNode, "effectiveStart", Date.class, createGenerateStartMethodCall())
        addProperty(cNode, "effectiveEnd", Date.class, createGenerateEndMethodCall())
 
    }
 
    // This method returns an expression that is used to initialize the newly created property
    private Expression createGenerateStartMethodCall() {
        return new ConstructorCallExpression(new ClassNode(Date.class), ArgumentListExpression.EMPTY_ARGUMENTS);
    }
 
    private Expression createGenerateEndMethodCall() {
        return new MethodCallExpression(
                new ConstructorCallExpression(new ClassNode(Date.class), ArgumentListExpression.EMPTY_ARGUMENTS),
                "parse",
                new ArgumentListExpression(new ConstantExpression("yyyy/MM/dd"), new ConstantExpression("2099/12/31")));
    }
 
    // This method adds a new property to the class. Groovy automatically handles adding the getters and setters so you
    // don't have to create special methods for those
    private void addProperty(ClassNode cNode, String propertyName, Class propertyType, Expression initialValue) {
        FieldNode field = new FieldNode(
                propertyName,
                ACC_PRIVATE,
                new ClassNode(propertyType),
                new ClassNode(cNode.getClass()),
                initialValue
        );
 
        cNode.addProperty(new PropertyNode(field, ACC_PUBLIC, null, null));
    }
}

This example code gets called for each annotated class and adds two new Date properties called effectiveStart and effectiveEnd to it. Those properties are seen by Grails and Hibernate and will become persistent and behave the same as if you typed them directly in your Domain.

It’s a lot of work to add a simple property to a class, but if you’re looking to consistently add properties and constraints across many Grails Domain classes, this is the way to do it.

Announcing Grails Constraints Custom Domain Constraint Plugin

I’ve released my first public Grails Plugin today.

The Grails Constraint plugin gives you the ability to create custom Constraints that you can apply to your Domain classes to validate them. These are applied and act just like the built in Domain class constraints.

Why would you want this?

Grails provides two generic, catch-all Constraints in the core application:

  • validator – a generic closure mechanism for validation
  • matches – a regular expression mechanism

While those work, I find myself often wanting to use the same Constraints on multiple Domain classes (think Social Security Number, Phone Number, Zipcode, etc.) and I don’t like to repeat those regular expressions or validations all over the place.

What does this plugin do?

With the Grails Constraints plugin, you can write a custom Constraint class, drop it in /grails-app/utils/ and it will automatically be available to all of your domain classes.

Example

I create a new constrain by hand in /grails-app/utils/ComparisonConstraint.groovy. (You can also use the provided create-constraint script like grails create-constraint com.foo.MyConstraint)

class ComparisonConstraint {
 
    static name = "compareTo"
    static expectsParams = true
 
    def validate = { val, target ->
        def compareVal = target."$params"
        if (null == val || null == compareVal)
            return false
 
        return val.compareTo(compareVal) == 0
    }
}

Then you can apply your constraint to your Domain class:

class Login {
    String password
    String confirm
 
    static constraints = {
        password(compareTo: 'confirm')
    }
}

See Grails Custom Constraints Plugin for the full documentation on what all of the above means and the source code.

DRYing Grails Criteria Queries

When you’re writing code, Don’t Repeat Yourself. Now say that 5 times. *rimshot*

One of the things that I find myself repeating a lot of in many business apps is queries. It’s common to have a rule or filter that applies to many different cases. I came across such a situation recently and wanted to figure out a way to share that filter across many different queries. This is what I came up with for keeping those Criteria DRY.

To start with, I’ll use an example of an Article. This could be a blog post or a newspaper article. One of the rules of the system is that Articles need to be published before they are visible by end users. Because of this seemingly simple rule, every time we query for Articles, we will need to check the published flag. If you get a lot of queries, that ends up being a lot of repetition.

Here’s our example domain class:

package net.zorched.domain
class Article {
    String name
    String slug
    String category
 
    boolean published
 
    static constraints = {
        name(blank: false)
        slug(nullable: true)
    }
}

Now we need to add a query that will retrieve our domain instance by its slug (a slug is a publishing term for a short name given to an article, in the web world it has become a term often used for a search engine optimization technique that uses the title instead of an artificial ID). To perform that query we might write something like this on the Article class:

    static getBySlug(String slug) {
        withCriteria(uniqueResult:true) {
            and {
                eq('approved', true)
                eq(' slug',  slug)
            }
        }
    }

We want to query based on the slug, but we also want to only allow a published Article to be shown. This would allow us to unpublish an article if necessary. Without the approved filter, if the link had gotten out, people could still view the article.

Next we decide we want to list all of the Articles in a particular category so we write something like this, again filtering by the approved flag.

    static findAllByCategory(String category) {
        withCriteria() {
            and {
                eq('approved', true)
                eq('category',  category)
            }
        }
    }

Two simple examples like this might not be that big of a deal. But you can easily see how this would grow if you added more custom queries or if you had some more complicated filtering logic. Another common case would be if you had the same filter across many different domain objects. (What if the Article had attachments and comments all of which needed their own approval?) What you need is a way to share that logic among multiple withCriteria calls.

The trick to this is understanding how withCriteria and createCriteria work in GORM. They are both implemented using a custom class called HibernateCriteriaBuilder. That class invokes the closures that you pass to it on itself. Sounds confusing. Basically the elements in the closure of your criteria queries get executed as if the were called on an instance of HibernateCriteriaBuilder.

e.g.

withCriteria {
     eq('a', 1)
     like('b', '%foo%')
}

would be the equivalent of calling something like:

def builder = new HibernateCriteriaBuilder(...)
builder.eq('a', 1)
builder.like('b', '%foo%')

That little bit of knowledge allow you to reach into your meta programming bag of tricks and add new calls to the HibernateCriteriaBuilder. Every Class in groovy has a metaClass that is used to extend types of that Class. In this case we’ll add a Closure that will combine our criteria with other criteria like so:

HibernateCriteriaBuilder.metaClass.published = { Closure c ->
    and {
        eq('published', true)
        c()
    }
}

This ands together our eq call with all of the other parts of the passed in closure.
Now we can put the whole thing together into a domain class with a reusable filter.

package net.zorched.domain
 
import grails.orm.HibernateCriteriaBuilder
 
class Article {
 
    static {
        // monkey patch HibernateCriteriaBuilder to have a reusable 'published' filter
        HibernateCriteriaBuilder.metaClass.published = { Closure c ->
            and {
                eq('published', true)
                c()
            }
        }
    }
 
    String name
    String slug
    String category
 
    boolean published
    Date datePublished
 
    def publish() {
        published = true
        datePublished = new Date()
    }
 
    static def createSlug(n) {
        return n.replaceAll('[^A-Za-z0-9\\s]','')
                 .replaceAll('\\s','-')
                 .toLowerCase()
    }
 
    static findAllApprovedByCategory(String category) {
        withCriteria {
            published {
                eq('category', category)
            }
        }
    }
 
    static getBySlug(String slug) {
        withCriteria(uniqueResult:true) {
            published {
                eq(' slug',  slug)
            }
        }
    }
 
    static constraints = {
        name(blank: false)
        datePublished(nullable: true)
        slug(nullable: true)
    }
}

And there you have it. Do you have any other techniques that can be used to DRY criteria?

Grails Embedded Classes ClassCastException

Using ORM tools allow you to map the data to a database independently of how your object model looks. Grails supports one-to-many and one-to-one relationships if you want to have the data in different table. But what about when you want to map a single table to multiple objects? In Grails a has a relationship where all the data is stored in a single table is defined by using the embedded syntax. (This creates a component in the Hibernate mapping world.)

An example of using the embedded syntax to create a compositional relationship:

class Person {
    static embedded = ['address']
 
    String name
    int age
    Address address = new Address()
}
 
class Address {
    String street
    String street2
    String city
    String state
    String zip
 
    static constraints = {
        street2(nullable:true)
    }
}

This is all great, but…
When you attempt to databind against the Person model including Address properties, you end up with an exception:

2009-04-17 20:36:10,058 [13260127@qtp2-0] ERROR errors.GrailsExceptionResolver – java.lang.ClassCastException: Address$__clinit__closure1
org.codehaus.groovy.runtime.InvokerInvocationException: java.lang.ClassCastException: Address$__clinit__closure1
at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:92)
at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:234)
at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1061)
at groovy.lang.ExpandoMetaClass.invokeMethod(ExpandoMetaClass.java:910)
at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:892)
at groovy.lang.Closure.call(Closure.java:279)
at groovy.lang.Closure.call(Closure.java:274)

It ends up there is a bug in Grails versions 1.0.4, 1.0.5 and 1.1 that is causing this. That bug is related to the constraints on the embedded class, in this case the Address class. Removing the constraints allows the object to be properly databound, with the obvious downside of lacking constraints.

I have filed a bug about this: GRAILS-4446. So hopefully it will be fixed soon. Hopefully if other people are having this problem they will help them out.

Update:
There is another workaround which is to declare the embedded class in its own file which makes it a first-class Domain object. When that’s done the constraints work as expected. The downside is that this means that a table will be created for the embedded domain class (and never used).

Update Table Data in Grails using Ajax Calls

Using Ajax for simple forms can offer users a very clean, simple and fast way to input data. I came across a situation recently where I was looking into replacing a document based workflow with an application. The documents themselves contained a series of different kinds of transactions that could have occurred. There were not a set number of any of the types and the user needed a simple way to enter many rows of data.

Grails offers some very easy to use simple Ajax controls. The formRemote tag has an update parameter that can be used to specify a DOM element to update after the form is submitted. This is Ajax in it’s simplest form. Submit some data and replace the contents of a DOM element with a partial-page update. This works well if you want to update a div for example. But what if you want to add a row to a table? In the standard update method, you would have to re-render the entire table contents. In many cases that will be fine, but I figured I could do better than that and just render the new row and add it to the table.

Defining Domain Classes

For this example we’ll start with some simple classes. An Account can have many Checks posted against it. There are no set number, so we define a hasMany relationship between the Account and the Checks.

class Account {
    static transients = ['checksTotal']
    static hasMany = [checks:Check]
 
    Date date = new Date()
 
    Double getChecksTotal() {
        if (! checks)
            return 0
        return checks.inject(0) { current, check-> current + check.amount }
    }
 
    static mapping = {
    	  checks joinTable: false
    }
}
 
class Check {
    String name
    Double amount
    String checkNumber
    String reason
}

Creating a Controller

Next we need to create a Controller to mediate between our Domain and our Views. The Controller is setup to generate the default scaffold. We’ll end up overriding the show view to add a form on the page to easily post Checks to that Account. The action is the postCheck action. This is our Ajax action that will post the Check to the Account.

class AccountController {
 
    def scaffold = true
 
    def postCheck = {
        def account = Account.get(params.id)
        if(account) {
            def check = new Check(params)
            account.addToChecks(check)
            if(! account.hasErrors() && account.save()) {
                render template:'check', bean:check, var:'check'
            }
        }
    }
}

The postCheck method calls the render method to render a template and return it as the Ajax response. This template contains the markup for a single Check row.

You can see the check template here:

<tr>
    <td>${check?.name}</td>
    <td>${check?.checkNumber}</td>
    <td><g:formatNumber number="${check?.amount}" format="\$###,##0" /></td>
    <td>${check?.reason}</td>
</tr>

Creating the Ajax Form

Now we need to add the form to our account/show.gsp so that we can call the AccountController.postCheck action. The example form is below. The thing to notice is that we’re not using the update parameter of the formRemote, but rather the onSuccess parameter. The update method tell the Ajax callback what element to replace but we can’t do that with a table. onSuccess on the other hand allows us to handle the returned values in our own way. Here’ we’re going to call the appendTableRow Javascript function to handle the response.

In this case I definitely don’t want to replace the entire node because the first row of my table is actually the form itself. This gives it a very nice look where the data is entered under the appropriate header and then immediately shows up as the following row when the user hits enter.

<h3>Checks</h3>
<g:formRemote name="postCheck" url="[action: 'postCheck', params: [id:account?.id]]"
        onSuccess="appendTableRow('checks', e)">
    <table id="checks">
        <thead>
        <tr>
            <th>Name</th>
            <th>Check #</th>
            <th>Amount</th>
            <th>Reason</th>
        </tr>
        </thead>
        <tbody>
        <tr>
            <td><g:textField id="name" name="name"/></td>
            <td><g:textField id="checkNumber" name="checkNumber"/></td>
            <td><g:textField id="amount" name="amount"/></td>
            <td><g:textField id="reason" name="reason"/></td>
        </tr>
        <g:render template="check" collection="${account?.checks}" var="check"/>
        </tbody>
    </table>
</g:formRemote>

Luckily the appendTableRow function is made pretty easy by using the prototype APIs. The event returned to us is an HTML snippet, so in this case we just want to insert that snippet directly into the DOM which is accomplished with the insert prototype function.

function appendTableRow(tableId, e) {
    $(tableId).down('tbody').down('tr').insert({after: e.responseText});
}

In the end you have a data table that allows for easy, fast updates with almost no hassle.

Grails Testing Acegi Security

Almost every web application I create needs some form of user authentication and authorization. Grails provides a great plugin system that allows you to extend the base framework to provide these kinds of features. My current favorite security plugin for Grails is the Acegi Security Plugin. It’s built using the Spring Security framework and the robust and widely used Acegi framework. I like the fact that it is built on top of existing, well-known frameworks which is the philosophy of Grails itself. It is also a flexible plugin that has a good default object model.

One of the situations that inevitably arises is how to unit test code that depends on your security framework. Either you will want to test that basic authorization is working, or you might have code that makes decisions based upon who is logged in or what roles they might have. To run those test you have to setup your test cases so that the code that works when the system is running normally is tested.

Unit Testing Setup for Testing Acegi Security Code

This situation arose for me the other day and so I thought I would share the solution that I came up with.

import org.springframework.security.context.SecurityContextHolder as SCH
import org.springframework.security.providers.TestingAuthenticationToken
import org.springframework.security.GrantedAuthority
import org.springframework.security.Authentication
import org.springframework.security.GrantedAuthorityImpl
 
class AuthenticationBaseTests extends GroovyTestCase {
def setUp() {
    def user = User.get(1)    // or create a new one if one doesn't exist
    authenticate(user, "abc123", [new GrantedAuthorityImpl('ROLE_ADMIN')])
}
 
protected Authentication authenticate(user, credentials, authorities) {
    def principal = new Expando()
    principal.domainClass = user
 
    Authentication authentication = new TestingAuthenticationToken(principal, null, authorities as GrantedAuthority[])
    authentication.authenticated = true
    SCH.context.authentication = authentication
    return authentication
}
}

setUp()

The setUp() method will get executed prior to your tests being run. So if you want to do different things for each test you would want to move this code to a more appropriate place. In the setup method we are creating our Principle class, in this case, the User. Next we pass the user along with all of the roles we want the user to have for the given test case.

authenticate(user, credentials, authorities)

The real setup work is done in the authenticate() method. This method does the real work of setting up the Authentication Token and setting it in the static context, which is a thread local variable I think, that is used by the framework to determine who is making the request and what rights they have.

The fun thing about this message is the use of the Expando class. Expando allows you to create a class on the fly. This is a really interesting way to do a Mock object on-the-fly in Groovy. In this case we’re creating a Mock authentication principle. We know, by looking at the Acegi Security code, that the security framework expects an object that will call domainClass to get the underlying implementation of the User (or Principle) implemented in the application. That will return us the User object that we are setting.

This simple method can be added to a base class and then inherited from any tests that need user authentication to run successfully.

Grails Validations Based on Related Objects

Grails has a rich set of tools for performing validations of your domain objects. There are quite a few built in validations that you can use. These mainly resolve around validating single properties within a single domain object. It also supports things like validating the sizes of dependent collections.

Sometimes you need to know about the properties of one instance to validate another dependent instance. The property of that dependent instance might be used to determine the valid values of or might provide a limit for a property.

This is more easily explained with an example.

Problem Statement

I’ll use voting for members of the Board of a public company as an example.

A ShareHolder owns N number of shares of stock in a company. When the ShareHolder votes on a Board member of the company, the ShareHolder can assign 1 to N shares to that Candidate. The top 5 Candidates that receive the most Shares (not individual votes) win the election.

We might create a series of Domain classes like this:

class ShareHolder {
    static hasMany = [votes:Vote]
 
    String name
    Double shares
}
 
class Candidate {
    static hasMany = [votes:Vote]
 
    String name
}
 
class Vote {
    static belongsTo = [shareHolder: ShareHolder, candidate: Candidate]
 
    Double voteShares
}

A ShareHolder can vote multiple times, so it has many Votes. A Candidate can be voted for many times, so it has many Votes. A given Vote can be assigned 1 or more shares. But the shares for a given vote must be less than or equal to the number of shares that the voter (the ShareHolder) owns.

Validation

The natural place to perform this validation is on the Vote domain object itself. The problem is that the limit is really the shares value from the ShareHolder domain object. To solve this we can not use a built in validation. Instead we need to create our own.

To do this we can utilize the validator validation. This is no different than any other custom validation that we might need to create. Since we must have the ShareHolder and the Candidate set for this to be a valid object, we can assume that they are available. Because of this we should be able to access their properties to validate our Vote domain object.

Add a custom validator constraint:

class Vote {
    static belongsTo = [shareHolder: ShareHolder, candidate: Candidate]
 
    Double voteShares
 
    static constraints = {
        voteShares(min: 0D,
                validator: {
                    val, obj ->
                    val <= obj.shareHolder?.shares
                })
    }
}

As you can see, the obj that gets passed in is the instance that is being validated. The val is the value of the property being validated, in this case the voteShares property. All that has to be done is to compare the value of the obj.shareHolder?.shares too the voteShares property. The obj.shareHolder?. should protect us against a null reference in case the shareHolder isn’t set. Then the validation will just fail on not having the ShareHolder.

Nothing really tricky here, just something interesting I ran into recently.

Package Grails DBMigrations in your WAR File

The Grails DBMigrate Plugin is a handy way to give you control over the generation of your database if you don’t want Grails to auto-munge your schema. It works fine in development, but when you create a WAR for deployment on another machine the Migrations are not packaged in the WAR so the database can’t be created or updated.

Packaging DBMigrate Scripts for Deployment

Here’s the quick solution to package your DBMigrations in your WAR file.

Just add this to your Config.groovy file and when you generate the WAR the migrations will be included and found by the Plugin.

grails.war.resources = {stagingDir ->
    copy(todir: "${stagingDir}/WEB-INF/classes/grails-app/migrations") {
        fileset(dir:"grails-app/migrations")
    }
}

Aside

The only problem with DBMigrate is that it doesn’t handle creating or updating Stored Procedures and Functions which means if you want to use those – for Reporting purposes lets say – you’re out of luck currently.