Friday, July 6, 2012

How to set Grails 2.0 DataSource to use JNDI for run-app command.

I wanted to setup my Grails 2.0 application to use a JNDI connection in the DataSource.groovy file. Here is how I got it working:

  1. Edit grails-app/conf/DataSource.groovy and configure a jndi data source:
  2. Edit grails-app/conf/Config.groovy and configure the Grails managed resource
  3. Edit the BuildConfig.groovy to insert the resource-ref in the web.xml
Here is the listing for DataSource.groovy:

environments {
    development {
dataSource {
dbCreate = "create"
jndiName = 'java:comp/env/jdbc/mydatasource'
}
              } 
}
Here is the listing for Config.groovy:

environments {
    development {
        grails.logging.jul.usebridge = true
jquery.minified = true
jqueryUi.minified = true
grails.naming.entries = ['jdbc/mydatasource': [
type: "javax.sql.DataSource",
       auth: "Container",
       description: "Data source for ...",
url: "jdbc:oracle:thin:@:",
username: "",
password: "",
driverClassName: "oracle.jdbc.driver.OracleDriver",
maxActive: "8",
              maxIdle: "4"
]
]
      }
}
Note: You will need to manually add postgres, mysql, oracle or db2 jdbc jar(s) to the application lib folder to use a datasource which references a driverClassName which is not provided by the Grails platform by default. 

Here is the listing for BuildConfig.groovy :


grails.war.resources = { stagingDir, args ->
def webxml = new File(grailsSettings.baseDir,"${stagingDir}/WEB-INF/web.xml")
def newxml = new File(grailsSettings.baseDir,"${stagingDir}/WEB-INF/new.xml")
def root = new XmlParser().parse(webxml)


// add the jdbc/mydatasource resource reference to the web.xml
def resourceRef = root.appendNode('resource-ref')
resourceRef.appendNode('description','The JNDI Database resource')
resourceRef.appendNode('res-ref-name','jdbc/mydatasource')
resourceRef.appendNode('res-type','javax.sql.DataSource')
resourceRef.appendNode('res-auth','Application')

def writer = new StringWriter()
new XmlNodePrinter(new PrintWriter(writer)).print(root)
newxml.withWriter { out ->
out.writeLine(writer.toString())
}
webxml.delete()
newxml.renameTo(webxml.path)
}

The code in BuildConfig is only needed to ensure the deployed war file has the required resource references. I do not believe you need that for just using the grails run-app command.




No comments:

About Me

My photo
Lead Java Developer Husband and Father

Tags