Thursday 24 February 2011

Exploring BootStrap.groovy

You may come across a scenario where you want to carry out a task every time your application starts or stops.

You just need to peep inside your grails-app/conf folder to find a groovy file called BootStrap.groovy.
BootStrap.groovy is a simple plain groovy script with two important closures : 'init' and 'destroy'. These closures are called upon when the application starts up and shuts down respectively.




But. BUT.. The 'destroy' closure is not guaranteed to be called at all times. The destroy closure will be called if your application exits gracefully. But if the web-server crashes or the machine reboots chances are, the 'destroy' closure would not be called. So please do not rely heavily on this one.

Let's consider a scenario where you want to send out an email to your team every time your application starts up or shuts down.

Step 1: Install the mail plugin
Let's use the grails mail plugin to send emails. To install the plugin use the command:
grails install-plugin mail

Step 2: Initialize mail properties in Config.groovy
Add some parameters to your Config.groovy file:
grails {
    mail {
        host = "smtpserver"
        port = 123
        username = 'username'
        password = 'password'
        props = ["mail.smtp.auth":"true",
                 "mail.smtp.socketFactory.port":"465",
                 "mail.smtp.socketFactory.class":"javax.net.ssl.SSLSocketFactory",
                 "mail.smtp.socketFactory.fallback":"false"]

   }
}
grails.mail.default.from = "abc@xyz.com"
grails.mail.disabled=true
app.startup.mail.to = "abc@xyz.com"
environments {
    production {
        grails.serverURL = "http:///localhost:8080/BootStrapTest"
        grails.mail.disabled=false
    }
    development {
        grails.serverURL = "http://localhost:8080/BootStrapTest"
    }
    test {
        grails.serverURL = "http://localhost:8080/BootStrapTest"
    }

}
[ We want to  send emails only if the application starts-up or shuts-down in production mode (ofcourse) ]

STEP 3: Update BootStrap.groovy
Edit the BootStrap.groovy file to send emails as follows:

import org.codehaus.groovy.grails.commons.ConfigurationHolder;
import java.util.*;
import java.text.SimpleDateFormat;

class BootStrap {

    def mailService

    def init = { servletContext ->
        println "Application starting up... "
       
        def toMail = ConfigurationHolder.config.app.startup.mail.to
        def mailSubject = "Application starting up on ${InetAddress.localHost.hostName}";
        String mailBody = '''
          
            Application started at ''' + new SimpleDateFormat("dd-MMM-yyy hh:mm:ss").format(new Date()) + '''<br/>''' +
            '''<a href=' ''' + ConfigurationHolder.config.grails.serverURL + ''' '> ''' +
            ConfigurationHolder.config.grails.serverURL + '''</a><br/><br/><br/>

            @Note : This is an automatically generated email.
        '''
       
        sendNotification(toMail, mailSubject, mailBody )
    }
   
    def destroy = {
        println "Application shutting down... "
       
        def toMail = ConfigurationHolder.config.app.startup.mail.to
        def mailSubject = "Application starting up on ${InetAddress.localHost.hostName}";
        String mailBody = '''
          
            Application shutting down at ''' + new SimpleDateFormat("dd-MMM-yyy hh:mm:ss").format(new Date()) + '''<br/>''' +
            '''<a href=' ''' + ConfigurationHolder.config.grails.serverURL + ''' '> ''' +
            ConfigurationHolder.config.grails.serverURL + '''</a><br/><br/><br/>

            @Note : This is an automatically generated email.
        '''
       
        sendNotification(toMail, mailSubject, mailBody )
    }
   
    def sendNotification(String toMail, String mailSubject, String mailBody)
    {
        println "### sending email ###"
   
        mailService.sendMail {
            to toMail
            subject mailSubject
            body mailBody
        }
   
    }
}


Well, that's about it!

STEP 4: Create a war and deploy it
Create a war file using the command:
grails war
Deploy the war in your favourite web-server and test the print statements and emails.

You could do any startup/shutdown tasks, cleanup etc you want to do using these two closures.
Hope you find this article useful.

Happy coding!

Download the sample code : bootstrap.rar


No comments:

Post a Comment