Category Archives: Java


After not requiring Groovy for a while, I went about installing it today and was directed to GVM. Very interesting and quick to install. But essentially a RVM knockoff for java.

Groovy: Writing to a File

Recently had a requirement at work to update multiple maven pom files with the correct <version>. After performing a grep for the files that I needed to change I wrote this simple grroovy script to open each file replace the text and then save the file.

def fileName = "pom_location.txt" // Locations of the pom files
def sourceText = "1.2-SNAPSHOT"
def replaceText = "1.2"

new File(fileName).eachLine { line ->

def pomFile = line
pomFile = pomFile.replaceAll("\\s","") + "/pom.xml"
def file = new File(pomFile)
println "Editing ... $pomFile"
def fileText = file.text
fileText = fileText.replaceAll(sourceText, replaceText)

Thanks to David Heffelfinger

Executing a class using the Maven Exec Plugin

Today, in a java maven built webapp, I needed to have a way to execute a class from the commandline. As maven was already building package into a war, I needed something extra.

Bring in the Maven Exec Plugin:

Pretty useful as I was able to define a specific profile for this class and now execute it by:

mvn compile -P run_my_class

Have a look at the documentation.

Also a good quick overview is provided by

Java SimpleDateFormat Example

I keep forgetting the exact syntax of the SimpleDateFormat. The below example passes in a month value say “02” and returns “February”.
However this can work to transfer any date format into another format.

Refer to the Java 7 doc for the Date and Time Patterns

import java.text.SimpleDateFormat;

public String formatMonth(String month) {
SimpleDateFormat monthParse = new SimpleDateFormat("MM");
SimpleDateFormat monthDisplay = new SimpleDateFormat("MMMM");
return monthDisplay.format(monthParse.parse(month));

Result = February

Finally Java gives us a switch on a String

I haven’t really paid much attention to the new features in Java 7. But at the Canberra Java User Group meeting last week a presentation was given on the new features of Java 7. It was actually quite interesting, especially the history bit … but the take home was the ability to use a String with the Switch statement. Definitely in the “About time” category. It has been one of those pet peeves that I just had to accept. (This was especially apparent when working on Java code after doing a few projects in Ruby.)

For example:

String color = "red"; 

switch (color) { 
case "red": 
	System.out.println("Color is Red"); 
case "green": 
	System.out.println("Color is Green"); 
	System.out.println("Color not found"); 

REST in Spring without using Spring Webservices

I quite like using Spring. Especially when using the Spring/Hibernate combo.

About a year ago I started using Spring for a whole heap of REST webservices I was writing. In the process I found it surprisingly easy. Various other colleagues experimented with RESTLET ( and Jersey ( But as I wanted to use Hibernate easily and I was using Spring MVC to build the client component of the project I was working on, so I used Spring MVC to build the services. Pretty simple. (Even though I refer to Spring 2.5 in the pom file, I am not using the features of 2.5.)

Here’s an example:

I have created a simple webapp using maven. The webapp is called rest-webapp. I have created a stupid service that retrieves the name of an evil programmer.

This means that the request would look like:

and this would return:
Dr Evil

I wrote a simple class that does this and also returns a 404 error if the request for tne evil programmer does not exist.

This means that the request would look like:

would return a 404 error with the message: HTTP Status 404 – This evil programmer does not exist!!




<?xml version=”1.0″ encoding=”ISO-8859-1″?>
<!DOCTYPE web-app PUBLIC “-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN” “http://java.sun.
<description>Test Rest Service</description>

mytest-servlet.xml (Spring Application Context)

<?xml version=”1.0″ encoding=”UTF-8″?>

<bean id=”urlMapping” class=”org.springframework.web.servlet.handler.SimpleUrlHandlerMapping”>
<property name=”mappings”>
<prop key=”/evil/programmers/*”>myController</prop>

<bean id=”myController” class=”au.bandaid.programming.controller.MyTestController”>


package au.bandaid.programming.controller;

import java.util.Hashtable;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

import au.bandaid.programming.exception.HttpStatusException;

public class MyTestController implements Controller {

private Hashtable list;

public MyTestController() {
list = new Hashtable();
// Set an arbitary list
list.put(“1”, “Dr Evil”);
list.put(“2”, “Big Bad Billy”);
list.put(“3”, “Big Bad Billy”);
list.put(“4”, “Stevie Exception”);
list.put(“4”, “Frank Void”);

public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {

// Determine the type of method
try {
if (request.getMethod().toUpperCase().equals(“GET”)) {
writeResponse(response, “text/xml”, HttpServletResponse.SC_OK, get(request));
//else if (method.toUpperCase().equals(“POST”))
//else if (method.toUpperCase().equals(“DELETE”))
//else if (method.toUpperCase().equals(“PUT”))

else {
throw new HttpStatusException(HttpServletResponse.SC_NOT_IMPLEMENTED, “Operation: ” + request.getMethod() + ” not supported.”);
catch (HttpStatusException e) {
response.sendError(e.getStatusCode(), e.getMessage());
catch (Exception e) {
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString());

return null;

private String get(HttpServletRequest request) throws HttpStatusException {

// Grab some parameters
// I am not using any now
String type = request.getParameter(“type”);

// Look at the request
// am expecting rest-webapp/programmers/1
Pattern p = Pattern.compile(“[1-9]+”);
Matcher m = p.matcher(request.getPathInfo());
String index = “”;
if (m.find()) {
index =;

if (!list.containsKey(index)) {
throw new HttpStatusException(HttpServletResponse.SC_NOT_FOUND, “This evil programmer does not exist!!”);

return “” + list.get(index) + ““;

private void writeResponse(HttpServletResponse response, String contentType, int statusCode, String ouput) throws IOException {
PrintWriter out = new PrintWriter(response.getOutputStream());


Some extra reading: – Comprehensive REST Support

The Hans Gruber effect – Using Spring and Hibernate JPA

At the end of the movie Die Hard John McClane (Bruce Willis), releases the watch from Holly’s wrist which results in Hans Gruber (Alan Rickman) falling to his death. Hans was hanging out of a window in a huge high rise, holding onto the wrist of Holly. The iconic scene has the view from their perpective seeing Hans flapping his arms moving further and further away from them as he falls to the ground. In some ways I felt like Hans flapping my arms trying to make Hibernate JPA and Spring work, whilst gravity was pulling me closer to my death …

Well my work colleague, Dave, first put me on the path to enlightenment. He references Ignacio’s experience or rather what he did to make the thing work. However, in all the references I flapped more and more as they all do it a little differently. Also Ignacio uses Spring auto-wiring and recently in a Spring course by Interface 21, the presenter, reckoned that auto-wiring should not really be used.

Maybe the biggest factor in my Hans Gruber impersonation is that at times everyone else makes it look so easy while I feel like a dufus. But I did eventually succeed.

Here’s how it worked for me:

I pretty much based everything I did on Getting Started with JPA in Spring 2.0, however I couldn’t get it to work properly. I also used Hibernate JPA and therefore had to make a few changes. I will list these changes below.

Issue 1: Gather all the required Jar’s

This is a bit of a problem as many of the blogs I read didn’t give a list of Jar’s required. I downloaded a version of:

* Spring 2.04
* Hibernate 3.2
* Hibernate Entity Manager 3.3.1

From these downloads a I used the following jar files. Still not sure if they are all needed but here is the list:

classes12.jar (I am using Oracle DB)

Issue 2: Spring config file

There were a few issues with setting up the config file.

Note the following:

  • Include the annotations for transactions, this becomes relevant when performing transactions and a solution for Lazy fetches.
  • I couldn’t get it to wotk with ContainerEntityManagerFactoryBean so I used LocalContainerEntityManagerFactoryBean

<beans xmlns=””

<!– Put this here if you want to use transactions –>
<tx:annotation-driven transaction-manager=”transactionManager”/>

<!– This comes from the blog –>
<bean id=”restaurantDao” class=”blog.jpa.dao.JpaRestaurantDao”>
<property name=”entityManagerFactory” ref=”entityManagerFactory”/>

<!– I used Oracle just change the dialect below to match your db –>
<!– I couldn’t get the ContainerEntityManagerFactoryBean to work
so I used LocalContainerEntityManagerFactoryBean –>
<bean id=”entityManagerFactory” class=”org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean”>
<property name=”dataSource” ref=”dataSource” />
<property name=”jpaVendorAdapter”>
<property name=”showSql” value=”true” />
<property name=”generateDdl” value=”false” />
<property name=”databasePlatform” value=”org.hibernate.dialect.Oracle9Dialect” />

<bean id=”dataSource” class=”org.springframework.jdbc.datasource.DriverManagerDataSource”>
<property name=”driverClassName” value=”oracle.jdbc.driver.OracleDriver” />
<property name=”url” value=”jdbc:oracle:thin:@xxx:1521:xxx” />
<property name=”username” value=”bandaid” />
<property name=”password” value=”bandaid” />

<bean id=”transactionManager” class=”org.springframework.orm.jpa.JpaTransactionManager”>
<property name=”entityManagerFactory” ref=”entityManagerFactory” />
<property name=”dataSource” ref=”dataSource” />


Issue 3: Lazy vs Eager Fetching

All was happy until I started playing around with lazy fetching. The problem was that I kept getting a session ending error after the initial read. This appears to be a Spring issue. Spring closes the database connection and you try to do the lazy fetch it throws an error that basically means the database connection doe snot exist. So after reading many blogs, pulling my hair out and crying myself to sleep at night, I stumbled onto the following blog Hibernate Lazy Loading.

I discovered a few work arounds for Spring:

  1. Don’t make any Lazy calls and just call the collection manually. I didn’t like that option.
  2. Make everything Eager. Not a good one either.
  3. Implement the OpenSessionInViewFilter in the Spring config. I read a few more blogs, referenced all the spring books I had and still couldn’t get the thing to work. It does seem to work but I couldn’t figure it out.
  4. Use the Spring @Transaction annotation for the method or class. That’s why I declared the annotations in the above spring config file.


I am very happy. Smiles all round. After many days impersonating Hans Gruber, I finally got the thing to work. It’s really simple and easy. I will tell my friends about it.