Wednesday, September 26, 2012

Grails: Configure JNDI datasource for both development and production mode

Datasource.groovy hard coded JDBC connection data are ok for quick and dirty apps, but what about a scenario where:

  • you need to setup a common DBCP datasource
  • to use it when setting up BOTH development and production?

For a Tomcat and Oracle environment, here is a solution working ok for me:

Step 1: META-INF/context.xml

<Context path="/proteys" debug="5" reloadable="true"> <Resource auth="Container" name="jdbc/db" type="javax.sql.DataSource" driverClassName="oracle.jdbc.driver.OracleDriver"
url="jdbc:oracle:thin:@127.0.0.1:1521:orcl" username="XXXX"
password="YYYY" maxActive="100" maxIdle="30" maxWait="10000
</Context>





Step2: Config.groovy
alter the environment sections as follow:

environments {
    development {
        grails.logging.jul.usebridge = true
//the following is for development mode only
//not needed to alter when deploy for production
//in production just configure meta-inf/context.xml
grails.naming.entries = [
"jdbc/db": [
type: "javax.sql.DataSource", //required
auth: "Container", // optional
description: "Data source for Proteys", //optional
driverClassName: "oracle.jdbc.driver.OracleDriver",
url: "jdbc:oracle:thin:@127.0.0.1:1521:orcl",
username: "XXX",
password: "YYY",
maxActive: "8",
maxIdle: "4"
]
]
    }
    production {
        grails.logging.jul.usebridge = false
        // TODO: grails.serverURL = "http://www.changeme.com"
    }
}

Step3: Alter the default templates in order to finetune the web.xml file and include there the necessary JNDI link:

1. run grails install-templates
2. in src/templates/war edit the web.xml template - appending the JNDI link reference:
  
 <resource-ref> <description>Datasource</description> <res-ref-name>jdbc/db</res-ref-name> <res-type>javax.sql.DataSource</res-type> <res-auth>Container</res-auth> </resource-ref>



This way, in every running or creation of war, automatically the produced web.xml will contain the above xml snippet.


Step4: config Datasource.groovy
The only content needed here is:
dataSource {
jndiName = "java:comp/env/jdbc/db"
dialect= 'org.hibernate.dialect.OracleDialect'
}
Although I don't use Hibernate / GORM / Scaffolding etc, because I needed to access an existent DB through GroovySQL, the second line regarding dialect was necessary to make grails stop complaining during building / running (or perhaps should I just drop hibernate plugin...)


From this point on, (hopefully) you can develop AND generate production WAR files using JNDI setup. And not to mention that you can now alter the db connection parameters in production, without the need of a special build


No comments: