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

36 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
  19. Besides my C course, I have a job and family, both of which compete to get my time. I couldn't find sufficient time for the challenging C assignments, and these people came in and saved my skin. I must commend them for the genius Programming Assignment Help. Their C Homework Help tutors did the best job and got me shining grades.

    ReplyDelete
  20. I am looking for a Statistics Assignment Help expert for Statistics Homework Help. I have struggled enough with statistics and therefore I just can't do it anymore on my own. . I have come across your post and I think you are the right person to provide me with SPSS homework help. Let me know how much you charge per assignment so that I can hire you today.

    ReplyDelete
  21. Matlab Assignment Help helped me to complete my seventh Matlab assignment, which was also the best-performed! It scored 92/100, which I've never scored before on any other assignment/exam in my lifetime. Otherwise, their service was as quick as usual. The delivery was also on time. I'm now requesting to use this same programmer multiple times. He seems the best in Image Processing tasks. Meanwhile, I'll ask for more Matlab Homework Help soon.

    ReplyDelete
  22. Hey there, I need an Statistics Homework Help expert to help me understand the topic of piecewise regression. In our lectures, the concept seemed very hard, and I could not understand it completely. I need someone who can explain to me in a simpler way that I can understand the topic. he/she should explain to me which is the best model, the best data before the model and how to fit the model using SPSS. If you can deliver quality work then you would be my official Statistics Assignment Help partner.

    ReplyDelete
  23. I don’t have time to look for another expert and therefore I am going to hire you with the hope that I will get quality economics assignment help .Being aneconomics homework help professor I expect that your solutions are first class. All I want to tell you is that if the solutions are not up to the mark I am going to cancel the project.

    ReplyDelete
  24. That is a huge number of students. Are they from the same country or different countries? I also want your math assignment help. I want to perform in my assignments and since this is what you have been doing for years, I believe you are the right person for me. Let me know how much you charge for your math homework help services.

    ReplyDelete
  25. Hello. Please check the task I have just sent and reply as soon as possible. I want an adjustment assignment done within a period of one week. I have worked with an Accounting Homework Help tutor from your team and therefore I know it’s possible to complete it within that period. Let me know the cost so that I can settle it now as your Accounting Assignment Help experts work on it.

    ReplyDelete
  26. As much as there are discouragements, it is true that mathematics is hard. Like in my case, I was never discouraged by anyone about math but I still find it very hard and that is why I am requesting your Math assignment help. I am tired of struggling with mathematics and spending sleepless nights trying to solve sums that I still don’t get right. Having gone through your Math homework help, I am sure that I will get the right help through you. Please tell me what I need to be able to hire you.

    ReplyDelete
  27. Just what I was looking for. I am struggling with my accounting assignment. I want an Accounting Assignment Help tutor to offer me two services. One is to complete my accounting assignments and the other is to provide me with online classes. I believe you are experienced enough to offer both Accounting Homework Help and online classes. I know you charge assignments based on the bulk. Tell me how much you charge for the online classes per hour.

    ReplyDelete
  28. The ardent Programming Homework Help tutor that nailed down my project was very passionate. He answered my Python questions with long, self-explanatory solutions that make it easy for any average student to revise. Moreover, he didn't hesitate to answer other questions, too, even though they weren't part of the exam. If all Python Homework Help experts can be like this then they can trend as the best Programming school ever online.

    ReplyDelete
  29. Hey STATA homework help expert, I need to know if you can conduct the Kappa measurement of agreement. This is what is in my assignment. I can only hire someone for statistics assignment help if they are aware of the kappa measurement of agreement. If you can do it, then reply to me with a few lines of what the kappa measure of agreement is. Let me know also how much you charge for statistics homework help in SAS

    ReplyDelete
  30. Me and my classmates took too long to understand Matlab Assignment Help pricing criteria. we're always grateful for unique solutions on their Matlab assignments. Matlab Homework Help experts have the right experience and qualifications to work on any programming student's homework. They help us in our project.

    ReplyDelete
  31. Hi, other than economics assignment help are there other subjects that you cover? I am having several assignments one needs an economics homework help expert and the other one needs a financial expert. If you can guarantee quality work on both then I can hire you to complete them. All I am sure of is that I can hire you for the economics one but the finance one I am not sure

    ReplyDelete
  32. Business Leads World is your long-run strategic growth partner with expertise within the Merchant Cash Advance Leads and various business loans. We have a tendency to focus on targeted campaigns and end-to-end lead generation services bound to bring best, exceptional results for our shoppers.

    ReplyDelete

  33. herbal incense 2021,
    trusted herbal incense sites 2021,
    k2 liquid incense,
    order cheap herbal incense,
    cheap strong herbal incense,
    super strong herbal incense liquid,
    most potent herbal incense on the market,
    best herbal incense website 2021,
    k2 liquid spray on paper for sale,
    where to buy liquid herbal incense,
    buy herbal incense with debit card,
    buy herbal incense overnight shipping,
    strongest liquid incense,
    buy herbal incense online cash on delivery,
    liquid herbal incense 2020,
    k2 spray that get you high for sale,
    buy herbal net


    https://k2herbalspice.com/
    Call Us: (+1) 747-500-1520
    Email: sales@k2herbalspice.com



    herbal incense 2021,
    trusted herbal incense sites 2021,
    k2 liquid incense,
    order cheap herbal incense,
    cheap strong herbal incense,
    super strong herbal incense liquid,
    most potent herbal incense on the market,
    best herbal incense website 2021,
    k2 liquid spray on paper for sale,
    where to buy liquid herbal incense,
    buy herbal incense with debit card,
    buy herbal incense overnight shipping,
    strongest liquid incense,
    buy herbal incense online cash on delivery,
    liquid herbal incense 2020,
    k2 spray that get you high for sale,
    buy herbal net


    website: https://herbalincensespices.com/
    Call Us: +1 (312)-319-2341
    Email: sales@herbalincensespices.com


    We are located in USA AND UK. Buy High Quality Grade(%99.96) Mephedrone (2- methylamino 1-one) also known as 4-methylmethcathinone(4-MMC).We are one of the top suppliers in wholesale and retail of Benzodiazepine,synthetic cannabinoids, Blotters chemicals. Mephedrone and other plants research chemicals such as: Amphetamines Pentylone Mephedrone Flephedrone Bulytone (bk-MBDB) MDAI Analgesic Chemical CB1 and CB2 CP 47497 CP-55940 HU-210 HU-331 Ephedrine Hcl Powder JWH-018 / JWH-200,JWH-250 TFMPP 2C-E, 2C-I, 2C-P, 2C-C, 2C-T-2 DOC, DOI Bromo DragonFly TCB-2 Testosterone 5-Meo-DMT 4-Aco-DMT 4-Ho-MIPT 4-Meo-PCP Naphyrone HEROIN. Methylone (bk-MDMA) Ethylone , Oxycodone Flephedrone (4-FMC, 4-Fluoromethcathinone) Methedrone (BK-PMMA, Methoxyphedrine) 4-Fluoromethamphetamine (4-FMA) a-Pyrrolidinopropiophenone (a-PPP). MDPV (Methylenedioxypyrovalerone, MDPK) Testosterone JWH-073, 1-butyl-3-(1-naphthoyl)indole Hydrocodone Dimethocaine (Larocaine/DMC) Morphine JWH-018, 1-Pentyl-3-(1-naphthoyl)indole Herione 4-Fluoroamphetamine (4-FA, 4-FMP, or Flux) Ketamine Our quality is the best you can find around and we sell in small/large quantities with guaranteed discreet delivery in good time Shipping

    website: https://uslegitresearchchemicals.com/
    Call Us: +1 760-573-6020
    Email: info@uslegitresearchchemicals.com

    ReplyDelete