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

19 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 need a Statistics Homework Help expert to handle my assignment on median regression. This model is just the same, and the quantile regression, which is estimating the median. The assignment requires you to fit the model in STATA. I hope that you are in a position to solve it. I won't accept anything other than a grade A. I will also need Statistics Assignment Help in other topics but first finish this one.

    ReplyDelete
  6. I have just gone through your website and I am highly convinced that you can offer quality economics homework help. I have seen several
    samples and the quality looks good. If the samples are done by you then I am more than willing to hire you for my assignment. I just hope that anytime I contact you for aneconomics homework help you will be available to help because some of these assignments are always very urgent.

    ReplyDelete
  7. I am happy that many students have received the right Math assignment help through you. I am in my third year in college and I have not had a chance to get such help. Since I have come across your post, I hope I will find the right Math homework help through you. My only obstacle would be finances. I hope that you are pocket friendly or should I call it student-friendly

    ReplyDelete
  8. I have a ledger posting assignment involving several entries. I am currently fishing for the best Accounting Homework Help tutor to help me with the task and from what I have read, you guys don’t seem too bad at your job except for the few flaws. I may consider taking Accounting Assignment Help from here and hopefully I will be back with positive feedback.

    ReplyDelete

  9. https://buydocumentation.com/

    Buy Driver’s License online, US driver license, drivers license renewal ca WhatsApp +1 (925) 526-5453


    Here at Buy Documentation, you can buy fake documents at a fraction of a cost. We keep our prices low to meet the needs of all our customers. We provide Best Quality Novelty Real and Fake IDs and Passport, Marriage Certificates and Drivers license online

    https://buydocumentation.com/canada-visa/

    https://buydocumentation.com/buy-real-drivers-license/

    https://buydocumentation.com/buy-real-id-cards/

    https://buydocumentation.com/social-security-number-ssn/

    ReplyDelete
  10. Having gone through your website I am sure that you are good enough. I have checked two of your samples and I like the work already. I want to get an A in my international economics and I believe you are the right economics assignment help expert to guide me in that. If I get an A in this first one then you will be my permanent helpeconomics homework help, expert.

    ReplyDelete
  11. Your Statistics Assignment Help team did an amazing job on my STATA homework. In Fact I would like to know thStatistics Homework Help expert who handled my work because I would like to hire them again. I am pleased with everything about you.

    ReplyDelete
  12. Your post has opened my eyes. I have never thought of asking for Math assignment help but I will try you. It would be a good thing to have someone ready to provide Math homework help. Sometimes I spend sleepless nights solving my assignments. If I knew you, I would not spend much time since I would just send you the assignments with a guarantee of top grades.

    ReplyDelete
  13. How do I know that you are offering the best Accounting Assignment Help? I have worked with more platforms in the past and I have had a lot of disappointments. I would be happy if you offered me Accounting Homework Help samples so that I can see the quality of work I should expect from you. If you satisfy me in the first task, then I am going to hire you for more work.

    ReplyDelete
  14. Thank you for your outstanding article. Our goal is to offer top-class specialized services to you that create a fruitful, long-lasting relationship between us. Our excellent real estate portfolio management is the reason why our clients become like family. We provide the Great Deals and Discounts on Real Estate Portfolio Management in Noida 3 BHK Flats, 4 BHK Flats, Apartments, Penthouse, Corporate Properties, Commercial Properties in Noida, Greater Noida West, Delhi NCR. Learn more about Investmango: visit our website and call now: +918076042671

    ReplyDelete
  15. Good and informative post. Java Assignment Help has always been a friend in need for the students. Thanks for informing me about LiveWebTutors and their expert services regarding the assignment. I will surely come back for more assistance.

    ReplyDelete
  16. Fox Chamber offers their clients the Top digital marketing service available. We are a group of professionals who provide extensive business strategies as well as the most effective and the Best Advertising Agency.

    ReplyDelete
  17. Fox Chamber offers their clients the Top digital marketing service available. We are a group of professionals who provide extensive business strategies as well as the most effective and the Best Advertising Agency.

    ReplyDelete
  18. Fox Chamber offers their clients the Top digital marketing service available. We are a group of professionals who provide extensive business strategies as well as the most effective and the Best Advertising Agency.

    ReplyDelete