Thursday, October 17, 2013

Easy way to show your application startup time

In this post you will learn a quick & easy way to access the start up time of your Grails application and display the information on a gsp page.

What we have to do is:
  1. Access the startup date of your applications context
  2. Make the date accessible in a convenient way
  3. Format and display the data in your gsp

Accessing the startup date 

First of all we need the time when the context of our application was started. This can be easily accessed via the GrailsApplication instance that can be injected in your Grails Services, Controllers, etc.
This example shows the BootStrap.groovy as starting point, but for production code a real service would be a better choice. So here we go...inject grailsApplication to into our class and get the startup date in milliseconds from the main context.

class BootStrap {
    def grailsApplication
    def init = { servletContext ->
        Long startupDateInMillis = grailsApplication.mainContext.getStartupDate()

Make the date accessible in a convenient way

Now you know the startup date, but if you want to display it in a gsp for example you need an easy way to access it. A practical and logical way is to store this meta information in the Grails Metadata along with other informations about your app (such as app version).
Complement the previous code to look like this:

Long startupDateInMillis = grailsApplication.mainContext.getStartupDate()
Date startupDate = new Date(startupDateInMillis)
grailsApplication.metadata.put('app.startupDate', startupDate)

The milliseconds are converted into a real date object and stored under the key app.startupDate (your choice).

Format and display the data

To access the data in a gsp you now have the <g:meta name="app.startupDate"> tag. This can be easily combined with the formatDate to display it the way you like. For the meta tag the gsp function syntax is used to prevent syntax problems while embedding it into the formatDate tag.

 <g:formatDate date="${g.meta(name:'app.startupDate')}" />

The meta data is also accessible in your controllers or taglibs with the g.meta method, just the way you need it.

That's it!

1 comment:

  1. Dear, I like all your post very much, it tells me so many thins that I do not touch before, hope you can do this job all the time. By the way, I want to introduce a useful Free Photo Recovery Software, which is a fantasy.