Wednesday, July 11, 2012

How to add external jar libraries to your Grails 2.0

I needed to setup my Grails application with a custom library that was not provided by traditional maven public repositories. Here is how I got it working:
1. Setup a local folder structure to hold custom libraries using maven/ivy naming convention. Add a system environment variable for the path to the local folder
2. Edit grails-app/conf/BuildConfig.groovy to add the local repository.
3. Edit grails-app/conf/BuildConfig.groovy to add the new local dependency jar.
4. Test the build by running grails command dependency-report
5. Create a new build with grails command war
6. Regenerate the Spring Source Tool Suite project and classpath files using grails command integrate-with --eclipse

Listing for step 1 Local Repository
C:.
├───lib
│   └───com
│       └───fourgablesguy
│           └───myapplication
│               └───1.0.0
│                   └───myapplication-1.0.0.jar

set LOCAL_REPOSITORY=C:\lib
Listing for step 2 and 3 BuildConfig.groovy
if (System.getenv().LOCAL_REPOSITORY == null) {
 println "*"
 println "* ERROR - LOCAL_REPOSITORY environment variable is undefined."
        System.exit(1)
} else {
 println "* LOCAL_REPOSITORY=" + System.getenv().LOCAL_REPOSITORY
 localRepoDir = System.getenv().LOCAL_REPOSITORY
}
grails.project.dependency.resolution = {
    //snip 
    repositories {
        //snip 
 mavenRepo "file:${localRepoDir}"
    }
    dependencies {
        //snip 
        compile "com.fourgablesguy:myapplication:1.0.0"
    }
}
Listing for step 4-6 Grails commands
grails dependency-report 
grails package
grails integrate-with --eclipse

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.




Wednesday, June 27, 2012

How do I set a new version for my existing Grails application?


I have been working with Grails lately for a new web project. So far it has been hard, but a lot of fun. I am new to Groovy as well. But I do have experience with Spring and Hibernate, which the application framework is built on top of. I found a JIRA issue which matched an error I was seeing in my code.

I am using Spring Source Tool Suite (STS) to develop the application and, by default, new projects are set with a version of Grails preinstalled by the Grails plugin, in my case it was at version 2.0.3. The fix I need is in version 2.0.4. This brought me to a question: How do I switch to a newer version of Grails or backport a fix to my version? The Grails documentation is quite extensive but I did not find a command to do this. This command:
grails set-version 2.0.4

| Loading Grails 2.0.3
| Configuring classpath.
| Environment set to development.....
| Application version updated to 2.0.4

Only sets your application's declared version, not the version of grails used to build and run your application.

Under the covers, this command is simply modifying the application.properties file and setting the property named app.version to the value you specify.

This same file has a property named app.grails.version, my app has this set to:
app.grails.version=2.0.3
Changing that value to 2.0.4, will not change what version of Grails you application is built with in STS, but I changed the value to 2.0.4 anyway. To get on 2.0.4 and resolve my issue I needed to first download the version of Grails I want to switch to. Extract the download to a file location on my system. Then in STS, I added the new version to the Grails plugin and set it as the default version. This is done using Window | Preferences | Groovy | Grails | Add. Finally in STS, use the grails command prompt (ctrl+alt+shift+g) to run

grails clean
| Loading Grails 2.0.4
| Configuring classpath.
| Environment set to development.....
| Application cleaned.

I am now  able to run my  application, all the classes are compiled with the new Grails version and the project is upgraded.


| Loading Grails 2.0.4
| Configuring classpath.
| Environment set to test.....
| Compiling 1 source files.....
| Compiling 50 source files.
| Running 2 unit tests... 1 of 2
| Running 2 unit tests... 2 of 2
| Completed 2 unit tests, 0 failed in 13013ms
| Tests PASSED - view reports in target\test-reports
I am still not sure about the process to backport JIRA fixes as patches to an older version, but this solution is sufficient for me for the current state of my project. Maybe I will post a question to stackoverflow about porting fixes to older versions.


If you are starting a Grails project, be sure to bookmark the Groovy, Grails, Spring, Hibernate, forums and  JIRA sites. Be aware of what versions of these technologies your project is running so you can intelligently find and resolve problems.


Tuesday, April 3, 2012

NClass - Free UML Class Designer



If you are ever looking for a nice UML class designer look no further than NClass. I used this for a project to port a large code base from .NET to Java. The program was able to reverse engineer UML from compiled .NET code. Love it.

Thursday, March 29, 2012

A Spiritual Feast

I am excited for the 2012 LDS spring conference sessions.

Come listen to living prophets


Come listen to living prophets

You can listen or watch them for free online. Consider accepting my invitation to attend conference and pull up your own chair to a spiritual feast.

Friday, March 23, 2012

Performance settings for production weblogic deployments

Put this in the weblogic.xml under WEB-INF folder: 
<!DOCTYPE weblogic-web-app PUBLIC "-//BEA Systems, Inc.//DTD Web Application 8.1//EN" "http://www.oracle.com/technology/weblogic/servers/wls810/dtd/weblogic810-web-jar.dtd">

<weblogic-web-app>

<container-descriptor>
<servlet-reload-check-secs>-1</servlet-reload-check-secs>
</container-descriptor>

</weblogic-web-app>

For JSPs you can also set this in weblogic.xml:

<jsp-descriptor>
<jsp-param>
<param-name>pageCheckSeconds</param-name>
<param-value>-1</param-value>
</jsp-param>
</jsp-descriptor>


Unless you are altering servlet code and JSPs on the fly in production (bad idea), there is no need to ever check for changes. These two settings can help with performance because without them, Weblogic will have periodic threads blocking
requests to poll the filesystem for Servlet or JSP changes.

So by default in thread dumps you will see one or more of this sort of thing:

waiting for monitor entry [c4f7f000..c4f7fc28]
     at weblogic.servlet.internal.ServletStubImpl.checkForReload(ServletStubImpl.java:771)

unless you disable that like shown above.

Monday, March 5, 2012

8 reasons why your browser does NOT send the cookie as part of the request

There are several reasons why a cookie you attempted to set on a remote client browser as part of a HTTP response is NOT sent back on the next request:
  1. The domain of the request does not match the cookie's domain attribute
  2. The path of the request does not match the cookie's path attribute
  3. The cookie has expired
  4. The cookie was set the secure attribute and the client's request was plain text HTTP.
  5. The cookie was set with the httpOnly attribute and the client's request was not HTTP/HTTPS (e.g. you used FTP).
  6. The client has disabled cookies globally or specifically for your domain.
  7. The client deleted or cleared the cookie that was set before the next request was made.
  8. The client's browser does not trust the SSL certificate used to sign your site and you are trying to use HTTPS communication.
Your domain of the request does not match the cookie's domain attribute
This one appears to be the most obvious of them all but does have a small gotcha. A cookie set for domain www.google.com will not be sent for a request to www.yahoo.com. We can understand that, but it will also not be sent for mail.google.com! The domain mail.google.com does not match www.google.com, so cookies set on one do not affect requests for the other. So when setting cookies that should be sent for all sub-domains: use .domain.com as the cookie's domain attribute, i.e. leave off the sub-domain (www) and just lead with the . prefix.

Your path of the request does not match the cookie's path attribute
If you set the path to /, all paths on the domain are going to send the cookie with the request, even if the request is for an image.. So use path wisely to avoid unnecessary overhead in your requests, especially if you are a heavy user of cookies. you only get one cookie path, make it count. You will be ding'd on Yslow if you don't avoid sending cookie info for images.

Your cookie has expired
Duh. Don't expect old cookies to join your request party. Be careful of short expiration on cookies, they may go stale before they are even set.

Your client has disabled cookies globally or for your specific domain
This is why it is important to document the requirements for your application. If you need cookies enabled (or even better detect that cookies are not enabled), tell the user to enable them (and how to enabled them) in a big red alert box with a flashing siren.


This is my list, do you have other reasons to add?





About Me

My photo
Lead Java Developer Husband and Father

Tags