{"id":11040,"date":"2013-02-21T23:16:00","date_gmt":"2013-02-21T22:16:00","guid":{"rendered":"http:\/\/touk.pl\/blog\/?guid=9fa5b869a8970eb1195c428d8dbe6bb0"},"modified":"2022-08-01T10:02:42","modified_gmt":"2022-08-01T08:02:42","slug":"grails-session-timeout-without-xml","status":"publish","type":"post","link":"https:\/\/touk.pl\/blog\/2013\/02\/21\/grails-session-timeout-without-xml\/","title":{"rendered":"Grails session timeout without XML"},"content":{"rendered":"<p>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.<\/p>\n<h2 id=\"common-approaches\">Common approaches<\/h2>\n<p>Speaking of session timeout config in Grails, a default approach\u00a0is to install templates with a command. This way we got direct access to\u00a0<span style=\"font-family: Courier New, Courier, monospace\">web.xml<\/span> file. Also more unnecessary files are\u00a0created. Despite that <u>unnecessary files are unnecessary<\/u>, we should also remember some other common knowledge: <b>XML is not for humans<\/b>.<\/p>\n<p>Another, a bit more hacky, way is to create mysterious <span style=\"font-family: Courier New, Courier, monospace\">scripts\/_Events.groovy<\/span> file. Inside of which, by using not less enigmatic closure:\u00a0<span style=\"font-family: 'Courier New', Courier, monospace\">eventWebXmlEnd = { filename -&gt;\u00a0&#8230; }<\/span><span style=\"font-family: inherit\">,\u00a0<\/span>we can parse and hack into <span style=\"font-family: Courier New, Courier, monospace\">web.xml<\/span><span style=\"font-family: inherit\">\u00a0with a help of\u00a0<\/span><span style=\"font-family: Courier New, Courier, monospace\">XmlSlurper<\/span>.<br \/>\nEven though lot of Grails plugins do it similar way, still it\u2019s not really straightforward, is it? Besides, where\u2019s the IDE support? Hello!?<\/p>\n<p>Examples of both above ways can be seen on <a href=\"http:\/\/stackoverflow.com\/questions\/11262450\/change-session-timeout-for-netbeans-embedded-grails\">StackOverflow<\/a>.<\/p>\n<h2 id=\"simpler-and-cleaner-way\">Simpler and cleaner way<\/h2>\n<p>By adding just a single line to the already generated <span style=\"font-family: Courier New, Courier, monospace\">init<\/span> closure we have it done:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"groovy\">class BootStrap {\r\n    def init = {\r\n        servletContext -&gt;\r\n        servletContext.addListener(OurListenerClass)\r\n    }\r\n}<\/pre>\n<p>Allrighty, this is enough to avoid XML. Sweets are served after the main course though :)<\/p>\n<h2 id=\"listener-as-a-spring-bean\">Listener as a Spring bean<\/h2>\n<p>Let us assume we have a requirement. Set a longer session timeout for premium user account.<br \/>\nUsers are authenticated upon session creation through SSO.<\/p>\n<p>To easy meet the requirements just instantiate the <span style=\"font-family: Courier New, Courier, monospace\">CustomTimeoutSessionListener<\/span> as Spring bean at resources.groovy. We also going to need some source of the user custom session timeout. Let say a <span style=\"font-family: Courier New, Courier, monospace\">ConfigService<\/span>.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"groovy\">beans = {\r\n    customTimeoutSessionListener(CustomTimeoutSessionListener) {\r\n        configService = ref('configService')\r\n    }\r\n}<\/pre>\n<p>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:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"groovy\">class BootStrap {\r\n    def customTimeoutSessionListener\r\n    def init = {\r\n        servletContext -&gt;\r\n        servletContext.addListener(customTimeoutSessionListener)\r\n    }\r\n}<\/pre>\n<p>An example <span style=\"font-family: Courier New, Courier, monospace\">CustomTimeoutSessionListener<\/span> implementation can look like:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">import javax.servlet.http.HttpSessionEvent\r\nimport javax.servlet.http.HttpSessionListener\r\nimport your.app.ConfigService\r\n\r\nclass CustomTimeoutSessionListener implements HttpSessionListener {\r\n    ConfigService configService\r\n    @Override\r\n    void sessionCreated(HttpSessionEvent httpSessionEvent) {\r\n        httpSessionEvent.session.maxInactiveInterval = configService.sessionTimeoutSeconds\r\n    }\r\n    @Override\r\n    void sessionDestroyed(HttpSessionEvent httpSessionEvent) {\r\n        \/* nothing to implement *\/ }\r\n}<\/pre>\n<p>Having at hand all power of the Spring IoC this is surely a good place to load some persisted user\u2019s account stuff into the session or to notify any other adequate bean about user presence.<\/p>\n<h2 id=\"wait-what-about-the-user-context\">Wait, what about the user context?<\/h2>\n<p>Honest answer is: that depends on your case. Yet here\u2019s an example of <span style=\"font-family: Courier New, Courier, monospace\">getSessionTimeoutMinutes() <\/span>implementation using Spring Security:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"groovy\">import org.springframework.security.core.context.SecurityContextHolder\r\n\r\nclass ConfigService {\r\n    static final int 3 H = 3 * 60 * 60\r\n    static final int QUARTER = 15 * 60\r\n    int getSessionTimeoutSeconds() {\r\n        String username = SecurityContextHolder.context?.authentication?.principal\r\n        def account = Account.findByUsername(username)\r\n        return account?.premium ? 3 H : QUARTER\r\n    }\r\n}<\/pre>\n<p>&nbsp;<\/p>\n<p>This example is simplified. Does not contain much of <i>defensive programming<\/i>. Just an assumption that principal is already set and is a String &#8211; unique username. Thanks to Grails convention our <span style=\"font-family: Courier New, Courier, monospace\">ConfigService<\/span> is transactional so the Account domain class can use GORM dynamic finder.<br \/>\nOK, 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&#8230;<\/p>\n<h2 id=\"any-gotchas\">Any gotchas?<\/h2>\n<p>There is one. When running <span style=\"font-family: Courier New, Courier, monospace\">grails test<\/span> command, <span style=\"font-family: Courier New, Courier, monospace\">servletContext<\/span> comes as some mocked class instance without <span style=\"font-family: Courier New, Courier, monospace\">addListener<\/span> method. Thus we going to have a <span style=\"font-family: Courier New, Courier, monospace\">MissingMethodException<\/span> when running tests :(<\/p>\n<p>Solution is typical:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"groovy\">def init = {\r\n    servletContext -&gt;\r\n    if (Environment.current != Environment.TEST) {\r\n        servletContext.addListener(customTimeoutSessionListener)\r\n    }\r\n}<\/pre>\n<p>An unnecessary obstacle if you ask me. Should I submit a Jira issue about that?<\/p>\n<h2 id=\"tldr\">TL;DR<\/h2>\n<p>Just implement a <span style=\"font-family: Courier New, Courier, monospace\">HttpSessionListener<\/span>. Create a <i>Spring<\/i> bean of the listener. Inject it into BootStrap.groovy and call <span style=\"font-family: Courier New, Courier, monospace\">servletContext.addListener(injectedListener)<\/span>.<\/p>\n","protected":false},"excerpt":{"rendered":"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.\nCommon approaches\nSpeaking of session timeout config in Grails, a default approach&nbsp;is to install templates with a command. This way we got direct access to&nbsp;web.xml file. Also more unnecessary files are&nbsp;created. Despite that unnecessary files are unnecessary, we should also remember some other common knowledge: XML is not for humans.\nAnother, a bit more hacky, way is to create mysterious scripts\/_Events.groovy file. Inside of which, by using not less enigmatic closure:&nbsp;eventWebXmlEnd = { filename -&gt;&nbsp;&#8230; },&nbsp;we can parse and hack into web.xml&nbsp;with a help of&nbsp;XmlSlurper.\nEven though lot of Grails plugins do it similar way, still it&rsquo;s not really straightforward, is it? Besides, where&rsquo;s the IDE support? Hello!?\nExamples of both above ways can be seen on StackOverflow.\nSimpler and cleaner way\nBy adding just a single line to the already generated init closure we have it done:\nclass BootStrap {\r\n    def init = { servletContext -&gt;    \r\n        servletContext.addListener(OurListenerClass)    \r\n    }    \r\n}\n\nAllrighty, this is enough to avoid XML. Sweets are served after the main course though :)\nListener as a Spring bean\nLet us assume we have a requirement. Set a longer session timeout for premium user account.\nUsers are authenticated upon session creation through SSO.\nTo 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.\nbeans = {    \r\n    customTimeoutSessionListener(CustomTimeoutSessionListener) {    \r\n        configService = ref('configService')    \r\n    }    \r\n}\n\nWith 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:\nclass BootStrap {\r\n    def customTimeoutSessionListener\r\n    def init = { servletContext -&gt;    \r\n        servletContext.addListener(customTimeoutSessionListener)\r\n    }    \r\n}\n\nAn example CustomTimeoutSessionListener implementation can look like:\nimport javax.servlet.http.HttpSessionEvent    \r\nimport javax.servlet.http.HttpSessionListener    \r\nimport your.app.ConfigService    \r\nclass CustomTimeoutSessionListener implements HttpSessionListener {    \r\n    ConfigService configService\r\n    @Override    \r\n    void sessionCreated(HttpSessionEvent httpSessionEvent) {    \r\n        httpSessionEvent.session.maxInactiveInterval = configService.sessionTimeoutSeconds\r\n    }    \r\n    @Override    \r\n    void sessionDestroyed(HttpSessionEvent httpSessionEvent) { \/* nothing to implement *\/ }    \r\n}\nHaving at hand all power of the Spring IoC this is surely a good place to load some persisted user&rsquo;s account stuff into the session or to notify any other adequate bean about user presence.\nWait, what about the user context?\nHonest answer is: that depends on your case. Yet here&rsquo;s an example of getSessionTimeoutMinutes() implementation using Spring Security:\nimport org.springframework.security.core.context.SecurityContextHolder    \r\nclass ConfigService {\r\n    static final int 3H = 3 * 60 * 60\r\n    static final int QUARTER = 15 * 60\r\n    int getSessionTimeoutSeconds() {    \r\n        String username = SecurityContextHolder.context?.authentication?.principal    \r\n        def account = Account.findByUsername(username)    \r\n        return account?.premium ? 3H : QUARTER\r\n    }    \r\n}\nThis example is simplified. Does not contain much of defensive programming. Just an assumption that principal is already set and is a String &#8211; unique username. Thanks to Grails convention our ConfigService is transactional so the Account domain class can use GORM dynamic finder.\nOK, 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&#8230;\nAny gotchas?\nThere 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 :(\nSolution is typical:\ndef init = { servletContext -&gt;\r\n    if (Environment.current != Environment.TEST) {    \r\n        servletContext.addListener(customTimeoutSessionListener)    \r\n    }    \r\n}\nAn unnecessary obstacle if you ask me. Should I submit a Jira issue about that?\nTL;DR\nJust implement a HttpSessionListener. Create a Spring bean of the listener. Inject it into BootStrap.groovy and call servletContext.addListener(injectedListener).\n","protected":false},"author":43,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[11],"tags":[50],"class_list":{"0":"post-11040","1":"post","2":"type-post","3":"status-publish","4":"format-standard","6":"category-development-design","7":"tag-groovy"},"_links":{"self":[{"href":"https:\/\/touk.pl\/blog\/wp-json\/wp\/v2\/posts\/11040","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/touk.pl\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/touk.pl\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/touk.pl\/blog\/wp-json\/wp\/v2\/users\/43"}],"replies":[{"embeddable":true,"href":"https:\/\/touk.pl\/blog\/wp-json\/wp\/v2\/comments?post=11040"}],"version-history":[{"count":10,"href":"https:\/\/touk.pl\/blog\/wp-json\/wp\/v2\/posts\/11040\/revisions"}],"predecessor-version":[{"id":14745,"href":"https:\/\/touk.pl\/blog\/wp-json\/wp\/v2\/posts\/11040\/revisions\/14745"}],"wp:attachment":[{"href":"https:\/\/touk.pl\/blog\/wp-json\/wp\/v2\/media?parent=11040"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/touk.pl\/blog\/wp-json\/wp\/v2\/categories?post=11040"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/touk.pl\/blog\/wp-json\/wp\/v2\/tags?post=11040"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}