2013/06/29

Grails enum custom database value mapping

About

How to map a custom value and type of enum constants into database with Grails Domain.

TL;DR

Just add id field to the enum class and set its value for each enum constant.

Example case

When modelling domain there is often some enum domain class introduced. Such as WhateverType or SomethingsStatus. Let say we want to use ordinal instead of default GORM's text mapping.
class SomeDomainElement {
    Level level

    static mapping = {
        level enumType: 'ordinal'
    }
}
Our enum presents itself as follows:
enum Level {
    EASY,
    MEDIUM,
    HARD
}
Latter introduction of a new level may happen. Lest say ADVANCED. It would be really tempting to place such between levels MEDIUM and HARD. This however would have changed the position number of level HARD. Stop! Database mapping will change either. What about already stored 'levels HARD'?

Solution

Remove the mapping block from SomeDomainElement. It won't be needed any more. Just add the id field to the enum constants.
enum Level {
    EASY(1),
    MEDIUM(2),
    ADVANCED(4),
    HARD(3)

    final int id
    private Level(int id) { this.id = id }
}
The field must be named id so Grails would map it automatically as DB value.

Any serializable and known by Hibernate type can be used instead of int. Like char, String, BigDecimal, Date and so on.

2013/04/06

Thought static method can't be easy to mock, stub nor track? Wrong!

No matter why, no matter is it a good idea. Sometimes one just wants to check or it's necessary to be done. Mock a static method, woot? Impossibru!

In pure Java world it is still a struggle. But Groovy allows you to do that really simple. Well, not groovy alone, but with a great support of Spock.

Lets move on straight to the example. To catch some context we have an abstract for the example needs. A marketing project with a set of offers. One to many.

import spock.lang.Specification

class OfferFacadeSpec extends Specification {

    OfferFacade facade = new OfferFacade()

    def setup() {
        GroovyMock(Project, global: true)
    }

    def 'delegates an add offer call to the domain with proper params'() {
        given:
            Map params = [projId: projectId, name: offerName]

        when:
            Offer returnedOffer = facade.add(params)

        then:
            1 * Project.addOffer(projectId, _) >> { projId, offer -> offer }
            returnedOffer.name == params.name

        where:
            projectId | offerName
            1         | 'an Offer'
            15        | 'whasup!?'
            123       | 'doskonaƂa oferta - kup teraz!'
    }
}
So we test a facade responsible for handling "add offer to the project" call triggered  somewhere in a GUI.
We want to ensure that static method Project.addOffer(long, Offer) will receive correct params when java.util.Map with user form input comes to the facade.add(params).
This is unit test, so how Project.addOffer() works is out of scope. Thus we want to stub it.

The most important is a GroovyMock(Project, global: true) statement.
What it does is modifing Project class to behave like a Spock's mock. 
GroovyMock() itself is a method inherited from SpecificationThe global flag is necessary to enable mocking static methods.
However when one comes to the need of mocking static method, author of Spock Framework advice to consider redesigning of implementation. It's not a bad advice, I must say.

Another important thing are assertions at then: block. First one checks an interaction, if the Project.addOffer() method was called exactly once, with a 1st argument equal to the projectId and some other param (we don't have an object instance yet to assert anything about it).
Right shit operator leads us to the stub which replaces original method implementation by such statement.
As a good stub it does nothing. The original method definition has return type Offer. The stub needs to do the same. So an offer passed as the 2nd argument is just returned.
Thanks to this we can assert about name property if it's equal with the value from params. If no return was designed the name could be checked inside the stub Closure, prefixed with an assert keyword.

Worth of  mentioning is that if you want to track interactions of original static method implementation without replacing it, then you should try using GroovySpy instead of GroovyMock.

Unfortunately static methods declared at Java object can't be treated in such ways. Though regular mocks and whole goodness of Spock can be used to test pure Java code, which is awesome anyway :)

2013/02/21

Grails session timeout without XML

This article shows clean, non hacky way of configuring featureful event listeners for Grails application servlet context. Feat. HttpSessionListener as a Spring bean example with session timeout depending on whether user account is premium or not.

Common approaches

Speaking of session timeout config in Grails, a default approach is to install templates with a command. This way we got direct access to web.xml file. Also more unnecessary files are created. Despite that unnecessary files are unnecessary, we should also remember some other common knowledge: XML is not for humans.

Another, a bit more hacky, way is to create mysterious scripts/_Events.groovy file. Inside of which, by using not less enigmatic closure: eventWebXmlEnd = { filename -> ... }we can parse and hack into web.xml with a help of XmlSlurper.
Even though lot of Grails plugins do it similar way, still it’s not really straightforward, is it? Besides, where’s the IDE support? Hello!?

Examples of both above ways can be seen on StackOverflow.

Simpler and cleaner way

By adding just a single line to the already generated init closure we have it done:
class BootStrap {

    def init = { servletContext ->    
        servletContext.addListener(OurListenerClass)    
    }    
}

Allrighty, this is enough to avoid XML. Sweets are served after the main course though :)

Listener as a Spring bean

Let us assume we have a requirement. Set a longer session timeout for premium user account.
Users are authenticated upon session creation through SSO.

To easy meet the requirements just instantiate the CustomTimeoutSessionListener as Spring bean at resources.groovy. We also going to need some source of the user custom session timeout. Let say a ConfigService.
beans = {    
    customTimeoutSessionListener(CustomTimeoutSessionListener) {    
        configService = ref('configService')    
    }    
}

With such approach BootStrap.groovy has to by slightly modified. To keep control on listener instantation, instead of passing listener class type, Spring bean is injected by Grails and the instance passed:
class BootStrap {

    def customTimeoutSessionListener

    def init = { servletContext ->    
        servletContext.addListener(customTimeoutSessionListener)
    }    
}

An example CustomTimeoutSessionListener implementation can look like:
import javax.servlet.http.HttpSessionEvent    
import javax.servlet.http.HttpSessionListener    
import your.app.ConfigService    
    
class CustomTimeoutSessionListener implements HttpSessionListener {    
    
    ConfigService configService
    
    @Override    
    void sessionCreated(HttpSessionEvent httpSessionEvent) {    
        httpSessionEvent.session.maxInactiveInterval = configService.sessionTimeoutSeconds
    }    
    
    @Override    
    void sessionDestroyed(HttpSessionEvent httpSessionEvent) { /* nothing to implement */ }    
}
Having at hand all power of the Spring IoC this is surely a good place to load some persisted user’s account stuff into the session or to notify any other adequate bean about user presence.

Wait, what about the user context?

Honest answer is: that depends on your case. Yet here’s an example of getSessionTimeoutMinutes() implementation using Spring Security:
import org.springframework.security.core.context.SecurityContextHolder    
    
class ConfigService {

    static final int 3H = 3 * 60 * 60
    static final int QUARTER = 15 * 60
    
    int getSessionTimeoutSeconds() {    
    
        String username = SecurityContextHolder.context?.authentication?.principal    
        def account = Account.findByUsername(username)    
    
        return account?.premium ? 3H : QUARTER
    }    
}
This example is simplified. Does not contain much of defensive programming. Just an assumption that principal is already set and is a String - unique username. Thanks to Grails convention our ConfigService is transactional so the Account domain class can use GORM dynamic finder.
OK, config fetching implementation details are out of scope here anyway. You can get, load, fetch, obtain from wherever you like to. Domain persistence, principal object, role config, external file and so on...

Any gotchas?

There is one. When running grails test command, servletContext comes as some mocked class instance without addListener method. Thus we going to have a MissingMethodException when running tests :(

Solution is typical:
def init = { servletContext ->
    if (Environment.current != Environment.TEST) {    
        servletContext.addListener(customTimeoutSessionListener)    
    }    
}
An unnecessary obstacle if you ask me. Should I submit a Jira issue about that?

TL;DR

Just implement a HttpSessionListener. Create a Spring bean of the listener. Inject it into BootStrap.groovy and call servletContext.addListener(injectedListener).