Wednesday, October 31, 2007

Using Groovy to easily avoid nasty NullPointerException

Groovy supports a pretty neat syntactic sugar operator to easily avoid the ugly NullPointerException: the question mark '?'.

Writing this in Java

if (name != null && param1 != null && param1.getUser() != null && name.equals(param1.getUser().getName()))
is now replaced by the much more readable Groovy
if (name && param1 && (name == param1.user?.name))
Amazing how a single character can improve readability that much and avoid potential NPEs. Also if you are curious about my use of == rather than the Java required .equals() see my post on More Groovy Sugar.

Most importantly I have inserted a hidden clue in this post and the first to solve the mystery will receive a free pop of their choice not to exceed 0.77 cents. The winner will be the first commenter with the correct answer.

Sunday, October 28, 2007

Using maven with Grails

By default Grails comes with an Ant build file to control your web application. For some of us this seems like a step backwards in technology (although apparently not for Graeme Rocher the Grails mastermind). Even though Grails doesn't support maven 1 or 2, you can get support for dependency resolution via Ivy (see Using Ivy for Dependency Resolution). Another option available is called Maven Tools for Grails (MTG). It sounds pretty promising and an improvement over Ivy, but their most recent release (v0.2) appears to work only with Grails 0.5.6 and 0.6; the current release of Grails is 1.0-RC1.

Grails vs Rails comparison

While following some of the Grails and Rails tutorials (Grails: The Definitive Guide to Grails. RoR: Creating a weblog in 15 minutes) I noticed a big difference on how they approach development. Consequently, I started a thread (Dynamic Domain classes) on the Grails user mailing list to confirm. What I found, thanks to Tim Pidgen, was that Grails is intentionally domain-centric (ie model-centric) whereas Rails is more database-centric. What's the difference? With Grails you modify the domain classes (models) and the database is updated automatically. So properties are explicitly defined in the Grails domain classes; no database modification. Conversely, with Rails you create your "empty" model class and after you modify the database (add new fields to a table) you can just refresh the page; no need to add variables to your models.

Not sure either one is right or wrong; just wanted to point out the differences because it is a pretty significant difference.

No more J2EE webapps

I got my start in my programming career over 7 years ago developing web applications as part of the intranet group for a Fortune 500 company. The group was switching from developing in Haht (I believe back then it was some type of vbscript) to Java (JSPs and Servlets). I joined the group at the moment they switched to Weblogic 5.1, JDK 1.3, and Oracle 8i (I think). It was a fast paced environment as we cranked out one internal application after another. Of course back then I wasn't the best web developer, but by the time I left I felt pretty confident in being able to hold my own (but humble at the same time).

One thing that always stayed the same throughout creating each one of those applications was the ability to rapidly develop them. What do I mean by rapidly develop? To me this means making a change and being able to switch to my browser and verify that change and repeating that hundreds of times a day.

That is how things were when I moved on 5 years later: (change + save + refresh) x 100s. Now it has been around 2 years since I have developed a real web application and for some reason that process has disappeared. For some reason my fellow J2EE developers have come to accept the process of rebuilding and hot deploying or even restarting the application server FOR EVERY CHANGE! Thousands or even millions of minutes are lost everyday by J2EE developers out there producing software like this. And to that I say, not good enough.

Maybe I am missing something; if so please enlighten me by commenting to this post. Take the JBoss Application Server (AS) 4.2.1 for example. I have tried finding better ways to deploy a WAR (exploded or bundled) on JBoss with no luck. The best I can come up with is increasing the JVMs PermSpace for better hot deployment (article), but I am still left with having to rebuild the WAR and copying it over. And sooner or later I have to restart the server. What a waste.

At one time there use to be a really slick maven 1 tomcat plugin made by that supported the ability to tell tomcat where your webapp was, preventing you from having to rebuild and redeploy. It was a huge time saver, but unfortunately this plugin is no longer supported (see here). If you are curious you can still get this plugin here thanks to Google Cache. The documentation has also been copied here.

Where does that leave me? Any language that lets me develop at a fast rate. Even if I lose tons of reusable components. I would imagine the time I save not rebuilding/redeploying more than makes up for reusable components and other goodies J2EE offers. In fact that has been the main reason for my personal quest to learn Grails and Rails. To me these languages offer the ability to deliver faster and cheaper and I believe this article supports that. If I had to start a new web project I would definitely look long and hard at either Grails or Rails.

Thursday, October 25, 2007

Effectively using Groovy Console in Grails App

Each chapter in The Definitive Guide to Grails continues to impress me. Currently I am on Chapter 4 which discusses The Application Domain. In this chapter the author uses the Groovy console within the grails app to test the domains to get some quick feedback. I got to say this ability is awesome! Not only could you do some quick testing, but I am sure it would be great for debugging purposes as well. Now obviously we want to keep testing in the console at a minimum and continue writing those unit tests, but that isn't until chapter 6. So until then here is how you can use the console in your grails app.

1) Already created a grails app: grails create-app bookmarks
2) Created at least one domain: grails create-domain-class Bookmark
3) Added some properties to the Bookmark domain (URL url)

Now cd into the bookmarks directory and run grails console. This will compile your domain class and make it available to the console. Then execute the following (CRTL + R):

def bookmark = new Bookmark(url: new URL(""))
println 'Bookmark url is ' + bookmark.url
You should see the following output:
Bookmark url is

Wednesday, October 24, 2007

Grails Tip: Enable SQL Logging

Here is a great tip while developing a Grails application to enable SQL logging (I would only recommend this in development mode).
In your grails project add the loggingSql = true property to the development closure and that is it. This was using Grails 1.0-RC1.

development {
dataSource {
dbCreate = "create-drop" // one of 'create', 'create-drop','update'
url = "jdbc:hsqldb:mem:devDB"
loggingSql = true

Then after starting your app (grails run-app) the SQL will be displayed. I was actually surprised for some reason when the list action was doing a specific select statement like "select title, author from book" rather than "select * from book".

Hotswap ability with JavaRebel

Here is a good article on using JavaRebel to reload your webapp changes without a hotdeploy like Rails and Grails do.

A Groovy switch/case example

Below is an example of Groovy's switch/case feature taken from The Definitive Guide to Grails by Graeme Rocher. I am not a regular user of Java's switch/case feature, but if it had been this way perhaps I might have.

switch (x) {
case 'James':
println "yes it is me"
case 18..65:
println "ok you are old"
case ~/Gw?+e/:
println "your name starts with G and ends in e!"
case Date:
println 'got a Date instance'
case ['John', 'Ringo', 'Paul', 'George']:
println "Got one of the Beatles"
println "Don't know"

More Groovy Sugar

Joe Kueser has some excellent posts on Groovy features (What Makes Groovy...So Groovy and More Groovy Goodies) and I would like to attempt to build on them. He has been nice enough to let me borrow The Definitive Guide to Grails, which so far has been an excellent resource for Groovy and Grails (probably one of the best technical books I have read in awhile).

Expando Objects
Joe does a nice job of explaining this handy new class. Here is another example taken from the Grails book by Rocher:

fred = new Expando()

fred.firstName = "Fred"
fred.lastName = "Smith"

fred.age = 40
fred.happyBirthday = {

assert fred.age == 41

You can easily play around with this code with groovy's console (/GROOVY_HOME/bin/groovyConsole). As you can see Expando allows you to define an object, its properties, and its methods at run time. Keep in mind that a method is defined by setting a closure to a property that can be later called like a regular method. One immediate use I can see for Expando is in unit tests.

Groovy's == operator
This is very important for existing Java developers. Groovy's == operator is different than Java's in that it does not evaluate object identity, rather it delegates to the object's equals method. To accomplish object comparison, Groovy introduces a new is method:

The Groovy Truth
Term used by Rocher in the Grails book and coined by Dierk Koenig, that explains the Groovy concept of what is true and what is not. Here is an example of what can be passed to if statements in Groovy and will evaluate to false:

  • A null reference
  • An empty or null string
  • The number zero
  • A regex Matcher that doesn't match
This makes those nasty Java if statements much cleaner.

if (str != null && str.length() != 0 )

now becomes

if (str)

More Mt. Dew sugar to come.

Tuesday, October 23, 2007

Enabling remote access to JBoss 4.2

Today I had an issue remotely accessing my JBoss instance running on another machine. Unknowingly, JBoss 4.2 binds specifically to by default (see below for me details). Thankfully they had a simple solution; just append -b to your startup script to bind to all interfaces. So to start JBoss on linux when I know I want to access it remotely I do:

./jboss/bin/ -b

ReadMe.html content on this subject:
"JBossAS now binds its services to localhost ( *by default*, instead of binding to all available interfaces ( This was primarily done for security reasons because of concerns of users going to production without having secured their servers properly. To enable remote access by binding JBoss services to a particular interface, simply run jboss with the -b option. To bind to all available interfaces and re-enable the legacy behavior use -b In any case, be aware you still need to secure you server properly."

Sunday, October 21, 2007

Great JetGroovy plugin feature for Idea+Grails

Just started using the JetGroovy plugin in Idea and I have to say initially it Rocks! Included is a screenshot of the plugin in Idea version 7 after I created a domain (aka model). Notice how there are nifty buttons for that domains Controller, Views, Domain Tests, and Controller Tests. I was constantly using this ability even in the 5 minutes it took me to create my Hello World grails app. Nice work guys.

Tip for using Grails in Idea

Recently I tried creating my first Grails application using the JetGroovy plugin available in Idea (version 7.0). However, I have Linux (Ubuntu 7.10) and you don't get those nice little icons to start Idea when you install it. Consequently when I tried to create a new Grails project I received the following error:

grails: JAVA_HOME is not defined correctly; can not execute: java

How in the world is that possible I thought to myself? What half decent java programmer doesn't have JAVA_HOME set? Oh but then I remembered my special start script responsible for starting Idea. Idea requires the variable JDK_HOME to be set, but Grails within Idea needs JAVA_HOME. Therefore, here is my new script I use to start Idea 7 which allows me to create new Grails projects. And don't forget Idea 7 on Linux requires JDK 1.6.

sh -c 'export JDK_HOME=/workspace/java/jdk1.6.0_03;export JAVA_HOME=/workspace/java/jdk1.5.0_12;/workspace/java/idea-7361/bin/'

Saturday, October 20, 2007

Performance tuning Java

Here is a centralized location for information on performance tuning the JVM:

Specifically, here is a great white paper on tuning ideas that include some great examples.

I have to admit I am rather new to this subject, but am really interested in learning more. From what I have read and also learned from my co-worker Travis Chase, the best and simplest improvement you can make is running your JVM with the -server option. Most likely your JDK came with the default -client set which starts up faster for development reasons, but should be switched to -server for better performance in production environments. However, before you start performance tuning be mindful of the Ergonomic settings which automatically set your defaults. For example for Window users (32-bit) the -client option is automatically set. Here is some more information on Ergonomics for Java 5.0.

Friday, October 19, 2007

Upgrading to latest Ubuntu Gutsy Gibbon (7.10)

Here is the information needed to upgrade Ubuntu from 7.04 to 7.10:

Friday, October 12, 2007

Linux generic start and stop scripts

If you are following my twitter account, you will notice that I recently switched to Ubuntu and will never look back. Sometimes I find myself having to create start and stop scripts for weblogic, glassfish, hudson, etc. All these scripts are generic enough that you just copy and paste and modify some names. But I don't do it frequently enough to have memorized the syntax. Therefore I want to document and explain start and stop scripts that are generic enough they can be used for almost anything.

Next you will see the exact start and stop scripts we use in our Continuous Integration environment to manage hudson.

Start Script -
nohup nice java -jar hudson-1.136.war --httpPort=8282 > ./hudson.out 2>&1 &

Stop Script -
kill `ps -ef | grep hudson-1.136.war | grep -v grep | awk '{ print $2 }'`

Start Script explained
nohup nice
I don't claim to be an advanced linux user, so don't expect a master's thesis on this one. Nohup on Wikipedia tells us that nohup "is a unix command that is used to run another command while suppressing the action of the HUP (hangup) signal, enabling the command to keep running after the user who issues the command has logged out. It is most often used to run commands in the background and output that would normally go to the terminal goes to the file called nohup.out if it is not redirected". Nice allows you to run a program with a modified scheduling priority with -20 being most important and 20 being less important. I believe the default when using nice without a value is 0.

The '>' command
Takes the output from my java command and places it in the file ./hudson.out.

The '2>&1' command
2> is standard error and &1 is standard output. So combined it says take standard error and put it in standard output, which the previous command said take standard output and put it in ./hudson.out. So together these two commands put standard output and error in ./hudson.out.

The '&' command
When appending it at the end like it is, it means runs this process in the background.

Stop Script explained
Uses the Process Status (ps) command and grep to search for a process that includes the text 'hudson-1.136.war'. Then it uses awk to split out the output from ps to get the Process ID. Once the Process ID is found it passes it to the kill program to stop the daemon (pipes rock!). This method of using kill to stop a process is rather brute force and does have some flaws if you don't use unique text to search (multiple users running hundreds of programs). Most programs, say weblogic, for example should already have a stop script, so obviously prefer those over my example.

So what if you want the startup script to begin at boot time? Well, add a soft link pointing to your startup script (ln -s /home/jlorenzen/bin/ in /etc/init.d/. Then use the update-rc.d command to add it at boot time (update-rc.d softlink_name defaults).

Update: Do to this posts popularity, I created a github account and uploaded these scripts so they can be easily shared, referenced, and forked. See for more information.

Ubuntu JeOS (Just Enough Operating System)

Back in September, Ubuntu announced a new addition to the family called JeOS (Just Enough Operating System). Ubuntu JeOS (pronounced "Juice", no not the Barry Bonds Juice that can be denied as not knowing) , "is an efficient variant of the popular desktop and server operating system, configured specifically for virtual appliances". The article goes on to state, "JeOS Edition has been tuned to take advantage of key performance technologies of the latest virtualisation products from VMware".

Looks really interesting and actually comes at a good time as I have been playing around a lot with VMware, DSL (Damn Small Linux), and Ubuntu Server.

To read the entire announcement go here.

Tuesday, October 9, 2007

Compressing ginormous files

I know most of my fellow linux coworkers already know this trick but since I am fairly new to linux and I know others are I am going to show how one can compress ginormous (quote from the movie "Elf") files.

First run: tar -cf filename.tar /directory/*
Then for best compression run: gzip -9 filename.tar

The to uncompress the file run: tar -xzvf filename.tar.gz

Saturday, October 6, 2007

Comparing Open Source Web Service Stacks

Here is one of the best articles I have read comparing the various open source web service stacks. Previously I have always referenced this page, which is still an excellent source of information. The author interviews lead developers from each project: Apache Axis2, Apache CXF (previously known as XFire), Spring Web Services, JBoss WS, and Sun's Metro.

First my opinions. Axis1 was one of the first open source stacks available and Axis2 was suppose to be a complete overhaul. From other articles I have read the performance isn't that great and my first use of it wasn't a good experience. I have had really good luck with XFire and really like how it is just a jar that you can include in your WAR. Spring Web Services is really new (they just released version 1.0). I really like the spring products and wouldn't hesitate to try this one. Their documentation is really good and they emphasize a top-down approach (which is honestly the best way, but not the most fun). Not sure why anyone would use JBoss WS if it isn't portable to other containers. Based on their wiki they only state it works in JBoss. Sun's Metro is making a lot of headway and I would recommend it to anyone. It seems to be the most mature in implementing the newer WS-* specifications and boasts the ability to interoperate with .Net services.

Back to the article. Here are some highlights for those not wanting to read the entire article:

  1. CXF can support returning JSON
  2. Use SXC to improve JAXB performance.
  3. Axis2 is the only one supporting WSDL 2.0
  4. All except Spring-WS and JBossWS implement WS-Addressing and WS-Reliable Messaging
  5. Metro is the only stack with support for WS-AtomicTransaction and WS-Coordination, which are hooked up to J2EE/Java EE transactions.
  6. CXF supports REST via annotations similiar to JSR 311. Spring-WS doesn't support REST.

Friday, October 5, 2007

Grizzly Port unification

Looks like one of my anticipated features in Grizzly is finally here in their latest version 1.6.1: Port Unification. According to this javalobby article, port unification has been implemented and can now be used in glassfish v3. For OpenESB users this means consolidating the HTTP ports between glassfish v2 and the HTTP BC. What this also means is being able to accomplish the same thing in the RSS BC since we use grizzly to service the HTTP GET requests for feeds.

One of the nice benefits this adds to glassfish v3 is the ability to now consume only one port verses 2 or 3. Now phobos, comet, and jruby can run on the same port and grizzly can determine the correct Adapter.

To stay current with this RSS BC enhancement watch issue #8:

Tip to improving glassfish performance

Today I was reading an entry (Customizing Glassfish v2 with 23 unpublished properties) from the Gestalt Shared Feed about hidden properties in glassfish v2. One very interesting tip to improve performance for glassfish would be to set the enableSnoop to false. Basically setting this property to false stops grizzly from logging the requests/responses to the log file. See the rest of the article on how to actually set the property in glassfish.

Monday, October 1, 2007

Using the OpenESB J2SE version and netbeans

As I mentioned in JBI deployment options, OpenESB can run as a standard J2SE application. This is a nice option that has some advantages such as getting started quicker without the need of downloading the rather large (300+MB) OpenESB bundle that includes glassfish/openesb and netbeans. The JBISE version is only 4.3MB. For those of you not needing a J2EE container this might be a valid option.

The only other missing piece is the tooling support to create Composite Applications. This is included in Netbeans v6 which is a part of the large OpenESB bundle. But since you are not downloading that you need to ability to get netbeans v6. Here is the netbeans v6 nightly builds location:

Good luck and happy downloading.