Archive for the Java Category

Those who have completed the SCJP exam would recall some of the challenges faced while tackling weird looking code problems aimed at thoroughly testing your understanding of the Java language. While the SCWCD exam has minimal code related questions, which are easier to interpret, it does have its own series of challenges to overcome. Preparation is one of them and can be quite daunting for those new to JEE.

Before I begin, I would like to highlight some of the advantages I experienced after obtaining the certification. Firstly, it provides you with an in-depth knowledge of the JEE platform. Your mind may not retain much of what you studied over the passing months but the strong fundamentals do help you to question best practices when working on a project. Secondly, it also allows you to formulate solutions based on what JEE has to offer and thirdly, the fundamentals could also aid you to spot similarities with other web technologies on the market and eventually become proficient in them.

To ensure that your preparation is effective, it is very important to choose a good study guide. For this, I chose the Head First: Servlets and JSPs book. There are two reasons that made me use this book. Number one, it was an advice from my colleague Glen Worsley, who had already taken and passed the exam. Number two, Head First books market themselves as “Brain Friendly” guides. I cannot stress enough the importance of having a brain friendly guide for something rather complex like JEE. Most textbooks are crammed with words and too much details. The simple diagrams and humorous examples (it’s good to be idempotent!) do help the reader to retain important bits of information. There is plenty to remember and selecting an exam date is as tough as hitting a moving target as I came to learn later.

Progress was slow. The original plan was to complete a chapter a week. An ideal plan it was, but I only managed to read through about 2 or 3 chapters within a month. I dutifully did the questions in the book after each chapter and found them rather tough which is for my own good. I did reasonably well on the first few but I was having a really difficult time when I got to the chapters on expression language and JSTL. There are several ways to accomplish the same thing and one of the difficulties is in trying to remember the JEE APIs taught in the earlier chapters as well as the various JSTL/action tags, which exist for similar goals. A handy tip would be to memorise and understand the various possible tags within the deployment descriptor by heart. Doing so would mean that you have studied a few portions of several chapters in the book. Six months had passed by the time I finished the book and the chapter questions.

While searching the Internet for good SCWCD training tools, I eventually came across Enthuware’s software. Its a really affordable exam simulator with about 8 mock exams and various questions for each chapter. Questions are categorized by their level of difficulty. I attempted the questions for all the chapters and found them not as tough as the ones in the book. Nevertheless, those questions were good practice as it helped me to gauge my strengths and weaknesses. These were presented as graphs and they are a good indicator of which chapters to re-study.

The mock exam questions found at the back of the Head First book is the penultimate gauge to indicate your level of preparedness. It should be done only once and when you truly feel that you know JEE kung-fu. Doing the mock exam too many times can lead to inaccurate results and a false sense of security which may lead to a severe defeat on exam day. Another technique I developed while revising for the exam is to tackle questions from random chapters in the book. This indicates that you are well trained to handle any surprise attacks which you may not see coming. It also means that you have kept the study material from both the early and late chapters close to your heart.

I eventually picked a good date to sit for the exam and passed with a good score. As usual, I marked the unsure questions and did the ones I knew. I had about an hour of extra time by the time I finished my first run of the questions. I then used the remaining time to ponder on the marked questions. Months of preparation had finally paid off and I was able to enjoy a healthy balance of work and personal life once again. As with most exams, the preparation does require some amount of sacrifice to personal time, but the returns and benefits are rewarding.

We have a new release of the GWT/Spring Shine Reference project out here (ver 0.3), which is an important improvement on the previous releases.

  • Now includes proper Data Layer : using Spring 2.5 annotations, Hibernate 3.2 and integrated HSQLDB runtime memory database.
  • Upgraded GWT gui to include save/delete/select functionality linking into the exposed Spring services
  • Maven now builds deployable war files for both the presentation (gwt) and service (spring) layers that can be dropped into a standard Tomcat install.

All of this should “just work” straight out of the box - tested on linux (fedora), mac and windows systems. Follow the “Getting Started” instructions on the project page.

This was just too painful! Unfortunately I would have to recommend to people to stay away from Ganymede if you use Subversion for version control until they sort out connectors, update sites etc. After installing on 4 machines (3 macs, 1 linux) i’ve finally got 3 out of 4 working - but one of them (one of the identical macs!) just wont fix and the others were such hit and miss affairs. In theory, all you need to do is add in the update site as detailed on the Polarian site

Update Sites - Direct your Eclipse update manager to both the following update sites…
* Subversive plug-in update site :
http://download.eclipse.org/technology/subversive/0.7/update-site/

* Subversive SVN Connectors update site
http://www.polarion.org/projects/subversive/download/eclipse/2.0/update-site/

I realise that its to do with license issues etc, but Eclipse really has to “just work” out of the box with Subversion soon. The update manager really needs work too. Whoever put the “Close” button where they did while hiding off the “Install” button needs to go on a design course - so fed up clicking “close” just when i’ve chosen “install”….!

Once in a while new technologies mature and coalesce together to provide a new and viable platform that radically change the traditional development landscape. In recent years Ruby on Rails has been the poster child of all that is new and groovy; the “must learn” skill for developers, leaving behind those “legacy” Java systems built over the last ten years.

It looks like GWT (Google Web Toolkit) is challenging those ideas. We’ve written an article explaining the steps involved putting together a multi-tiered system using GWT and Spring together (with both layers built by Maven). This also comes with an Open Source reference project showing in detail how to get up and running very quickly. Full details here.

What makes me particularly happy about all this is , is that it looks like there is still life in the old Java dog yet :)

First came light-weight containers such as Spring which provide some of the useful features of application servers, but with less constraints over both design and deployment. Now we have Web Beans:

  1. A Web Bean does not have to be an EJB
  2. Web Beans should be executable outside the EE environment

This is further support for the move away from the over-engineered and invasive approach in the original J2EE specification to a simpler POJO based model. However the Web Beans proposal attempts to stay within the formal J2EE fold by choosing to delegate some services to the application server:

” … not every component needs the services that EJB provides (transaction demarcation, authorization, etc). However, Web Beans will not duplicate this functionality, so when these services are needed, the Web Bean should be written as a session bean.”

In contrast, Spring implements some services (such as transaction management) and supports integration with other components to support others - for example Hibernate for persistence, Terracota for clustering - and does not rely on an application server (although it can be deployed within one).

It will be interesting to see where this ends up, and whether Web Beans ends up moving closer to or further away from the model adopted by Spring.

But what about the application server ? Certainly not dead, but perhaps leaner.

Hopefully these POJO based approaches will make design decisions less about the deployment architecture and specification constraints and more about implementing the business logic.

Last month I attended a seminar about Virtual Worlds and in particular Second Life, during which it was suggested that Second Life had been through the hype stage, passed over the bell curve of growth and the “cool” factor, and was now on the other side of the curve with as many articles in the press concerning problems and issues than there were previously praising it.

Is the same happening with Rails?

For the last couple of years there has been a great deal written and tried with Rails which has been overwhelmingly positive (and in the main rightly so). However, I am detecting a swing in the coverage, and in particular the recent blog from cdbaby.com describing why a Rails re-write of a PHP system was completely abandoned, details here.

There have been a number of successes at Shine using Rails, and it is a great technology, but is it really that good a fit in the enterprise beyond new greenfield systems? Is there compelling reasons to replace the (in the main) Java systems we have built and maintained over the last 10 years? Is GWT a better solution for existing corporate systems - even just from the point of view that the retraining involved in GWT is trivial for a Java developer as GWT development is all written in Java? Or will improvements in Rails, for instance JRuby, allow greater integration into existing systems and hence speed its adoption?

So back to the original point, where on the bell curve is Rails….

In a Java program, we sometimes need to make sure we close a resource after we’ve finished using it. Common examples are files, Hibernate Sessions, JDBC Connections, Statements and ResultSets. The database-related ones are particular important - if we don’t close them, we can be left with unclosed connections to the database. This means that we could eventually run out of connections. Sure, these objects are supposed to close their underlying resources when they’re garbage collected, but sometimes they don’t get a chance to (for example, if the JVM exits suddenly) and sometimes they don’t do it even though they’re supposed to (some dodgy JDBC drivers can do this - I once used one that would leave the underlying database connection open if you didn’t close the ResultSet - even if you closed the Connection object).

Of course, I’m probably not telling you anything new here. And you’ll probably tell me that all you need to do is provide a ‘finally’ block that closes the resource.

Well let me first start by saying that frameworks like Spring provide helper classes that can do a lot of this stuff for you. You mightn’t think that it’s much effort, but as you’ll see soon, doing it properly can actually result in quite a lot of code. So if you’ve got the chance, check out Spring’s JdbcTemplate or HibernateTemplate classes. I don’t think you even need to use all of the other Spring infrastructure with them - as long as you can provide a JdbcTemplate with a java.sql.DataSource or a HibernateTemplate with a org.hibernate.SessionFactory, it’ll handle everything for you.

But what if you can’t use Spring, or it’s just overkill to use it? That’s fine, but it seems that people get confused about how to structure their code so that their ‘finally’ blocks work correctly under every circumstance. And this can result in unexpected behavior in your programs. Here’s one example that I see quite often:

Connection connection;

try {
connection = dataSource.getConnection();
// Do stuff with connection.
} finally {
connection.close();
}

So what’s wrong with this code? Well, if the call to dataSource.getConnection() fails, an exception will be thrown. The ‘finally’ block will still execute however, but the ‘connection’ object will be null. This will result in a NullPointerException being thrown instead of the original exception. So the original exception will be masked by the NullPointerException. ‘Who cares?’ you might say. Well, I care if I’m investigating a production problem at 3am and have just wasted five bleary-eyed minutes wondering why a NullPointerException occurred when the underlying cause was really a problem getting a database connection.

“Easy”, you say, “just do something like this:”

Connection connection;

try {
connection = dataSource.getConnection();

// Do stuff with connection.
} finally {
if (connection != null) connection.close();
}

That’ s great, but what if you’ve got a statement that you need to close too? “No worries”, you say, “the code needs to morph into something like this:”

Connection connection;
Statement statement;

try {
connection = dataSource.getConnection();
statement=connection.createStatement();

// Do stuff with statement.
} finally {
if (statement != null) statement.close();
if (connection != null) connection.close();
}

Well, what if the call to statement.close() fails? It’ll skip closing the connection. Whilst I admit that it’s unlikely that a call to statement.close() would fail, my point is that these are just a few of the wide number of possible combinations of things that can happen in your code. Wouldn’t it be easier if you didn’t have to worry about all these possibilities?

Well, fortunately, there’s a simple strategy that you can use to always make sure that these sorts of objects get closed down in an orderly, watertight fashion. It goes like this:

  1. Do not initialize the connection variable to null - always assign the real connection object to it immediately.
  2. On the very next line of code, start a try/finally block that will use that connection and then close it.
  3. When you get a statement from the connection, don’t use the same try/finally block to manage it. Instead, repeat steps 1 and 2, but this time apply them to the statement instead of the connection. In other words, initialize the statement immediately and start a new, nested try/finally block on the next line of code.

Here’s what the code looks like:

Connection connection = dataSource.getConnection();
try {
Statement statement = connection.createStatement();
try {
// Do stuff with the statement
} finally {
statement.close();
}
} finally {
connection.close();
}

Because variables are initialized immediately, there’s no danger of NullPointerExceptions. And because each object is managed with it’s own carefully nested try/finally block, there’s no danger of things not being closed if some failure occurs in a contained block.

This pattern can pretty much be applied recursively. For example, you would manage a nested result set in the same manner:

Connection connection = dataSource.getConnection();
try {
Statement statement = connection.createStatement();

try {
ResultSet resultSet = statement.executeQuery(”some query”);

try {
// Do stuff with the result set.
} finally {
resultSet.close();
}
} finally {
statement.close();
}
} finally {
connection.close();
}

So hopefully you’re seeing a bit of a pattern here. In fact, we can generalise it for any object that needs to be closed:

  1. Do not initialize the object variable to null - always assign the actual object to it immediately.
  2. On the very next line of code, start a new, nested try/finally block. All code that uses the object should be within the ‘try’ block. The code that closes the object should be in the ‘finally’ block.
  3. When you get a child object that also needs to be closed, go to step 1 and repeat.

It might look like overkill but in 10 years of coding Java I’ve found that this is the only way to really be sure that everything is going to be closed correctly. Every time I’ve tried to cut corners I’ve invariably introduced a defect. If you can see something wrong with it, or have got a better idea, I’d love to hear about it.

So as you’ve seen, doing this sort of thing properly requires a fair bit of code. And the more code we have, the more unit testing we have to do. That’s why it’s a good idea to use things like the Spring JdbcTemplate if you can - they’ve already done all of the work (and the testing) for you. What initially seems like a trivial piece of work is actually reasonably involved if you want to do it properly.

The same sort of pattern can be applied to files, or any other type of activity that requires resources to be closed.

Those who have seen my recent presentation on Test-Driven Development may be curious as to why all of my examples used services and DAOs that were defined directly as classes, instead of defining interfaces first and then having separate implementation classes.

In recent years I’ve shifted away from the use of Java interfaces when defining the interface into a service or DAO. Instead, I often just make it that the actual implementation is the base class, and that if anybody wants to stub it up they just subclass it. It’s important to note that I still think carefully about what the ‘interface’ to the base class is. In fact, I always start by just writing method stubs that throw an UnsupportedOperationException - something that you’ll see in the presentation. I then start writing tests against the class, fleshing it out from there.

The prime benefit of this approach is that the code is easier to navigate. If you navigate to a class or method in Eclipse, it’ll go straight to the implementation. Having spent years maintaining large codebases with a zillion interfaces I have found this to be very useful. You no longer hit a dead-end when you navigate into an interface and have to look up the implementers yourself. There’s also the benefit that instead of every service or DAO having at least two classes – an interface and an implementation – you have one class. The codebase becomes less bloated.

Dependency injection is still possible. Furthermore, if I want to mock the class using a mocking framework, frameworks like jMock and EasyMock can also dynamically generate mock subclasses using CGLIB. I’ve even found that Spring is able to use CGLIB to generate transaction or security proxies for these classes. The only stipulation is that each of your classes must have a default constructor, which beats the heck out of having to have two classes.

However, there are a couple of limitations that I have experienced or could imagine might be a problem:

  • If you alter a method that constitutes the ‘interface’ to a base class, any stub subclasses that over-ride the original version of the method (for example, manually coded stubs) won’t automatically break. You need to make sure that you adjust them, or they’ll just be treated as an additional method and not an override. I encountered this on a recent project where we had a couple of developers who were new to stubs and mocks working on an evolving service layer. Somebody would change a method signature on the service base class, not realizing that somebody else had overridden the original method definition in a subclass that was a stub. Tests would start failing and it would take a while to figure out what was going on. To be perfectly honest, in that instance we shifted back to using separate interfaces to avoid the confusion.
  • It’s potentially open to abuse, with people just diving into implementation without thinking clearly about their interfaces. I haven’t seen this in practice though, especially if you adopt a TDD approach.
  • Invocation on mocks and proxies may be fractionally slower. However, before you get too excited about this I want to emphasise that we’re probably talking microseconds here, which would only be noticable for your tests if they were calling DAOs and services thousands of times…which they’re probably not going to do.

If you’re new to mocking frameworks, dependency injection or Spring, I probably wouldn’t adopt this approach in the first instance - you’ll already have enough to get your head around. However, if you’re more experienced, it may be worth a look. And even if you don’t start using this technique straight away, it’s worth knowing that you can do it, rather than just blindly creating interfaces and implementations for every service and DAO that you ever write. Think of it as another tool in your toolbox of techniques for creating more concise, easy-to-follow code.

Well, this week I’ve been able to introduce another developer to the Eclipse Web Tools Platform project and it’s been satisfying to see the look of joy on his face as he discover its hidden gems. As well as the standard stuff like HTML syntax highlighting, error highlighting and formatting, there’s also the more powerful stuff like completion on any tag library you want. Sure you can get this sort of thing with MyEclipse, but the WTP is free.

The only catch with this project is that it’s a big one with a couple of dependencies - which makes it much, much easier to install if you just use the Eclipse Update Manager and get it to automatically load dependent frameworks. I’m surprised at the number of developers who still install Eclipse plugins and features using the old-school technique of downloading a zip file and unpacking it into their plugins folder. You can often even upgrade all of Eclipse using the Update Manager!

However, we haven’t been able to use the Update Manager this week as we’ve been working behind a corporate firewall that blocks it for some reason - even after we configure the HTTP proxy access. Initially we resorted to the old-school approach (with all of its consequent difficulties) but then remembered that you can get distributions of Eclipse that are prepackaged with WTP. After that there was no looking back.

I saw the post on theserverside.com that had gone official 1.0 release. With much anticipation I jumped over to www.jruby.org only to find the news about the RC3 release.

Never fear, jump to the Downloads page and you will see the 1.0 downloads sitting meekly by the RC3 versions.

JRuby 1.0

Very low key for a fairly big milestone. But go read the blog entry by Charles Nutter to find out more what the release means and the upcoming work.

JRuby is a key technology that might allow Ruby on Rails applications to make a much more rapid entry into the Enterprise development arena than otherwise would have been the case. At the point where you can deploy a Rails application alongside other Java Enterprise applications inside a container many of the barriers that Rails faced start to disappear.

And before you start talking about Rails being slow, check out the blog entry by Julian Doherty and the response he got from Charles Nutter that highlights how Ruby under JRuby is already equivalent in speed to native Ruby and likely to get even faster in the future.

All we need now is for some of the cool plug-ins that rely on native code to be re-written in pure Ruby, or to have Java equivalents written (I’m looking at you, Ferret).