Loading...

Sunday, April 5, 2009

Use Apache Camel plugin in Grails

We've learned how to use Apache Camel from Groovy code. In this post we learn how to use Apache Camel in a Grails application.

To include Apache Camel in a Grails application is so easy, thanks to the plugin system of Grails. We can install Camel with the Camel plugin. This plugin will add the Camel classes to our application, the possbility to send and route messages directly from services and controllers and a new Grails artifact: routes. We are going to install the plugin and create a new route which will poll a Gmail account and save the attachment to a specified directory.

$ grails install-plugin camel
$ grails create-route GetMail

In the directory grails-app/routes we have a new file GetMailRoute.groovy. The great thing is we can use closures for the filter, when and process methods from the Java DSL. The following code fragment shows how we can poll for e-mails and save the attachment to a directory. We use values from the Grails configuration in our code for mail username and password and the directory we want the files to be saved.:

import org.codehaus.groovy.grails.commons.*

class GetMailRoute {
    
    def configure = {
        def config = ConfigurationHolder.config

        from("imaps://imap.gmail.com?username=" + config.camel.route.gmail.username
            + "&password=" + config.camel.route.gmail.password
            + "&folderName=GoogleAnalytics"
            + "&consumer.delay=" + config.camel.route.gmail.pollInterval)
        .filter { 
            it.in.headers.subject.contains('Analytics')
        }
        .process{ exchange ->
            exchange.in.attachments.each { attachment ->
                def datahandler = attachment.value
                def xml = exchange.context.typeConverter.convertTo(String.class, datahandler.inputStream)
                def file = new File(config.camel.route.save.dir, datahandler.name) << xml
                log.info "Saved " + file.name
            }
        }
    }
}

That's it. We now have created our own route and when we start the application the route is executed. The only thing we need to do is to include the JavaMail libraries, because they are used by the Camel mail component. Therefore we copy activation.jar and mail.jar to the lib of the Grails application.