Saturday, December 18, 2010

grails - providing your own plugins configuration

sometimes you want to share some services in a plugin, which needs to be configured at runtime.

The easiest way is to provide a simple file in the grails conf diretory of your plugin and just read it and access it at runtime.

How to?

our little helper:


package binbase.core

import grails.util.GrailsUtil
import org.codehaus.groovy.grails.commons.GrailsApplication

/**
* Created by IntelliJ IDEA.
* User: wohlgemuth
* Date: 12/18/10
* Time: 1:00 AM
* To change this template use File | Settings | File Templates.
*/
class BinBaseConfigReader {

private static ConfigObject config = initialize()

/**
* initializes the object
* @return
*/
static ConfigObject initialize() {
return new ConfigSlurper().parse(new GroovyClassLoader(BinBaseConfigReader.class.getClassLoader()).loadClass('BinBaseConfig'))
}

/**
* returns the server
* @return
*/
static String getServer() {
if (GrailsUtil.getEnvironment().equals(GrailsApplication.ENV_TEST)) {
return config.binbase.test.server.toString()
}
else if (GrailsUtil.getEnvironment().equals(GrailsApplication.ENV_DEVELOPMENT)) {
return config.binbase.development.server.toString()
}
else if (GrailsUtil.getEnvironment().equals(GrailsApplication.ENV_PRODUCTION)) {
return config.binbase.production.server.toString()

}
else {
throw new RuntimeException("unexspected enviroment found")
}
}
}



our configuration


/**
* this file contains the binbase configuration for this plugin.
*
*/
binbase {
production {
key = "dasdasd"
server = "10.1.1.1"
}
test {
key = "dasdasd"
server = "10.2.2.2"
}
development {
key = "dasdasd"
server = "127.0.0.1"
}
}


and to access it in your, say spring configuration?


jndiBinBaseTemplate(org.springframework.jndi.JndiTemplate) {

environment = [
"java.naming.factory.initial": "org.jnp.interfaces.NamingContextFactory",
"java.naming.factory.url.pkgs": "org.jboss.naming:org.jnp.interfaces",
"java.naming.provider.url": "${BinBaseConfigReader.getServer()}:1099".toString()
]
}


easy, isn't it?

No comments:

Post a Comment