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

40 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. Contact us to hire a web service and much more other services....

    ReplyDelete
  6. Amazing content with cool website designing and also many apps visit for more info local marketing

    ReplyDelete
  7. Excellent and very cool idea and the subject at the top of magnificence and I am happy to this post..Interesting post! Thanks for writing it.What's wrong with this kind of post exactly? It follows your previous guideline for post length as well as clarity.
    Java Training in Chennai

    ReplyDelete
  8. It is amazing and wonderful to visit your site.Thanks for sharing this information,this is useful to me...
    Android Training in Chennai
    Ios Training in Chennai

    ReplyDelete
  9. This was an nice and amazing and the given contents were very useful and the precision has given here is good.
    AWS Training in Chennai

    ReplyDelete
  10. Thank you a lot for providing individuals with a very spectacular possibility to read critical reviews from this site.
    aws training institute in bangalore

    ReplyDelete
  11. AWS Training in Bangalore - Live Online & Classroom
    myTectra Amazon Web Services (AWS) certification training helps you to gain real time hands on experience on AWS. myTectra offers AWS training in Bangalore using classroom and AWS Online Training globally. AWS Training at myTectra delivered by the experienced professional who has atleast 4 years of relavent AWS experince and overall 8-15 years of IT experience. myTectra Offers AWS Training since 2013 and retained the positions of Top AWS Training Company in Bangalore and India.


    IOT Training in Bangalore - Live Online & Classroom
    IOT Training course observes iot as the platform for networking of different devices on the internet and their inter related communication. Reading data through the sensors and processing it with applications sitting in the cloud and thereafter passing the processed data to generate different kind of output is the motive of the complete curricula. Students are made to understand the type of input devices and communications among the devices in a wireless media.

    ReplyDelete
  12. You blog post is just completely quality and informative. Many new facts and information which I have not heard about before. Keep sharing more blog posts.
    DevOps Training in chennai

    DevOps Training in chennai

    DevOps Training in chennai

    DevOps Training in Velachery

    DevOps Training in Tambaram

    DevOps Training in sholinganallur

    ReplyDelete
  13. Hi, thank you very much for new information , i learned something new. Very well written. It was so good to read and usefull to improve knowledge. Keep posting. If you are looking for any python related information please visit our website
    python training in bangalore

    ReplyDelete
  14. شركة تنظيف فلل بالرياض Perfect cleaning and cleaning of the villa's rooms and the use of a vacuum cleaner to remove dust and soil.شركة تنظيف بالرياض The beauty and cleanliness of the place gives the use of steam cleaning machines that remove stains accurately and quickly and are used to clean canes and boards.
    شركة تنظيف بالخرج Carpets, carpets and ceramics. If you are unable to execute these tips from شركة تنظيف منازل بالخرج .
    شركة مكافحة الحمام بالرياض We provide you with a range of tips that prevent the nesting of the bathroom on the surface of your home you clean the surface and balconies from the remnants of the grain and clean it from waste and used furniture
    شركة تنظيف منازل بالمدينة المنورة We have the ability to make your home an oasis of cleanliness and beauty. We have a dedicated team to clean every part of your home, but we are keen to provide important tips to keep your house clean for as long as possible. شركة تنظيف بالمدينة المنورة Use a vacuum cleaner to get rid of accumulated dust on a daily basis. Cleaning the glass home facades provides a perfect look for the home Provide you with a great service in cleaning your house if you can not do this hard work and effort شركة نقل عفش بالمدينة المنورة .
    شركة تنظيف بينبع Provide you with a distinctive service in all types of private cleaning Carpet carpet cleaning using the steam cleaning machine makes it clean and fully sterile.
    شركة نقل اثاث بينبع It is an ideal choice to carry out your home furniture without any effort or hardship. But if you want to do it yourself, arrange the clothing bags for your family so that you can remove the tires and wooden rooms easily. Transportation. Many things you can do .
    شركة تنظيف منازل بمكة It is the best choice for you to clean the perfect parts of your home - Carpet cleaning and carpeting the best types of steam cleaning machines or sent to Cleaning and cleaning of beds and boards and putting mattresses on them to prevent the accumulation of dust and stains on them You must use high quality detergents to ensure high quality cleaning of all the items and parts of your home You need a daily cleaning of the kitchen and bathrooms to give a recovery and confidence in the cleanliness of the whole house شركة تنظيف خزانات بمكة Able to clean your home without bothering you or get tired at great cheap prices.
    Visit our website
    https://www.allsaad.com/

    ReplyDelete

  15. شركة تنظيف بالمدينة المنورة Is one of the best companies currently located in Al Madinah Al Munawwarah, Saudi Arabia. Since the company started its activities more than twenty years ago, it has endeavored to develop all its services and made sure to provide the best service at the highest level of quality in cleaning and disinfection at the lowest prices possible. The company believes that the company's employment is a mirror that reflects the efficiency of the company that boasts of it. The worker must be confident and credible to provide the customer with everything he can provide. JAL cleaning and sterilization found in شركة تنظيف منازل بالمدينة المنورة .
    شركة نقل اثاث بالمدينة المنورة Providing customers with transportation services of furniture and furniture and storage of furniture using the latest methods and methods and modern techniques and trained workers and freight cars specially equipped to transport furniture and clothes to anywhere inside or outside Medina, customers often need a city to transfer furniture to move furniture from their offices or homes Or their companies to new places but are afraid of their loss of damage or loss, but our company guarantees its customers to complete the transfer process safely and safely without being exposed to any piece of fracture or loss as the company provides a service to lift and download furniture using a hydraulic winch The only available within شركة نقل عفش بالمدينة المنورة .
    شركة تنظيف بينبع The company's services include all kinds of services needed by customers such as house cleaning services, apartments, cleaning services for ground and upper water tanks, cleaning of palaces and cleaning services for hotels, residential complexes, mosques, parks, facilities and others. Types of Services The main governmental and private bodies cooperated with the cleaning company in Yanbu. Our company has provided them with the most complete image that has impressed them and increased their confidence in the skill and efficiency of our company and its employees. P safe and effective when providing various cleaning services such detergents, but inside there is no شركة تنظيف منازل بينبع .
    شركة نقل اثاث بينبع Is one of the largest furniture transport companies in the city of Yanbu, which is known for providing services at the highest level and the company always offers offers and discounts and wonderful offers on the cost of services and this is what surprises customers and make them always put them the only choice for them, we have a professional team of carpenters who oversee the distinguished operations Dismantling and installing furniture and repair and maintenance of any fractures, as the company has workers polishing furniture and wooden furniture with effective polishes to remove the dirt from the layers of paint and make the furniture bright shiny like new, after the completion of cleaning the workers of evil Of furniture with materials encapsulates the strength and durability to protect the furniture from the external shocks or natural factors such materials are available only from within شركة نقل عفش بينبع
    Visit our website
    https://fajr-sate3.com/

    ReplyDelete

  16. The task of moving a catcher needs to rely on شركة نقل عفش بالمدينة المنورة It is specialized and has a long history in this field, helping it to carry out the task of transporting the baggage without causing any problems. Among the precautions taken by the company during transport of the luggage are the following: High-quality packaging materials to ensure that no problems are encountered during transport, the luggage is loaded into the car very carefully so as not to be subject to any problems during transportation. The luggage is re-connected to the place where it is transported and the packaging that is placed on the pallet is removed. During transportation. , All the transferred items are written to make sure that there is no defect in the piece, therefore you will ensure the transfer of the baggage without being exposed to any problems during transportation, شركة نقل اثاث بالمدينة المنورة .
    Is characterized by شركة تنظيف بالمدينة المنورة With the experience and efficiency in the task of cleaning, as it uses the best equipment and the latest in addition to many aspects that focus on them to ensure that the cleaning is done to the fullest, and the most important things that you find in the fast service company and nowhere else find the following: It depends on the best detergents that can eliminate stains and smears, follow a certain system in the cleaning task; for this reason it ensures that it reaches the best results, depends on the latest methods such as steam cleaning method which proved its efficiency in the cleaning work, During which to eliminate all germs and The bacteria that are present in the place and maintain the health of the present, possess the best specialized perfumes that you can only find شركة نظافة بالمدينة المنورة.
    that شركة تخزين اثاث بالمدينة المنورة It can store any quantity of furniture even if it is huge. This is because the company owns large warehouses divided into many sections. It packs and puts furniture in cars and is transported to the stores equipped with the highest level and has the latest means of monitoring. شركة تخزين عفش بالمدينة المنورة You will get satisfactory results without having to pay a lot of money in return
    Be aware شركة تنظيف بينبع Cleaning works require the latest equipment for cleaning and the best detergents. This is what it provides to its customers. Therefore, it ensures the results. The company can clean any place, Will t D have شركة نظافة بينبع Discounts and offers can not be found elsewhere
    The task of moving furniture from one place to another can not be done by anything, but it must rely on a specialized company such as شركة نقل اثاث بينبع ، As it will provide you with assurance that the furniture transfer works will be done well and will not be exposed any piece of the pieces to any problems during the transfer of furniture. In addition, it will carry out a comprehensive inspection of all parts before and before the transfer. The best packaging tools are used in this task. you only have to communicate with شركة نقل عفش بينبع .
    Visit our website
    https://www.zeenclean.com/

    ReplyDelete

  17. Welcome to the official website of our company to clean apartments, houses, villas and shops in Saudi Arabia This is because we are the best home services company at the moment and by the testimony of our valued customers, the workers who work in the company have a very high experience in the field of cleaning in general, as well as we will give you cleanliness of the highest quality and the lowest prices with the testimony of customers, our goal is to satisfy our customers to the highest degree possible and thanks to God always First of all, thanks to the workers and technicians, we were able to satisfy all the customers who contracted with the company and contacted them, because we specialize in cleaning, sewerage and transport of luggage just contact us and you will notice that your house as if it is completely new from the intensity of cleanliness.
    شركة الصفرات للتنظيف بالرياض
    شركة الصفرات لتنظيف الخزانات بالرياض
    شركة الصفرات لمكافحة الحشرات بالرياض
    شركة الصفرات لنقل الاثاث بالرياض
    شركة الصفرات لكشف التسربات بالرياض
    شركة تنظيف بالمدينة المنورة
    شركة تنظيف بينبع
    https://www.cleanriyadh.com/

    ReplyDelete
  18. Al-Najah Company is one of the most distinctive things about Al-Ahsa cleaner company. Cleanliness of furniture, and some individuals are responsible for the operation of devices, whether pumping devices or suction, and there is a team responsible for the process of sterilization air conditioners , Our team is considered one of the best teams because of its vast experience over many years in this field, skill and high efficiency, and fast and perfect performance. The nature of the work of the team and what may be seen when carrying out its mission, and we have a team of women to be at the service of our valued customers so as not to worry about the entry of the team of men to come home in the presence of women and housewives.
    شركة تنظيف بالاحساء
    شركة تنظيف مكيفات بالاحساء
    شركة تسليك مجارى بالاحساء
    شركة مكافحة حشرات بالاحساء
    https://www.a-lnagah.com

    ReplyDelete
  19. House cleaning company in Hail represents the best and ideal solution for specialized and distinctive cleaning of all pieces of furniture and house rooms no matter the number of floors of the house and the number of rooms, where we work through a team trained on modern methods of cleaning using the latest steam cleaning machines that give outstanding results in cleaning sofas, boards, carpets and rugs It is also used to clean curtains and furnishings.Ceramic floors, chimneys and hoods are cleaned from hard fat stains and rust stains safely and completely.We also provide marble polishing services by providing the latest Italian marble polishing machines with the best types of detergents Its excellent cleaning and disinfecting houses cleaning company examples in Hail is the best choice and cheaper.
    شركة تنظيف بحائل
    شركة تنظيف فرش بحائل
    شركة تنظيف مجالس بحائل
    شركة تنظيف سجاد بحائل
    شركة تنظيف منازل بحائل
    شركة رش مبيدات بحائل
    https://www.raya-hail.com

    ReplyDelete
  20. Hi,Very nice post.Thanks for the information provided.It is very interesting and very informative.I am always impressed with your post and helpful tips.Keep posting tips and relevant content as usual.
    big data training in btm

    ReplyDelete
  21. Wonderful information is you Share with us in this Article, thank you for taking the time to share with us such a good article. Amazing insight you have on this, it's nice to find a website that details so much information about different artists. If you need any college level Assignment Help at reliable quality with better work. Kindly visit our website. We provide best My Assignment Help services in Australia, USA, UK, UAE, and Canada etc.

    ReplyDelete
  22. Thenutritionsclinic manufacturing of gas or flatulence after consuming any sugar based totally food • bloating of the belly • oral thrush and terrible breath • skin issues like psoriasis or eczema • temper swings • meals cravings, especially for sugar foods • feeling tired and lightheaded it's far critical to get the condition recognized because the signs and symptoms are much like different illnesses and you could incorrectly diagnose your self.
    https://thenutritionsclinic.com/

    ReplyDelete
  23. You have performed a great job on this article. It's very precise and highly qualitative. You've managed to make it readable and easy to read. You have some real writing talent. Thank you so much.
    jobs in dubai

    ReplyDelete
  24. A special thanks to My Assignment Help for providing a well-written assignment. You guys were a savior to me. Will contact you soon for my upcoming assignments. You can email us at cs@Myassignmenthelpau.Com or Phone Number: +61-2-8005-8227

    ReplyDelete
  25. Nice to be visiting your blog again, it has been months for me. Well this article that i've been waited for so long. I need this article to complete my assignment in the college, and it has same topic with your article. Thanks, great share.
    Best Dissertation Writing Services

    ReplyDelete