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).

16 comments:

  1. Hi! I followed your steps exactly in Grails 2.3.7 and I can't get the Listener to inject the Service :(
    I mean, in your example, your configService is always null. The resources.groovy file is exactly the same as yours. Any ideas? Thanks!

    ReplyDelete
  2. If I get the service using Holders.grailsApplication.mainContext.getBean it works, but I can't figure out why it doesn't autowire it like it should.

    ReplyDelete
  3. Did you pass class or bean instance to the addListener() method? The first example is with class, as that's enough if you don't need tie session listener with Spring context. Sorry if that was misleading. I've just added 2nd example starting with words "With such approach BootStrap.groovy has to by slightly modified". Check it please and let me know if that helps. If there still be a problem I'll post example on GitHub.

    ReplyDelete
  4. That was it! The bean instance was the thing I was missing and now it works like a charm. Thanks very much!

    ReplyDelete
  5. I didn’t know that you guys were so good at providing programming assignment help. The Java assignment I sent is back and it’s simply excellent. However, the Java homework help tutor I was assigned, has saddened me by telling me that she is leaving your team. All in all, I am happy for completing my work on time and I will continue engaging you more in the future. If you guys handled other assignments other than programming I would hire you as well. However, if I get another programming one it will surely come your way.

    ReplyDelete
  6. As a statistics homework help expert can you do my statistics assignment within a day? The paper is not very hard but I need a very experienced Econometrics assignment help expert to handle it. If you don't have anyone who can guarantee an A then please don't pick the job. I strictly want to get everything in the paper. I have sent it to you and therefore go through it and let me know whether you can handle it well.

    ReplyDelete
  7. I am a Matlab homework help expert and would like to know, how is sampling done when a sensing array is used for image acquisition? I have looked for answers to this question on the web but I can’t seem to find anything satisfactory? Any matlab assignment help suggestions on where I can get more information on this topic and image processing as a whole? It would really help improve my skills as a Matlab homework help tutor.

    ReplyDelete
  8. Which country do you operate in? I am looking for an economics assignment help expert from Australia. I want someone who can help me while relating to economic issues in our country. I am almost giving up on finding one from Australia. Therefore if you are from Australia or can get an economics homework help expert from Australia then you would have helped me in a great way.

    ReplyDelete
  9. On your post, you claim to provide first-class java homework help. If the assignment you send to me is not as satisfactory as you claim am I allowed to claim my money back? I have had some very horrible experiences with online programming assignment help companies. I just want assurance that whatever you claim to offer is what you offer. With that, I would give you all my assignments for the next two years.

    ReplyDelete
  10. I tend to come across two major equations while studying probability theory. They are Chebyshev's inequality and the Markov inequality. From experience, they are not that easy to understand. Apparently, the two are related. I need someone experienced, i.e., a statistics homework help or a professor, to show me if the two are related. In addition I also need a SAS assignment help expert to work on my paper.

    ReplyDelete
  11. I hate doing control systems assignments because they take too much of my time. I always come to this site when I need Matlab assignment help and never had problems but I didn’t like my last experience at all probably because the person who handled my task didn’t seem to have enough experience with the topic.I had to hire a different expert for the job and this almost made me miss my assignment submission deadline. I am not saying that this is not a good site to hire a Matlab homework help expert. All I am saying is that the company should take another look at their data mining experts to avoid future inconveniences.

    ReplyDelete
  12. Hello, I need an economics assignment help with regression and unemployment. I am not able to describe everything here but I have submitted the entire task on your provided website for review. I just hope that I will get the right economics homework help from you. Should you have any questions on the work I have provided please feel free to contact me. In addition, let me know how much I need to pay for the work to be completed.

    ReplyDelete
  13. This must be a popular blog since the content and design is great. Law is an area that includes lots of detailing and information, both while speaking and writing. Moreover, when students are given law assignments to write, they might find themselves in trouble. While completing their law homework on time with full accuracy and if you are one of them, you don’t have to worry at all because we provide the best law assignment writing help service. Do you need Law Assignment Writing Services ?

    ReplyDelete
  14. You have a great article. I just wanted to point out that high definition content has become a standard for consumers, just imagine how demanding video resolution requirements are in the field of professional filming. Well, to some, video cameras that shoot in full HD may still suffice; however, with the advent of 4K video cameras & 4K camcorders, others may not think the same anymore. Many of the newer 4K models have very advanced HD functionality and are truly a one shop stop for HD and 4K combined. Know more about Best 4K Camcorders Under 1000

    ReplyDelete

  15. Finest [url=https://www.dukeandlordpublishers.com//]Duke and Lord Publishers [/url]
    to give quick recognition in top-tier journals, best editing services, reliable resources to authenticate the research publication

    ReplyDelete
  16. Finest Best Publishing Solutions to give quick recognition in top-tier journals, best editing services, reliable resources to authenticate

    ReplyDelete