Thursday, 29 December 2011

Technology Related Classic Mistakes

In my last blog I looked a Product Related Classic Mistakes from Rapid Development: Taming Wild Software Schedules by Steve McConnell, which although it’s now been around for at least 10 years, and times have changed, is still as relevant today as when it was written.

Tuesday, 27 December 2011

Product Related Classic Mistakes

In my last blog I looked a Process Related Classic Mistakes from Rapid Development: Taming Wild Software Schedules by Steve McConnell, which although it’s now been around for at least 10 years, and times have changed, is still as relevant today as when it was written.

As Steve’s book states, classic mistakes are classic mistakes because they’re mistakes that are made so often and by so many people. They have predictably bad results and, when you know them, they stick out like a sore thumb and the idea behind listing them here is that, once you know them, you can spot them and hopefully do something to remedy their effect.

Thursday, 22 December 2011

Process Related Classic Mistakes

In my last blog I looked a People Related Classic Mistakes from Rapid Development: Taming Wild Software Schedules by Steve McConnell, which although it’s now been around for at least 10 years, and times have changed, is still as relevant today as when it was written.

Monday, 19 December 2011

People Related Classic Mistakes

In my last blog I mentioned Rapid Development: Taming Wild Software Schedules by Steve McConnell, which although has now been around for at least 10 years is still as relevant today as when it was written. One of my favourite parts of the book was his treatment of Classic Mistakes

Friday, 16 December 2011

Stuck with the The Inner Platform Anti-pattern?

Just recently our team has received some innocuous requests from the customers: “please can we have a configurable menu here?” or “...this would save us a lot of time”. These, on the face of it, should have been extremely easy to code, but have turned out to be a real nightmare. At first, I put this down to the massive technical debt1 of the legacy code we’ve inherited, but more recently, after a comment from a colleague, I’ve come to realise that it’s more than that.

Wednesday, 14 December 2011

Summary of Testing Techniques Blogs

As I’ve just about come to the end of my series of blogs on testing techniques, today’s blog lists for review purposes my nine blogs on this subject so far - there may be more...

Monday, 12 December 2011

Oracle Weblogic Server 11gR1 P2: Administration Essentials

I was recently asked to review Oracle Weblogic Server 11gR1 P2: Administration Essentials by Michel Schildmeijer and I was some what apprehensive at first. After all, my blog is about Java development; a personal notebook detailing stuff I need to know, plus... this was a book on Weblogic Server administration.

Then it struck me that, as a developer, how many times I’ve had to configure a server of some kind, be it Weblogic, Tomcat, JBoss or Glassfish. And, every time I do configure a server, I’ve often thought how great it would be to have a handy, succinct, easy to read guide available to ensure that I’m doing it right and I now think I have my book for configuring Weblogic.

Thursday, 8 December 2011

Some Definitions - Testing Techniques 9

I think that I’m coming to the end of my series of blogs on testing techniques, and it feels like it’s been along haul. One of the things that has become clearer to me is that approaches to testing are still in their infancy and as such are a definite source of contention or discussion amongst developers - and that’s a good thing. I suspect that we are at a point in the history of our profession where the discipline of writing tests is only just gaining ground and will one day be common place and taught as part of elementary programming classes1. Today’s blog provides a summary of the of the terms used in my previous blogs in this series.

Tuesday, 6 December 2011

Why You Should Write Unit Tests - Testing Techniques 8

I’ve had lots of reaction to my recent blog on ‘What you Should Test’, some agreeing with me for varying reasons and others thinking that I’m totally dangerous for suggesting that certain classes may not need unit tests. Having dealt with What to test, today’s blog deals with Why you should write unit tests, and today’s example code is based upon a true story: only names, dates and facts have been changed.

Thursday, 1 December 2011

More on Creating Stubs for Legacy Code - Testing Techniques 7

In my last blog, I talked about dealing with the badly behaved untestable1 SitePropertiesManager class and how to create stubs by extracting an interface. But what happens when you don’t have access to the source code of the legacy class because it’s locked away inside a third party JAR file?

Tuesday, 29 November 2011

Creating Stubs for Legacy Code - Testing Techniques 6

Any one who reads this blog will probably have realised that at present I’m working on a project that contains a whole bunch of legacy code that’s large, expansive, and written without any tests what so ever. In working with this legacy code, there’s been one very badly behaved class that’s all pervasive, which the whole team have tripped over time and time again. In order to protect the guilty, I’ll call it Mr. X although its real name is SitePropertiesManager as it manages the web site’s properties.

Thursday, 24 November 2011

Unit Testing Using Mocks - Testing Techniques 5

My last blog was the fourth in a series of blogs on approaches to testing code, demonstrating how to create a unit test that isolates the object under test using a stub object. Today’s blog looks at what is sometimes regarded as an opposing technique: unit testing with mock objects. Again, I’m using my simple scenario of retrieving an address from a database:

… and testing the AddressService1 class:

Tuesday, 22 November 2011

Regular Unit Tests and Stubs - Testing Techniques 4

My last blog was the third in a series of blogs on approaches to testing code and discussing what you do and don’t have to test. It’s based around my simple scenario of retrieving an address from a database using a very common pattern:

...and I proffered the idea that any class that doesn’t contain any logic doesn’t really need unit testing. In this I included my data access object, DAO, preferring instead to integration test this class to ensure it worked in collaboration with the database.

Friday, 18 November 2011

What Should you Unit Test? - Testing Techniques 3

I was in the office yesterday, talking about testing to one of my colleagues who was a little unconvinced by writing unit tests. One of the reasons that he was using was that some tests seem meaningless, which brings me on the the subject of what exactly you unit test, and what you don’t need to bother with.

Consider a simple immutable Name bean below with a constructor and a bunch of getters. In this example I’m going to let the code speak for itself as I hope that it’s obvious that any testing would be pointless.

Wednesday, 16 November 2011

The Misuse of End To End Tests - Testing Techniques 2

My last blog was the first in a series of blogs on approaches to testing code, outlining a simple scenario of retrieving an address from a database using a very common pattern:

Monday, 14 November 2011

Testing Techniques - Part 1 - Not Writing Tests

There’s not much doubt about it, the way you test your code is a contentious issue. Different test techniques find favour with different developers for varying reasons including corporate culture, experience and general psychological outlook. For example, you may prefer writing classic unit tests that test an object’s behaviour in isolation by examining return values; you may favour classic stubs, or fake objects; or you may like using mock objects to mock roles, or even using mock objects as stubs. This and my next few blogs takes part of a very, very common design pattern and examines different approaches you could take in testing it.

Friday, 11 November 2011

Software is Art

I perhaps shouldn’t mention this, but one of my colleagues sent around an email pointing to a very cool video made, I suspect, by a competitor, and saying how good it was. At about a minute or two in, they showed some code and bragged at about their digital services. So, as a diverting interlude, I did a tongue-in-cheek critic of the code in a screen shot....

Wednesday, 9 November 2011

Reviewing PowerMock's Features

When you write a blog, you get a feel for those subjects that are contentious and those that aren’t and one of the most contentious subjects seems to be the area of unit test techniques: are you a mockist or a classist? Can you test internal state or private methods? Should you just test behaviour? Just out of curiosity, I recently took a look at Powermock, software with which I have no relationship, and I wrote four simple ‘how to’ blogs on some of its features. The blogs were:
  1. Using PowerMock to Mock Static Methods
  2. Using PowerMock to Mock Constructors
  3. Why Use PowerMock to Mock Private Methods?
  4. Testing an Object's Internal State with PowerMock

One of the things I didn’t do was to sum up how useful I thought each of the features were, which led to some constructive criticism, which I broadly agreed with before the authors made their first keystrokes.

Monday, 7 November 2011

Adding a Site to your Maven Project

Once you’ve got your Maven project built and sorted, one of the neat tricks you can do to make it look even more professional is to add a Maven Site. Maven gives you the ability to add a whole site structure with one simple command.

mvn archetype:generate -DarchetypeGroupId=org.apache.maven.archetypes

Friday, 4 November 2011

Using JSR-250’s @PostConstruct Annotation to Replace Spring's InitializingBean

JSR-250 aka Common Annotations for the Java Platform was introduced as part of Java EE 5 an is usually used to annotated EJB3s. What’s not so well known is that Spring has supported three of the annotations since version 2.5. The annotations supported are:
  • @PostContruct - This annotation is applied to a method to indicate that it should be invoked after all dependency injection is complete.
  • @PreDestroy - This is applied to a method to indicate that it should be invoked before the bean is removed from the Spring context, i.e. just before it’s destroyed.
  • @Resource - This duplicates the functionality of @Autowired combined with @Qualifier as you get the additional benefit of being able to name which bean you’re injecting, without the need for two annotations.

Wednesday, 2 November 2011

Using Spring MVC’s @ModelAttribute Annotation

The @ModelAttribute annotation is used as part of a Spring MVC web app and can be used in two scenarios.
  • Firstly, it can be used to inject data objects the model before a JSP loads. This makes it particularly useful in ensuring that a JSP has all the data is needs to display itself. The injection is achieved by binding a method return value to the model.
  • Secondly, it can be used to read data from an existing model assigning it to handler method parameters.

Monday, 31 October 2011

Maintaining Separation of Concerns when using a JSP Front Strategy MVC Pattern.

My last MVC blog tried to add a little depth into exactly what the MVC pattern is in relation to web-applications, and in writing it I highlighted the problems and pitfalls of using a JSP Front Strategy as an MVC front controller pattern. To sum this up, although favoured by some organisations, it seems to me that using JSP Front Strategy makes it all too easy to mix the controller logic, view information together with the model in the wrong place, which results in nothing more than a plate of indecipherable spaghetti code.

So, I thought that I’d investigate a technique for implementing the JSP front strategy without creating a dog’s dinner and try to sort out a few rules that can be applied if you ever find yourself working on, what is after all, obsolete technology.

Friday, 28 October 2011

Autowiring Property Values into Spring Beans

Most people know that you can use @Autowired to tell Spring to inject one object into another when it loads your application context. A lesser known nugget of information is that you can also use the @Value annotation to inject values from a property file into a bean’s attributes.

Wednesday, 26 October 2011

Everybody Knows About MVC...

From a recent blog, you may have gathered that I’ve recently been conducting some interviews and as they were for web application developers a question I asked was “can you explain what the MVC pattern is?”, and to their credit, every candidate knew the answer.

Monday, 24 October 2011

Testing an Object's Internal State with PowerMock

Most unit testing focuses on testing an object’s behaviour in order to prove that it works. This is achieved by writing a JUnit test that calls an object’s public methods and then testing that the return values from these calls match some previously defined set of expected values. This is a very common and successful technique; however, it shouldn't be forgotten that objects also exhibit state; something that is, by virtue of the fact that it’s hidden, often overlooked.

Friday, 21 October 2011

Intermittent ORA-12519 error on 10g XE

There’s an Oracle error that seems to raise its ugly head every now and again and it occurs on Oracle 10g Express Edition running under 32 bit Windows (which in my case was XP). It happened to me after transferring my test Oracle database from a real to a virtual copy of Windows XP, and when running a series of unit tests on a database module.

The error manifests itself as an ORA-12519 connection refusal error as highlighted by the following partial stack trace:

java.sql.SQLException: Listener refused the connection with the following error:
ORA-12519, TNS:no appropriate service handler found
The Connection descriptor used by the client was:
at oracle.jdbc.driver.DatabaseError.throwSqlException(
at oracle.jdbc.driver.DatabaseError.throwSqlException(
at oracle.jdbc.driver.T4CConnection.logon(
at oracle.jdbc.driver.PhysicalConnection.(

The suggested fix, and this was written two years ago, is to increase the number of available processes by logging on as SYS and issuing the following command:


…which doesn’t seem like a real fix to me as it just pushes the problem further away.

Yes, I know that Oracle 10g is obsolete and the 11g Express Edition is freely available, but 11g adds yet another layer of unwanted complexity to my requirement for a simple Oracle database.

Wednesday, 19 October 2011

Why Use PowerMock to Mock Private Methods?

So far I’ve written a couple of blogs on PowerMock covering some of what I think are its most useful features. Today’s blog takes a look at PowerMock’s ability to mock private methods. At first this struck me as a pretty useless idea. The PowerMock documentation says that you can use it to mock private methods that are called many times during your build process so that you only test them once. My first reaction was does it matter whether or not you execute a piece of code once or a thousand times during a set of unit tests? Usually the answer will be ‘no’ and this feature will be pretty superfluous. However, there is a scenario where is come come in very handy...

Monday, 17 October 2011

Using PowerMock to Mock Constructors

In my opinion, one of the main benefits of dependency injection is that you can inject mock and/or stub objects into your code in order to improve testability, increase test coverage and write better and more meaningful tests. There are those times, however, when you come across some legacy code that doesn’t use dependency injection and held together by composition rather than aggregation.

Friday, 14 October 2011

Top Trumps in God Objects

If we were playing the children’s game Top Trumps with Java interface definitions I think that I’d win every time. That’s because I’ve just found an interface, which is part of a prestigious company’s public API with with 167 methods. Trump that! Imagine, if the interface definition contains 167 methods, how big is the implementation class? In the words of a texting teenager “OMG”.

You’ll probably know that objects that are as out of control as this are usually called God Objects or Monster Objects and there’s an anti-pattern of the same name which explains it all. If you look on at various definitions of the God Object Anti-Pattern, they usually say a god object is an object that “knows too much or does too much”1, words which seem to crop up all too often if you dig around the internet. In modern programming speak this generally means that a god object:

Wednesday, 12 October 2011

Using PowerMock to Mock Static Methods

In a recent blog, I tried to highlight the benefits of using dependency injection and expressing the idea that one of the main benefits of this technique is that it allows you to test your code more easily by providing a high degree of isolation between classes, and coming to the conclusion that lots of good tests equals good code. But, what happens when you don’t have dependency injection and you’re using a third party library that contains classes of a certain vintage that contains static methods?

Monday, 10 October 2011

The Benefits Of Dependency Injection

Dependency Injection is the way to go, so say the Guys at Spring, and who am I to argue with them, after all it sounds like a sensible idea. But, how many developers have ever stopped to figure out why?

Friday, 7 October 2011

Installing the EGit component in Eclipse

The ever increasing popularity of Git seems to know no bounds, which is not bad for something that’s named after a British English insult that’s only slightly more venomous than “idiot”1. Being popular, there is an eclipse plug in available and this short blog covers how to install it.

Thursday, 6 October 2011

Looking into the Magic of Dependency Injection Using Annotations - Part 4

This is the fourth and last in a short series of blogs that looks into implementing dependency injection using annotations. The previous three blogs on this subject have covered:
Today’s blog ties up all the loose ends and does produce a limited, but fully functional, dependency injection factory class based upon annotations.

Wednesday, 5 October 2011

Flash, flowplayer and nyroModal Overlays

It doesn’t take me to tell you that in today’s world Flash is a very popular way of presenting video content to your users, and almost as common is the use of overlays to present your users with alternative content or messages. This is usually supported by some javascript library such as the nyroModal JQuery plugin.

Unfortunately, sometimes the two don’t mix with the flash video appearing to “show through” the overlay, but is this really the case. The blog examines what’s really happening.

Tuesday, 4 October 2011

Looking into the Magic of Dependency Injection Using Annotations - Part 3

This is the third in a short series of blogs that looks into implementing dependency injection using annotations.If you’re familiar with Spring or EJB3, you’ll know the sort of thing I’m talking about: you write you class; add a few annotations, for example @Autowired or @Ejb; deploy it to your web-server and then et volia it’s all glued together and works, as if by magic...

Friday, 30 September 2011

Looking into the Magic of Dependency Injection Using Annotations - Part 2

This is the second in a short series of blogs I’m presenting that looks into implementing dependency injection using annotations. If you’re familiar with Spring or EJB3, you’ll know the sort of thing I’m talking about: you write you class; add a few annotations, for example @Autowired or @Ejb; deploy it to your web-server and then et volia it’s all glued together and works, as if by magic...

This blog isn’t going to write a fully formed DI factory using annotations, but it will give you a few hints in to the kinds of techniques used by the Guys at Spring and the EJB3 Team.

Thursday, 29 September 2011

Looking into the Magic of Dependency Injection Using Annotations - Part 1

One of the things that every Spring and EJB3 developer does on a daily basis is to use annotations to inject instance variables into your objects, which, it seems, has become something we do without thinking about.

You know the type of thing I’m talking about: you write a couple of classes annotating one with @Component and the other with @Autowired and when you run your killer app hey presto everything’s happily glued together.

Wednesday, 28 September 2011

Searching Maven Central

It seems that no matter how much you read about software and how much you try and learn, you always seem to miss something pretty useful. I’ve been using Maven for at least three years and only found out a few weeks ago that you can search the Maven repository for artifacts... Duh! It seems the obvious thing to do, but if you’ve never seen something...

Tuesday, 27 September 2011

Using Spring Interceptors in your MVC Webapp

I thought that it was time to take a look at Spring’s MVC interceptor mechanism, which has been around for a good number of years and is a really useful tool.

A Spring Interceptor does what it says on the tin: intercepts an incoming HTTP request before it reaches your Spring MVC controller class, or conversely, intercepts the outgoing HTTP response after it leaves your controller, but before it’s fed back to the browser.

Friday, 23 September 2011

The Benefits and Dangers of using Opensource Java Libraries and Frameworks

Everyone in the Java world seems to use various opensource libraries and frameworks... and why not, there are hundreds available covering virtually every type of programming problem you’re likely to come across in today’s programming landscape. This blog takes a quick look at the reasons for using opensource artifacts and examines what could go wrong...

Thursday, 22 September 2011

Adding SLF4J to your Maven Project

In yesterday’s blog, I documented the various bits of the Maven POM file created for a ‘Spring MVC Project’ using one of Spring’s project templates. In that POM file you may have noticed a reference to an slf4j-api artefact and comment to the effect that the Guy’s at Spring were excluding “Commons Logging in favor of SLF4j”. This blog takes a look at SLF4j, or to give it its full title: “Simple Logging Facade for Java” and demonstrates how to add it to a project.

Wednesday, 21 September 2011

Dissecting Spring's MVC Project POM

One of the good things about Spring’s STS is that is provides a whole bunch of useful Spring project templates that you can use to generate empty or stub projects from which to start writing some code. The list of projects includes a ‘Simple Spring Utility Project’ and a ‘Spring Batch Admin WebApp’.

Tuesday, 20 September 2011

When Inheriting a Codebase, there are more questions than answers...

There will be that time in your life when you inherit someone else's source tree or codebase and you’ll need to think of a plan to deal with this situation. Now, there are codebases and there are codebases, none are ever perfect, but some are just unbelievable...

The idea of this blog is to go through some of the question’s you’ll need to ask in order to figure out what you can do and whether or not you’ll be able to make a difference or just end up picking away at the edges going nowhere.

Monday, 19 September 2011

Deploying Applications to Weblogic Using Maven

When developing JEE applications as part of the development cycle, it’s important to deploy to a development server before running end to end or integration tests. This blog demonstrates how to deploy your applications to your Weblogic server using Maven and, it transpires that there are at least two ways of doing this.

Friday, 16 September 2011

Using AspectJ’s @After Advice in your Spring App

Today’s blog demonstrates how to implement a simple after advice in your Spring application using the @After annotation. An after advice is where your advice code gets called after the join point in your point cut. I’ve previously blogged on the definitions AOP/AspectJ’s cryptic terms, but putting it simply, your advice code gets to run when a method whose signature meets some pre-defined pattern has finished running. Sets of methods whose signatures meet some pre-defined patterns are the point cuts.

Thursday, 15 September 2011

Defining Spring's AspectJ Advice Types

My blog from a couple of days ago defined the AspectJ, AOP’s term ‘advice’ as the code that runs when your application execution reaches a join point in a point cut. What I neglected to mention is that there are several different types of advice all applied to method executions and these are summarized in the table below:

@BeforeThe advice method gets called before the method defined in your point cut.
@AfterThe advice code gets called after the method defined by your point cut has finished executing.
@AroundAn advice that combines the @Before and @After, executing some code before the method in the point cut and some after.
@AfterThrowingAn advice that executes after an exception have been thrown, and before it’s caught.

The Guy’s at Spring have documented how to use these annotations in this document.

Wednesday, 14 September 2011

Using RESTful URLs on your Spring 3 MVC Webapp

This blog comes as an answer to a question from a reader. Now, as a rule, I don’t do request blogs, but I thought that this sounded like an interesting topic. The question refers to my blog from July 11 on accessing request parameters using Spring 3 MVC and was “Do you know how to encode the uuid so it is not visible to the user for security concerns?”. The answer is “Yes”, but that would make for a very short blog.

Tuesday, 13 September 2011

AOP and AspectJ Terminology

In my recent blog on 10 minute concepts, I mentioned some of the terms relating to AspectJ and AOP, which I never defined. This blog puts that right and explains some of these terms below...

AspectJ TermDescription
AspectA feature of a program that is separate from, and not related to any specific part of a program, but is woven throughout the fabric of the program so as to be used by all or many parts of the program.... and this sounds really vague. You can think of a program as a bunch of events, for example: methods being called, objects being constructed etc. An aspect oriented approach to programming, such as ApsectJ, really means creating some mechanism where by you can call your method before, after or around some other event, so as run some of your code, without the need to reference this code from the event.
Join PointA join point is the name given to one of the programmatic events as described above, eg calling a method or creating an object. In AspectJ, a joint point is really the specification of where/when in your program, your aspect code is running. For example, if your aspect code runs before a given method call, then the join point describes the signature and arguments of that method.
PointcutA set of related joint points. When program execution reaches one of the join points in the pointcut, then your aspect code will run.
AdviceThis is the code that runs when program execution reaches a joint point in your pointcut.

Monday, 12 September 2011

Weasel Words

The other day I had to look into a project’s source code and shocked by the state it was in. I can, hand on heart, say I haven’t seen code like it for 10 years... which made it interesting.

Friday, 9 September 2011

Using Spring's AspectJ Support and the @Before Annotation

You may have wondered how the Guys at Spring do all that jiggery-pokery with the annotations that you add to your Spring beans. I’m not an expert here, but I suspect that somewhere along the way, they do a little Aspect Oriented Programming using AspectJ - after all, they do have comprehensive support for it. This of course is total supposition - I’ve not been trawling through their source code. This blog demonstrates how you can use AspectJ to intercept your class's annotated methods and to do that,I’m going to demonstrate the @Before annotation by writing a Before Advice class that takes a peak at the attributes of a method’s annotations. This blogs builds on my previous AspectJ blog that demonstrates how to write an After Throwing advice.

Thursday, 8 September 2011

The Ten Minute Concept Rule

This is something really simple that occurred to me the other day. If you’ve read any of my blog content over the past few months, you’ll realise that I’ve covered a lot of ground, talking about Java, Spring, Weblogic, EJB3 and other topics, and in talking about these APIs it struck me that the most popular ones have one thing in common: their basic concepts can be easily understood within a few minutes of reading about them.

Take for example Spring and dependency injection. Spring is BIG, there’s a lot to it, but the concept is simple: use a factory of some sort to build your application by injecting all its dependencies and do it in the simplest way possible.

Wednesday, 7 September 2011

Using AspectJ’s @AfterThrowing Advice in your Spring App

This may not be strictly true, but it seems to me that the Guy’s at Spring are always banging on about AspectJ and Aspect Oriented Programming (AOP), to the point where I suspect that it’s used widely under the hood and is an integral part of Spring and I say “widely used under the hood”, because I haven’t come across too many projects that do use AspectJ or AOP in general.

I suspect that part of the reason for this is possibly down to the fact that AOP different is a concept to Object Oriented Programming (OOP). AOP, they say, is all to do with an application’s cross-cutting concerns, which translates to mean stuff that’s common to all classes within your application. The usual example given here is logging and example code usually demonstrates logging all method entry and exit details, which is something that I’ve never found that useful. The other reason that I’ve not seen it used is that the AspectJ documentation is a bit ropey.

Tuesday, 6 September 2011

Using Spring’s @Required Annotation

When your application needs a bean class, it’s not unusual for certain attributes to be mandatory, which if missed from your Spring config file will cause you problems at some undetermined future time. The Guys at Spring thought of this and came up with the @Required annotation that you can apply to your bean’s setter method:

  // Snippet from a plain old bean...
private int id;
private String street1;

public void setId(int id) { = id;

public void setStreet1(String street1) {
this.street1 = street1;

Monday, 5 September 2011

Integrating SureAssert with Existing Projects

I recently blogged about SureAssert’s ability to do automatic, continuous, declaration driven testing using annotations, which could make JUnit test classes obsolete. When picking up any new and useful development tool, the first question asked is usually “how can it help my existing project?” The answer here is that SureAssert integrates with existing JUnit test code, which gives you the benefit of having your existing JUnit tests continuously monitored and executed.

Friday, 2 September 2011

Adding Sitemesh to your Spring webapp

The other day I came across a company that was recommending the use of Sitemesh as a way of creating re-useable JSP templates and this worried me slightly. There’s nothing particularly wrong with Sitemesh, it’s a tool for segmenting JSP pages in a similar way to Struts Tiles and it’s rather neat. The downside of using it is that it was written by the now defunct OpenSymphony, which means that no one’s supporting it and bugs, if there still are any, won’t get fixed. Furthermore, is the source code still available so that you can build it yourself? I also, wondered whether this company’s very prestigious clients know that this firm was using unsupported, vintage software and would they care?

Thursday, 1 September 2011

A Mention On SpringSource

I normally reserve my blog for demonstrating various Java bits and pieces that I’m personally interested in, whether it’s something that I need to know that’s related to work or something I’m just curious about.

Today’s blog is an exception, as it’s a thank you to the Guys at Spring - Josh Long - for the mention in This week in Spring, and Guys, I currently have 53 Spring related blogs including another half dozen yet to be published.

Wednesday, 31 August 2011

Installing Weblogic Server on Your Mac

Installing Weblogic Server on an Apple Mac doesn’t come naturally. The usual technique is to download and, with a bit of fiddling about, install the generic package installer aimed at Solaris.

Oracle seemed to have improved things, however, by bringing out a Weblogic Zip distribution for development purposes that can be easily installed on Windows, Linux and Mac. You can download this from the following link: ...assuming that you already have a developer account.

Tuesday, 30 August 2011

Enabling the root Account on Your Mac

There are several ways to enable the root account on your handy-dandy Apple Mac. The simplest one I can think of is to open a terminal window and type the following:

%   sudo passwd root
Enter Password: {type your current password here}
 Changing password for root
New password:  {type your new root password here}
Verify password: {re-type your new root password here}

Monday, 29 August 2011

Developing Enthusiasm and Excitement

I went on a course a few weeks ago for the first time in about 12 years. I was learning about a well known content management system. The course was split into two parts: firstly, the principles and use of a content management system (CMS) and secondly, developing a presentation layer using their web application framework. I have to say that I was really impressed by the ideas on CMS, especially the idea that you can have large numbers of people that, given the right tools, can contribute to a web site with only a bit of common sense and without any real technical knowledge. An example would be a whole load of reporters constantly updating a news website. Brilliant.

Friday, 26 August 2011

Subversion: Attempted to lock an already-locked dir

Earlier today I was committing some changes to a local Subversion repository running on a PC when Windows decided it was too busy to co-operate and told me that it was “Not Responding” (which is not unusual). Spring's STS program (aka eclipse painted green) running on my handy-dandy Mac hung and then crashed (v. unusual) leaving the commit half complete.

On restarting STS, I again attempted to commit my work and got this error:

Thursday, 25 August 2011

The Ten Minute Build

Given a development environment any developer should be able to get hold of the source code, click a button or type a simple command and run a build. The build should compile and perform its unit tests within about ten minutes. This is the Ten Minute Build rule in James Shore’s and Shane Warden’s book The Art of Agile Development and it’s easy to see why this is a good idea because builds that don’t run easily are both frustrating, which lowers moral, and burn project time shovelling your company’s money into some metaphorical furnace.

Wednesday, 24 August 2011

Declarative Unit Testing: Is JUnit Obsolete?

One of the pains in the bum with Test Driven Development is that if (or when) you change a class, you often spend a good deal of time patching up all your unit tests and if you’re a Mockist then it becomes even harder as you have to mess around re-jigging a lot of mock code. So, the other day I was surprised when I came across a new free product that turns the current ideas of unit testing on their head. The surprise came in the form of SureAssert, which as the website says is “an integrated Java unit testing solution for Eclipse”.

Tuesday, 23 August 2011

RC4 Encryption

Bazinga! I hope that everyone who read yesterday’s ROT13 blog spotted the Sheldon Cooper-esque 'clever prank' for the more secure double ROT13 aka ROT26 algorithm. Today’s blog takes encryption one step further and covers the hugely popular RC4 encryption algorithm developed by Ron Rivest, indeed the RC stands for Ron’s Code. Although now broken, the RC4 algorithm is still widely used in protocols such as SSL and WEP.

Monday, 22 August 2011

ROT13 Encryption

I thought that today I’d tackle the thorny issue of encryption starting with one of the most simple and weakest algorithms available: ROT13. ROT13 is a simple character shift or Caesar (or Caesar’s) cipher. In ROT13 each plain text character is replaced with one that’s 13 characters further along the alphabet. For example: ABC becomes NOP, whilst the plain text characters after M loop around back to the start of the alphabet; hence: MNO becomes ZAB whilst XYZ becomes KLM. Note that only upper and lower case letters in the English alphabet are encoded.

Friday, 19 August 2011

Code Formatting in Agile Teams

Whether you work in an Agile team or not, one of the crucial aspects of team work is agreeing your team's code formatting rules. You may wonder why I’m using the word crucial when introducing this topic and the answer lies in the consequences of not using a common style.

Thursday, 18 August 2011

Adding the Blueprint Toolkit to your Spring Webapp

If you’ve ever taken a look at the Spring MVC sample code, you’ll notice that the screens have a certain style and digging deeper into the JSPs you’ll find that the apps use a number of CSS classes with their <div>s tag such as container and span-12.

Wednesday, 17 August 2011

Tuning your Server's free pool

When writing an EJB for the Weblogic Server, there is a really useful vendor specific deployment descriptor called weblogic-ejb-jar.xml. This file contains many different properties that can be used to tune your application and today’s blog examines two of these: initial-beans-in-free-pool and max-beans-in-free-pool, which apply to stateless EJBs and MDBs.

Tuesday, 16 August 2011

How Big Should a Function Be?

The other day I was talking to a colleague; we were comparing horror stories about the largest functions that we’d ever seen and I quoted a 14,500 line absolute monster that I’d seem a long time ago that was part of a stock settlement system written in C++ and, oh how we laughed. This got me thinking that you never really see many opinions, recommendations or rules of thumb for the optimum length of a function, so when it comes down to it I like to quote Bob Martin’s two rules covering the length of a function from his book ‘Clean Code - A Handbook of Agile Software Craftsmanship’: "The first rule is that they should be small. The second rule is that they should be smaller still".

Monday, 15 August 2011

More on String and the StringBuilder Performance

In February, I demonstrated the most efficient way I could think of for conditionally building a string. This compared the use of StringBuilder and the ‘+=’ operator whilst checking for null values. The results showed that StringBuilder.append(..) was much faster than using ‘+=’.

Today’s blog covers the much simpler scenario: trying to decide which is the quickest way of of creating a simple string. In order to test this out, I modified the code I’d used last time adding a couple of new methods:

Friday, 12 August 2011

Wrapping Java API Classes

The benefits of using TDD to write your code are well known; the idea that you can write simple, independent, repeatable tests that will challenge your class is a lynch pin of today’s software industry. There are those classes, however, in the Java API, usually the ones that have been around for a long time, that are written in such a way as to make testing difficult and the reason this happens is because they don’t implement an interface or communicate with some external resource.

Thursday, 11 August 2011

Is ‘Convention Over Configuration’ Going Too Far?

I’m all for convention over configuration, especially in frameworks such as Spring and I really like the idea that the Spring XML configuration file can boil down to one line:

<mvc:annotation-driven />

...and there’s even argument for suggestion that if the XML config file is missing from your project then Spring should assume that your application is annotation driven and attempt running - though I’m not too naive to assume that more thought would be needed here as this may have other ramifications.

Wednesday, 10 August 2011

@DateTimeFormat Depends on Joda Time

Yesterday’s blog explained the use of the @DateTimeFormat and whilst writing it, I purposely chose to use java.util.Calendar for simplicity as I didn’t want to add an unnecessary dependency into my classpath... and that’s where I came unstuck. I turns out that if you don’t have the following dependency in your POM:

Tuesday, 9 August 2011

Using the Spring 3 @DateTimeFormat Annotation

@DateTimeFormat is the complimentary annotation to yesterday’s @NumberFormat and like @NumberFormat it does what it says on the tin and allows you to format dates and times. The Spring javadoc states that it can be applied to java.util.Date, java.util.Calendar, java.long.Long, or Joda Time classes and works on dates sent to the presentation layer from the controller and visa-versa.

Monday, 8 August 2011

Using Spring 3 @NumberFormat Annotation

The Guys as Spring have provided a very useful annotation called @NumberFormat that allows you to, well... format numbers. It works on numbers sent to the presentation layer from the controller and visa-versa and can be applied to any class derived from java.lang.Number. It will format numbers into three styles as defined by the NumberFormat.Style enum: CURRENCY, PERCENT and NUMBER.

Friday, 5 August 2011

The Spring MVC-Ajax Sample and its JSON Library

The Spring-MVC sample code is available from the Spring subversion repository at The idea of this sample is to demonstrate a simple Ajax application that updates an account screen both checking that a user name is available and adding a new account to the application.

Thursday, 4 August 2011

Adding JQuery to your Page

JQuery is probably the most popular Javascript library available today and given its flexibility, and the enormous number of plugins it’s not difficult to see why. There are two versions of JQuery available, a production version and developer or debug version, and at least two ways of including it in your page.

Wednesday, 3 August 2011

The JSR 303 javax.validation.Payload Class - WTF???

During the course of my last few blogs I’ve covered quite a few features of the JSR 303 Valdator and there is one feature that I’ve avoided looking into until now and that's the payload attribute of the constraint annotation interface.

There’s not much on this Hibernates documentation, and I couldn't find an entry for Payload in the JSR 303 Javadocs (if you know of one please let me know), so it raises the question of what it’s for... Looking at Hibernate’s documentation it states that: “an attribute payload that can be used by clients of the Bean Validation API to assign custom payload objects to a constraint. This attribute is not used by the API itself.” From this, you’d think that wouldn’t have to include it in your custom constraint declaration, but try taking it out and nothing works. This means that the validator is reflectively checking for its presence even though it’s not using it. Something smells fishy here.

Tuesday, 2 August 2011

Using the JSR 303 @GroupSequence Annotation

Yesterday’s blog covered JSR 303 groups, and today’s blog builds on that idea and demonstrates how to use the @GroupSequence annotation using the beans and custom constraints mentioned previously.

If you need to find all my blogs on JSR 303, then I suggest that you click on the ‘JSR 303’ label in the cloud below. They all follow the same Address bean validation theme.

Monday, 1 August 2011

Using JSR 303 Validation Groups

Anyone who’s looked at the code for a JSR 303 custom constraint will have noticed that the annotation interface declaration contains a couple of less than obvious attributes: groups() and payload as demonstrated by the @Country custom constraint below:

@Target({ ElementType.METHOD, ElementType.FIELD })
@Constraint(validatedBy = CountryValidator.class)
public @interface Country {

String message() default "{country.constraint}";

[] values() default "UK";

[] groups() default {};

extends Payload>[] payload() default {};

This blog covers the groups attribute in an attempt to explain its purpose.

Friday, 29 July 2011

Adding Optional Arguments to a JSR 303 Custom Constraint

When looking at JSR 303 you may have noticed that you can add argument values to some of the built-in constraints. For example:

  @Size(min = 2, max = 25)
private String street;


Thursday, 28 July 2011

Capitalization of Inferred Names

Today's short blog covers the rules for the 'Capitalization of Inferred Names'. This is something so basic that we're all supposed to know about it. These rules are often mis-named and referred to as, for example: 'JavaBeans property naming rules’.

Given that naming and precision is so import in our business, I thought that I'd jot down a link to the appropriate document, just for revision purposes. So, the definition for the ‘Capitalization of inferred names’ can be found in Page 57, Section 8.8 of the Sun JavaBeans Specification.

And, just in case you can't be bothered to click on the link, the capitalization rules are, to quote the document:

When we use design patterns to infer a property or event name, we need to decide what rules to follow for capitalizing the inferred name. If we extract the name from the middle of a normal mixedCase style Java name then the name will, by default, begin with a capital letter. Java programmers are accustomed to having normal identifiers start with lower case letters. Vigorous reviewer input has convinced us that we should follow this same conventional rule for property and event names.

Thus when we extract a property or event name from the middle of an existing Java name, we normally convert the first character to lower case. However to support the occasional use of all upper-case names, we check if the first two characters of the name are both upper case and if so leave it alone. So for example,

    “FooBah” becomes “fooBah”
    “Z” becomes “z”
    “URL” becomes “URL”

We provide a method Introspector.decapitalize which implements this conversion rule.

Wednesday, 27 July 2011

Adding a JSR 303 Custom Constraint to your Spring 3 Web App

In yesterday’s blog, I demonstrated how to write a JSR 303 Custom Constraint and validate it use Hibernate’s reference validator class javax.validation.Validator. Having written your constraint, the next step is to add it into your web-application, which couldn’t be easier.

Tuesday, 26 July 2011

Writng a JSR 303 Custom Constraint

Yesterday’s blog demonstrated how to write a Spring custom validator for an address web-app. At the same time I mentioned how that this method should really be marked as deprecated in favour of a JSR 303 custom constraint, and writing a custom constraint isn’t that complicated, it’s just a matter of implementing two basic steps:
  1. Create a constraint annotation
  2. Create a constraint validator
If the Hibernate Validator is on your path then these classes are picked up automatically, so there’s no need to hook things together.

I’m going back to yesterday’s contrived scenario of a Birmingham postal code validator for our Address object. As the code below demonstrates, all we want to do is to apply an

Monday, 25 July 2011

Applying a Custom Spring Validator to a Spring MVC Controller

Last month I wrote a blog demonstrating how to write a Spring validator using Spring’s Validator interface. Today’s blog demonstrates how to apply that validator to the Controller of a Spring 3 web-application.

Friday, 22 July 2011

java.lang.OutOfMemoryError: PermGen

Like most people, I’ve experienced the pain of a java.lang.OutOfMemoryError: PermGen exception when developing applications using a Weblogic server. It usually occurs when I’m running my Weblogic server with Sun’s Hotspot JVM and, like most people I’ve complained that the developers at Oracle should fix this problem, but the question is, can they?

Thursday, 21 July 2011

Using Spring’s HttpEntity Class to Parse the HttpRequest

Spring provides an HttpEntity class for dealing with HTTP request and response objects. This blog uses the HttpEntity class to pull the HTTP request apart and return it as a page. The first thing to do is to quickly write some HTML that’ll POST a request to the server giving us something to parse and return. For that, I’ve used the following form:

Wednesday, 20 July 2011

Using the Spring ResponseEntity Class

Spring’s @ResponseBody annotation, which I talked about yesterday, covers scenarios where you want absolute control over what’s passed back to your client in the Http response body. There are times, however, where you’ll want absolute control over both the Http response body and the response header.

Tuesday, 19 July 2011

Using Spring's @ResponseBody Annotation

Yesterday’s blog demonstrated how to use the @RequestBody annotation to map the HTTP request into an argument of your controller’s handler method. Today, I’m demonstrating its counterpart: @ResponseBody.

The @ResponseBody is used to map the return value from your controller’s handler method directly into the body of your Http response.

This works with a simple Http GET, so to test your controller, you’ll need a page containing the following link:

Monday, 18 July 2011

Using Spring's @RequestBody Annotation

Spring MVC has some handy-dandy annotations for mapping http data into your controller’s handler methods. So far, I’ve looked at, amongst others, @RequestParam and @PathVariable. Today, I’m looking at @RequestBody.

Sunday, 17 July 2011

Using the Hibernate Validation Annotation Processor

A few days ago, I blogged on the possibilities and problems of misapplying JSR 303 Bean Validation Annotations and concluded that a little more consistency was required in how exceptions are thrown when annotations are misapplied.

There is, currently in development, an validation annotation processor that’s designed to check whether or not you’ve applied validation annotations to your bean’s attributes correctly. It’s fully documented by Hibernate and the idea here is that you can test whether or not you’ve applied your constraints correctly by throwing up errors at compile time.

Saturday, 16 July 2011

Base64 Encoding with Apache and Sun Libraries

Base64 is a encoding scheme that is commonly used to create a textual representation of binary data. This is usually needed for either transmission of that data via a text based medium such as email, or storage in a text base repository. I don't intend to go into great depth on this as there is a full explanation on wikipedia.

Friday, 15 July 2011

Creating Striped Renderer for a Swing JList

Do you think that the default JList is boring? Do you want to spice one up a little? It’s actually a lot simpler than you may think. All you need to do is to change your JList’s list cell renderer. Creating a new renderer class is just a matter of extending DefaultListCellRenderer and overriding the getListCellRendererComponent() method as shown in the code below:

Thursday, 14 July 2011

Misapplying JSR 303 Annotations

One of the main things to remember when applying constraint annotations to your beans is that not every annotation can be applied to every data type. This is fairly obvious when considering the @Future and @Past annotations as from their names you can deduce that they’re applicable to date / time values of some description.

But, what about the more generically named annotations?

Wednesday, 13 July 2011

Using Resource Bundles with JSR 303 Validation and Spring 3 MVC Web-Apps

Even if your application doesn’t need to support different locales it’s always a good idea to separate the text displayed on your user’s screen from your Java code. In Spring 3 web-apps, this is usually done by using a ResourceBundleMessageSource to load a bunch of property files. My last blog demonstrated how to add JSR 303 Bean Validation to a Spring web-app, and you may remember that the error messages that were displayed on the screen were embedded in the Java code as message attributes on the JSR 303 constraint annotations. For example:

Tuesday, 12 July 2011

Validating a Spring 3 MVC Web-App Using the Hibernate JSR 303 Validator

My last blog covered the Maven POM entries required to implement JSR 303 - Spring Bean Validation in a Spring 3 MVC web-app. Having set things up, the next step is to actually validate a command object and the easiest way of doing that is to use the Hibernate JSR 303 Validator's built-in set of constraints.

Monday, 11 July 2011

Maven Settings for the Hibernate JSR 303 Bean Validator

The Guy’s at Spring, when talking about their MVC examples, always bang on about JSR 303 - Bean Validation, and why not, it’s an integral part of their validation strategy replacing the older inheritance based validation of deprecated classes such as SimpleFormController. The reference implementation for JSR 303 has been written by Hibernate and is available from the JBoss repository. To get hold of the validation JAR files you’ll need to either add the following to your settings.xml:

Sunday, 10 July 2011

Accessing Request Parameters using Spring 3 MVC

One of the neat things you can do in Spring 3 MVC is to map request parameters into specific controller method input arguments. This is done by applying the @RequestParam annotation to your controller method signature:

Saturday, 9 July 2011

Accessing Path Variables in Spring MVC

One of the neat things you can do in Spring 3 MVC is to map pieces of a URL request string into specific controller method input arguments. This is done by using a mixture of two annotations: @RequestMapping and @PathVariable. As mentioned in a previous blog, the @RequestMapping annotation is used to filter and route browser requests to specific methods using its arguments: value, method, params and headers.

Friday, 8 July 2011

Designing Spring 3 MVC Controller RequestMethod Handlers

When using Spring 3 MVC, you define a handler method in your controller using the @RequestMethod annotation. This annotation has four attributes, all well documented in the Spring javadoc, that are:

Thursday, 7 July 2011

Spring Bean Scopes: Singleton and Prototype

Spring defines two bean scopes in an application’s context: singleton and prototype. A singleton scoped bean is one that obeys the rules of the Singleton Pattern: ie. there is only ever one instance of your bean and this is the default when Spring creates its beans. On the other hand, when a bean is marked as a prototype, then for every call to getBean(...) Spring will create a new instance especially for you.

Wednesday, 6 July 2011

Tomcat JSP Compilation Exception

I was recently porting a simple web-app from Weblogic to Tomcat 7. Everything seemed fine, and it all deployed correctly. However, when I ran a simple test, by requesting the first page, I got the following exception:

Tuesday, 5 July 2011

Setting up a Tomcat Server in Eclipse Helios

This blog describes how to create a Tomcat server in Eclipse Helios. As a starting point I’m assuming that you’ve installed Tomcat and it’s running okay. If you’ve installed it using the Windows Installer, ensure that you stop the Tomcat service before you follow these instructions.

Monday, 4 July 2011

Installing a MySQL Datasource on Tomcat 7

The default installation of Tomcat doesn’t come with any datasource access, so it’s down to you to set this up and it has to be done manually as there is no wizzo web frontend that’ll do it for you.

The first thing to do is to copy database driver JAR file into the Tomcat lib directory. In my case I’m using the MySQL Community Edition, so I copied mysql-connector-java-5.1.6-bin.jar to Tomcat 7.0\lib.

Sunday, 3 July 2011

Installing m2eclipse Extras

m2eclipse also provides a set of additional features that can be installed from To install this eclipse plugin, go to Help | Install New Software, when the dialogue will appear. Then click the ‘Add...’ button and add the above URL together with some description or other. Finally, click Next and follow the instructions...

m2eclipse extras provide Maven integration for:
  • WTP (Web Tools Project)
  • Hudson
  • OSGi
  • Subclipse
  • Web Application Runner

For more information on installing m2eclipse take a look at the Sonatype m2eclipse page, though descriptions of these 'extras' are few and far between.

Saturday, 2 July 2011

Using Version Numbers in POM Files.

A top tip: when you have a POM file or set of POM files that reference a bunch of libraries that have the same version number, then it’s a good idea to setup a version property. To do this, add the following near the top of a parent POM:

Friday, 1 July 2011

A java.lang.NoSuchMethodError from a Spring WebApp

I was working on a Spring MVC web app recently when I got the following exception:
java.lang.NoSuchMethodError: org.springframework.web.context.ConfigurableWebApplicationContext
    at org.springframework.web.context.ContextLoader.createWebApplicationContext(
    at org.springframework.web.context.ContextLoader.initWebApplicationContext(
    at org.springframework.web.context.ContextLoaderListener.contextInitialized(

Thursday, 30 June 2011

Definition of ‘Convention over Configuration’

The words ‘Convention over Configuration’ are often bandied about in the programming world these days and I suspect that the idea has largely grown out of some of the complexities and muddles that have been created with XML configuration files.

As a ‘Convention over Configuration’ example, take the wine search scenario that I’ve often used in previous blogs. If I wrote a Wines class that represented a collection of wines then it’s associated database table should also be called wines and not, for example, fermented_grape_juice. I could then write any handling or client software so that if it came across a class called Wines it would automatically assume the name associated database table.

Wednesday, 29 June 2011

Using the Spring 3 ConverterFactory Interface

Yesterday, I mentioned that the Guys at Spring have come up with a whole new way of doing type conversion that supersedes the property editor support mechanism. This is based on the org.springframework.core.convert package and also I demonstrated how to implement the Converter interface and wire it in with your Spring beans. I also said that it offers additional functionality to the property editor support method and this comes in the form of the ConverterFactory, GenericConverter, and ConditionalGenericConverter interfaces. The Spring documentation briefly details these extra interfaces and how to implement them.

Tuesday, 28 June 2011

Using the Spring 3 Converter Interface

Yesterday’s blog covered Spring’s older property editor based conversion mechanism. Spring 3 introduces the new org.springframework.core.convert package that provides a complete conversion system, which offers much more functionality than previously available. This blog reimplements yesterday’s idea of regular expression conversion using the Converter interface; a fundamental interface of the new mechanism.

Monday, 27 June 2011

Writing a Custom Property Editor in Spring

Spring’s XML configuration file specifies the beans you wire together to create your application's context. When building your application context Spring, behind the scenes, is busy converting the property values in your XML file, written as Strings, into the correct type required by your bean and it does this using a set of built in property editors. A property editor is an Adaptor class that converts a String value in your XML file into the type required by your bean. For example, given the following bean setter:

Sunday, 26 June 2011

Bad Habits with the equals() Method

I have this really bad habit, it’s something I know I shouldn't do, so this blog is to formally document my failing in the hope that I will change. This bad habit concerns the Java if statement and its use with the equals() method. Like me, most people, when comparing a string variable with a string constant would probably write something straight forward like this:

Saturday, 25 June 2011

The Annotation Paradigm Shift

One of the current paradigm shifts in the Java world is to update existing APIs that were originally based on inheritance and replace them with much the same API only this time based on annotations.

For example, EJB 2.x used inheritance,

Friday, 24 June 2011

Discover from which JAR File your class is being loaded

A trick often used by certain organisations is to bundle up the Open Source project code on which their proprietary code depends into their own set of randomly named jar files and then to ship them with their products. The guys at BEA / Oracle are guilty of this practise and the upside is that it ensures that the classes used by their product are available and that they don’t get any ClassNotFoundExceptions. The downside to this is that it can lead to mix ups in your code with completing JAR files on your classpath, and possibly competing versions of the same class leading weird bugs.

Thursday, 23 June 2011

Applying the @Interceptors Annotation to EJB3 Beans

One of the new features of EJB3 is the ability to apply simplistic Aspect Oriented Programming (AOP) to your beans. This is achieved using the @Interceptors and @AroundInvoke annotations. I’ve called this ‘simplistic AOP’ not to deride it, but to compliment it. AOP can be a very complex topic, and if you only want to implement some simple functionality, like logging for example, then you need a simple tool to do it.

There are two steps to implementing interceptors,

Wednesday, 22 June 2011

Tag Lib Imports for JSPs

Yesterday I mentioned that I favoured a mixture of different JSP tag libraries, which has come about for no other reason than convenience, which were Spring, JSTL and Struts. Having said that I thought about why I use them and the features I use from each one.

Tuesday, 21 June 2011

Accessing Spring Resource Bundles from your JSPs

Yesterday’s blog demonstrated how to create and load a set of multi-lingual property file that you can use to internationalise your application. Today’s short blog expands this idea and demonstrates how to access property file values from within your web-apps JSP pages.

The usual way to achieve this is to use JSP tag-libraries. There are many flavours of tag-lib around that duplicate much of the same functionality. My preferred flavours are: struts, JSTL and the Spring tag-libs and it’s the Spring tag lib that I’m using to read property file values.

The first step in using a tag-lib is to add an import line,

Monday, 20 June 2011

Using Spring, ResourceBundles and Locales

Yesterday’s blog covered the Locale class and talked about determining what locales your JVM supports. Today’s bog moves on to how you make use of this information by loading locale specific property files into your Spring application.

When internationalizing your application, it’s common practice to create a property file containing all your presentation strings for each locale you support together with an additional file for those locales that you don’t support.

Spring and the JDK uses the name of your property files to determine their locale. The file name format is:

Sunday, 19 June 2011

Listing Locale Information

In writing a global application - if there is such a thing - you’ll often need to add locale specific information. From a Java perspective, a locale is an arbitrary combination of language and country information held in several different ways. This can then be used as a key to describe a whole bunch of other information such as number formatting, currency details and dates and times.

Saturday, 18 June 2011

Is the Spring Validator mechanism as friendly as it could be?

When I first came across the Spring validator classes in October 2006, I thought at the time that they weren’t particular clear. They seem fit into that realm of programming where everyone just copies what other people have done without understanding what’s going on and it all works, which is how I’ve seem them used. I guess that today it’d be called Cargo Cult programming. As you know from my previous blog, ValidationUtils will validate your target object without any obvious reference to it, which to me is confusing. You also know that you can pass null in to the Validator.validate() method for the target object, but again there’s no explanation why.

Friday, 17 June 2011

The Spring Validator Interface and Other Animals

An important part of any application is validating your user’s input and the bitter experience of spending hours debugging code that’s failed owing to bad data only serves to underline how crucial this is.

You should virtually always perform user validation at the presentation level and a top-tip is to always factor your validation code into a distinct set of objects and to avoid interweaving it in with

Thursday, 16 June 2011

The Difference Between JSON and XML

A few days ago I did a blog Comparing XML and JSON. Today I will be illustrating the difference between JSON and XML using a simple coding example. So, straight to the point: XML is human-readable data interchange specified in a document format, whilst JSON is human-readable data interchange data format.

Wednesday, 15 June 2011

Using Environment Variables

Java SE 5 re-introduced the idea of allowing Java programs to get at a system's environment variables (I seem to remember that you could do this in the old days and that is was removed for 'non-portability' reasons).

Environment variables are accessed using the System.getEnv() method, which comes in two flavours:

Tuesday, 14 June 2011

Maven POM Settings for JSON APIs

Having talked about JSON and XML yesterday, I mentioned that there are a number of successful APIs available for both data interchange systems. The two APIs I’ve used for JSON are JSON in Java available from the JSON website and the JSON-Simple API from Google.

Monday, 13 June 2011

Comparing XML and JSON

There seem to have been, at various times, some argument about which open standard for human-readable data interchange is best: JSON or XML. This blog takes a look at these two standards and compares the two,

Sunday, 12 June 2011

Using Spring's DisposableBean Interface and a Shutdown Hook in Life-Cycle Management

A few days ago I demonstrated the Runtime class and covered the concept of shutdown hooks to ensure that you can cleanly tidy up external resources when your JVM closes down.

As part of the Spring context life-cycle, it’s pretty important to ensure that your Spring beans close down correctly, especially if they access external resources, and this is where the JDK’s shutdown hooks comes in handy.

Saturday, 11 June 2011

Loading Resources Using Spring’s ApplicationContext

Using the ApplicationContext, the guys at Spring provide a uniform way for your application to access various types of resources. These may be a file on the file system or on the classpath or something more remote on the Internet.

Friday, 10 June 2011

Reading and Writing Property Files

Your application will usually need some configuration data that can be set-up prior to run-time and determines how your application runs. A common method for achieving this is to use a one or more property files and these are usually read and written using the Properties class.

Thursday, 9 June 2011

Using the JDK’s Runtime Class

“Every Java application has a single instance of class Runtime that allows the application to interface with the environment in which the application is running” is the brief JavaDoc entry for the JDK’s Runtime class, which, if you examine the methods it contains, doesn’t really cover what this class does.

Wednesday, 8 June 2011

Implementing Spring's FactoryBean Interface

There are times, and not many of them, when Spring cannot load an object in to its context. This is usually the case then the object you’re trying to build has a private constructor and a static factory method (which by convention should be called getInstance()) and cannot be instantiated by simply calling new.

Tuesday, 7 June 2011

Spring's Application Context Event System

Spring provides a simple and lightweight publish/subscribe or Observer mechanism built around the ApplicationContext. This is a synchronous mechanism in that the event listener code is called during the call to the publishing code.

If you’ve seen this before, you may not know that this system has been updated in the Spring 3 release to use Generics.

Monday, 6 June 2011

Using Spring's ApplicationContextAware Interface

I’ve been trying to think of reasons why you shouldn’t widely use Spring’s ApplicationContextAware interface when constructing your Spring beans. On the surface it seems like rather a bad idea, but with the release of Spring 3, my last reservation has disappeared.

Sunday, 5 June 2011

Using Spring's BeanNameAware Interface

Although it’s not a good idea to rely on the BeanNameAware as it adds a “potentially brittle dependence on external configuration”, it is a useful debugging feature especially in the situation where you need to instantiate a number of beans using the same class with each configured in a different way.

Saturday, 4 June 2011

Prefer Injecting EJBs via Setter Methods

If you read many of the EJB3 texts you’ll see that they advise you to use the @EJB annotation to inject one ejb into another. This is all good and fine as in a deployment situation the container will neatly inject one bean into another, but, and here’s the problem, all the books and info that I can find on the Internet always recommend that you annotate your injected instance variable. For example, in yesterday’s blog I defined a very simple User ejb and if we use the recommended method for injecting it into another ejb, then we’d annotate our other ejb’s instance variable like this:

Friday, 3 June 2011

EJB3 Stateless Session Bean Annotations

Creating a Stateless EJB using EJB3’s annotations is very simple. Just in case you can’t remember this is how to annotate your java code to create a simple User bean.

Thursday, 2 June 2011

Implementing the Observer Pattern using Composition

When I previously discussed the Observer pattern I recommended following Joshua Bloch’s advice and “favor composition over inheritance” and suggested that the JDK’s implementation of the Observer, Observable, though convenient, was somewhat flawed. This blog demonstrates how to implement the Observer pattern using composition. The benefit of using this technique is that it clearly upholds the single responsibility principle broken in several places by my earlier news server examples.

Wednesday, 1 June 2011

Stateful Session Beans and the @Remove Annotation

There’s not a lot you can really say about Stateful Session Beans except that I’ve never seen them used in large systems owing to the overhead of maintaining a bean in memory for every client and when you’re processing thousands of client requests per second then that’s a lot of memory.

Tuesday, 31 May 2011

UML, the Template Class and Java

One problem you often see when dealing with UML is that some developers don’t get the idea that what you see in class diagram should translate directly into code they draw a class diagram and write some code and neither bare any resemblance to each other. This, and other forthcoming blogs in the series, demonstrate the link between diagrams and code.

This blog demonstrates how to draw a template class in UML followed by its equivalent Java code and looking at it you'll notice that the Java code is all about generics. I guess that's because UML's template class idea stems from C++'s template classes, which are similar to, but not a direct equivalent of Java's generics.

Monday, 30 May 2011

EJB3 Transaction Annotation

This blog documents the EJB3 transaction annotations and was written because I had to add a transaction annotation to an EJB recently and the javadoc for JEE 5 didn’t document what the TransactionAttributeType values do; some are obvious if you’ve done this before, but I'm not psychic.

Sunday, 29 May 2011

Message Driven Bean Annotations for EJB3

The other day, I blogged about the name and mappedName attributes of @Stateless, @Stateful and @MessageDriven annotations of EJB3.

In writing that blog, it occurred to me that it’s very hard to find information on which attributes are available. In the good ol’ days of EJB 2.x, all you had to do was to look at the appropriate EJB schema file and you knew which XML element and attributes did what.

Saturday, 28 May 2011

The Observer Pattern

Having written two blogs that mentioned the Observer pattern, I thought that I’d talk about it more formally, mainly because the Wikipedia entry for this pattern is a bit rubbish: the Java example given doesn’t implement the class diagram shown and uses the flawed Observer, Observable classes instead. Looking back at my GOF Design Patterns book, the actual pattern should be something like this:

Friday, 27 May 2011

Using EJB3 Annotations with Weblogic 10.3 / 11g

It seems to me that BEA and now Oracle are usually behind the curve when it comes to implementing the latest JEE specifications and often interpret things rather differently to the guys working on the Glassfish reference implementation.

Thursday, 26 May 2011

Implementing the JDK's Observer Pattern

Yesterday’s blog talked about the ActionListener event handler's implementation of the Observer pattern that is woven throughout Java’s Swing classes. The JDK duplicates this pattern in an implementation with classes called Observer and Observable.

Wednesday, 25 May 2011

Events and the ActionListener

The ActionListener event handlers are an implementation of the Observer pattern that is woven throughout Java’s Swing classes. It’s used by buttons to inform their clients that they’ve been pushed, it’s used by menu items to tell the application that a selection has been made, by the JFileChooser to select files and by many other classes.

Tuesday, 24 May 2011

The Three Laws of Test Driven Development

I’ve mentioned Test Driven Development several times in this blog, but haven’t yet got around to defining its three principle rules. These were, I think, first documented by Bob Martin in IEEE Computer Society Journal of May/June 2007. To summarise, the three rules are:

Monday, 23 May 2011

Primitive Wrapper Classes and Their Factory Methods

The java SDK primitive wrapper classes such as Integer, Boolean and Long come with a whole bunch of often ignored factory methods that can be used to improve performance. Indeed, the best advice when converting a "true" or "false" is to use

      val = Boolean.valueOf("false");

rather than

Sunday, 22 May 2011

Using the Builder Pattern to Construct Thread-Safe Objects

A couple of days ago my blog described the benefits of creating immutable POJOs in order to make your programs more thread-safe. Today’s blog builds on that idea, by demonstrating the use of the Builder pattern to construct your POJO’s. It’s strange that I haven’t discussed this before as it’s one of my favourites. You can find it in more detail in Joshua Bloch’s Effective Java Second Edition - page 14.

Saturday, 21 May 2011

The Telescoping Constructor (Anti)Pattern

The Telescoping Constructor is an example of a pattern that borders on an anti-pattern that is all too often used in projects even though there are better alternatives availble. In this pattern, your POJO has numerous constructors each taking a different number of parameters that, if the class has been written correctly, delegate to a default constructor.

Friday, 20 May 2011

Thread-Safe Immutable Objects

Threading problems are the most weird and difficult bugs to fix, mainly because they’re so hard to reproduce. You can mitigate some of these problem by designing thread-safe code, which isn’t so hard as you think.

The code below is an example of a thread-safe technique that's for synchronising the update of instance variables without the need for language specific locking and mutexes. The big idea is that we tie two or more instance variables together in a bean. The fields are final and obey the Java rules of only being updated table during either static initialisation or when the constructor is called.

Thursday, 19 May 2011

Generating Message and Correlation Identifiers

SOA messages often need to include, as part of their schema, some kind of unique identifier. This is usually called ‘message identifier’ or even ‘correlation identifier’. The idea here is that when a calling service receives a reply from your service, it’ll know what your service is talking about. This is especially helpful when the call is asynchronous.

Wednesday, 18 May 2011

String Formatting

Crusty old Java hacks, myself included, use the StringBuffer class (or StringBuilder) to stitch together strings, but Java 5 added String formatting classes to the API to and a ‘C’ style printf(...) to the System.out class to make life easier.

These newer classes are seemingly often under-used, but pretty straight forward...

Tuesday, 17 May 2011

Are finalize() Methods Useful?

Under normal circumstances, the finalize method is not of much use when programming everyday java code. Indeed, Joshua Bloch states, in his book Effective Java, that "finalizers are unpredictable, often dangerous, and generally unnecessary"; given this view, it's not surprising that the section of the book I'm referring to is called 'Item 6: Avoid finalizers' (see Page 20).

Monday, 16 May 2011

Creating a Spring Web Service Using Version 2.0.1.RELEASE

I thought that I’d write a Web Service using the Spring Web Services product. This is described as a Contract-First web service; however, the guys at Spring have made life a little easier for us in that the product can dynamically create a WDSL file, which is a feature that we’ll be using.

The scenario for this example is of a wine search service, in which the client sends a request containing a country name and gets back a list of wines produced by that country. For the purposes of this example, I already have a business service POJO and that I’ll be injecting it into my web service code.

Sunday, 15 May 2011

Web Service Design: Contract-First or Contract-Last?

Web service design seems to come in two flavours contract-first and contract-last. Contract-first starts with designing the XML schema / WSDL and then creating the Java interface based upon the schema.

Contract-last takes an existing Java interface and from that, creates your web service. On reflection, you’d think that this meant create a schema contract, but generally it seems to mean getting hold of some tool that will take a Java interface as an input and deliver a WSDL as an output.

Saturday, 14 May 2011

An Easy Way to Build a Schema Using XMLBeans inst2xsd

I know that I’ve mentioned this tool before, but I was too brief. This blog rectifies that by demonstrating how easy it is to build your self a schema using a little sample XML and inst2xsd, which is free.

Friday, 13 May 2011

SAXBuilder ClassNotFoundException When Creating a SAX Parser.

I was recently using JDom to parse some XML.

      InputStream is = new FileInputStream(fileName);

      SAXBuilder builder =
new SAXBuilder();
      retVal =

Everything was pretty straight forward untill the code ran, when the build() method threw a ClassNotFoundException

Thursday, 12 May 2011

How to Schema Validate XML Using SAX

This blog builds on my Checking for Well-Formed XML blog creating a class that can validate XML messages against their schemas by using extra features available in the SAX parser.

This example uses JDom, as part of its interface, but you could use any XML API, such as XmlBeans, or even pass in a String.

The steps required to create a schema validator class are:

Wednesday, 11 May 2011

inst2xsd and Other Useful Tools

No matter how much you think you know about a tool, pattern or subject, there’s always something useful that pops up from time to time. I’ve been using XmlBeans for a number of years and only found out about inst2xsd the other day and all this time I’ve been writing XML schemata by hand.

This little blog is just a quick reminder that Xmlbeans provides useful tools as well as a useful API by demonstrating how to use inst2xsd.

The simplest way of using inst2xsd is to type:
inst2xsd /filename.xsd
This will produce a schema file called schema0.xsd whose contents won't be perfect, which means that you'll need to fiddle around with it tailoring it to meet your exact needs.

For more information on inst2xsd see inst2xsd on the xmlbeans tools page.

Tuesday, 10 May 2011

Breaking the Single Responsibility Principal

One of the most important programming principals is the Single Responsibility Principal (SRP), which states that an object should have one, and one only, reason to change its state.

Monday, 9 May 2011

weblogic.xml Versions in your Webapp

Using the wrong version of weblogic.xml in your Weblogic webapp causes eclipse to shout about a whole bunch of errors. For example, using the following schemata:
<wls:weblogic-web-app xmlns:wls="" xmlns:xsi="" 
causes the following error:

Sunday, 8 May 2011

Unit Tests and the FIRST Acronym

ObjectMentor came up with a really good acronym to describe Unit test, it’s FIRST and it describes all the qualities of a good test.

Saturday, 7 May 2011

Java Primitive Sizes

The sizes of Java primitives are:

TypeMin ValueMax ValueBits

Friday, 6 May 2011

Generic Factory Class - Sample

Previously I’ve talked about generic classes and generic methods. This blog combines the two and demonstrates how to write a generic factory class. Now, as this is a blog, we’re keeping it simple and assuming that the classes we wish to use our factory to create have a default no-arg constructor and are public - you can add extra detail in to deal with constructor args.

Thursday, 5 May 2011

Using Generic Methods

This blog adds to my previous couple of blogs about using generics, by introducing Generic Methods. My other blogs dealt with sample code that parametrise entire classes, but it makes more sense to parametrise a single method rather than a whole class if possible.

Wednesday, 4 May 2011

Using Generic bounded wild-cards in an API

Yesterday’s blog touched on the strange aspect of bounded wild-card generics showing that you can create typed collections into which you can’t add anything except null. The example, covering Fruit classes, begs the question of why you can write ? extends Fruit.

Tuesday, 3 May 2011

Are Generics Overly Complicated?

Generics, introduced in Java 5, are widely used in Java programs today especially in the arena of collection classes. What are not so widely used and little understood by average programmers are generics that use bounded wildcards (and don’t forget that by definition nearly everyone is average).

Monday, 2 May 2011

Using the Visitor Pattern

The visitor pattern is a method of separating an algorithm from it’s data with the result that you can add new algorithms easily without violating the open/closed principal.

Sunday, 1 May 2011

Null Collections and the Special Case Pattern

In my last blog I covered the Special Case Pattern demonstrating a special case NullEmployee object in an employee details scenario. What it doesn’t cover is the
public List<Employee> getEmployeesBySurname(String surname)
method. This method must also adhere to the Special Case pattern and not return null when there’s no data available.

Saturday, 30 April 2011

Null Return Values and the Special Case Pattern

My previous blog talked about the problems associated with nulls being somewhat awkward to deal with and how this problem can be mitigated using exceptions. From my last blog, you’ll also probably guess that I believe that even using exceptions isn’t great a idea and that the best approach is to force your objects to do even more work. This blog uses the same contrived employee details scenario to implement Martan Fowler’s Special Case Pattern.

Friday, 29 April 2011

Dealing with Null Return Values

One of the things most of us do is to return null from their methods without questioning the validity of the technique. It should be widely excepted, but isn’t, that returning null is a bad idea as it forces any and all client code to constantly check method return values and take special action when they are null. Not only does your client code need to constantly check for null there is also the increased risk of a NullPointerException as it’s easy to miss a out a check altogether, which from experience, is a common occurrence.

Thursday, 28 April 2011


Oracle EZCONNECT is a database connection technique that does away with the need to look up service names in tnsnames.ora when connecting via a network. It provides for connection by enhancing the original connection string format of:
CONNECT username/password@service_name
The updated format allows for the use of a connection URL to enhance the service_name:
CONNECT username/password@//host[:port][/service_name]
Where host is either the host name or IP address of the database, port is an optional port number defaulting to 1521, whilst service_name is the database service name, which defaults to the host name.

For example:
CONNECT Scott/tiger@//
A complete description of this is available on wikipedia.

Wednesday, 27 April 2011

Using an Oracle Function Index as a Constraint

Two previous blogs of mine have talked about Oracle’s Function Based Indexes:

In what should be the final blog on the subject I’m going to cover a more complex use of function based indexes to enforce a rule-based constraint.

Tuesday, 26 April 2011

The Difference Between Method Overloading and Method Overriding

When taking the Oracle Certified Professional, Java SE 6 Programmer exam, one of the tricks used to try to catch you out is to try to confuse you over the meanings of overriding and overloading methods and I guess that this is because they have similar sounding names. This blog clarifies all that - take a look at the code...

Monday, 25 April 2011

hashCode() Tips.

Did you know that a hash code MUST be a positive value and that String uses the hashCode() method inherited from Object.

Sunday, 24 April 2011

Exception Ordering

Exceptions caught in a catch block must be caught in order of precedence, starting with the most specific and ending with the most general. The following code will compile:

Saturday, 23 April 2011

The Evolving switch Statement

One thing about working in programming is that things change; you can count on it, new things are written, tools become in vogue and techniques go in and out of fashion. One thing that changes somewhat less often is the Java language itself, though it is evolving and for the better.

Consider the humble switch statement: at the time of J2SE 1.4 you could make a choice based upon an int value:

Friday, 22 April 2011

chars and shorts: useful stuff to know?

It seems logical that the compiler should be able to automatically convert a char into a short, after-all they’re both 16 bits wide...

Thursday, 21 April 2011

Qualifying @Ejb Annotation to Resolve Injection Problems

A few days ago, I wrote a blog about simplifying EJB3 and Spring by using Spring’s SpringBeanAutowiringInterceptor which allows you to dispense with a certain amount of boilerplate code. In writing my sample code (remember the golden rule: never use a technique, api, pattern or algorithm professionally until you’ve used it to write some sample code) I did some rough refactoring of an existing EJB3 sample with the result that I had, in my JAR file, two implementations of an @Remote interface.

Wednesday, 20 April 2011

Floating Point and Divide By Zero

Did you know that dividing a double by zero will not throw an ArithmeticException? This seems rather inconsistent to me as dividing an int by zero will.

Tuesday, 19 April 2011

Subversion Error: Failed to get lock on destination repos

During a regular copy of my main Subversion repository to a mirror I got the following inexplicable error message:

Monday, 18 April 2011

Using a Spring ContextSingletonBeanFactoryLocator

When writing EJBs using Spring you often bump up against the ContextSingletonBeanFactoryLocator, a class that extends SingletonBeanFactoryLocator. As the name suggests, it’s used to create a singleton Spring context, and this is useful in EJB development as it seems preferable for all EJB instances in your bean pool to share the same Spring context: indeed I have fixed bugs in EJBs that were the result of loading one Spring context per EJB instance.

Sunday, 17 April 2011

Auto-wiring EJB3 Beans with the Spring SpringBeanAutowiringInterceptor

The usual technique for creating an EJB using Spring is to extend AbstractStatelessSesstionBean and then to use the ContextSingletonBeanFactoryLocator to load your configuration via a beanRefContext.xml file. You would then load your Spring beans by overriding onEjbCreate():

Saturday, 16 April 2011

Unexpected Spring Exception

One of my golden rules of coding is never to use a technique, api, pattern or algorithm until I’ve used it to write some sample code. With this in mind I took a simple EJB3 stateless session bean I’d previously written with the aim of adding a Spring SpringBeanAutowiringInterceptor, which I’d never used before. This shouldn’t have been too difficult as the code built, ran and passed all its tests. So, I wrote the code and created the simplest of JUnit tests that loaded my Spring context from a simple XML file:

Friday, 15 April 2011

Code Optimization

Two rules of code optimization: 

  1. Don't do it.
  2. For experts only: don't do it yet. -- M. A. Jackson 1975

Thursday, 14 April 2011

Using Spring JmsTemplate

One very useful reoccurring Spring pattern is the use of template helpers that take hard work out of some very boring day to day stuff. The guys are Spring have provided a considerable number of template classes including JdbcTemplate, JdoTemplate and SqlMapClientTemplate. One of the most useful is the JmsTemplate, which is a way of managing JMS connections. It is incredibly flexible as it works in collaboration with several other helper classes including JndiTemplate, JndiObjectFactoryBean and JndiDestinationResolver.

Wednesday, 13 April 2011

Setting Null Values in Spring Config

There are some occasions when you need the ensure that null values are passed to objects defined in Spring XML. Now, with you own objects you don’t usually need to bother with this as you can design then to ensure that attributes are initialised to null during their creation.

Tuesday, 12 April 2011

Comments in Your Code

Are comments a good thing? I know I used to believe that they were for years, starting with my days of writing Basic on an Apple IIe, through C, C++ and finally Java. But technology changes, techniques evolve and somehow, in today’s world comments in your code usually aren’t all they’re cracked up to be.

Monday, 11 April 2011

More Spring Java based DI

Yesterday’s blog covered the new Java based dependency injection (DI) feature of Spring 3 demonstrating how to create and instantiate a simple factory class using @Configuration annotation. So far so good, but those clever chaps at Springsource have thought this through quite thoroughly and provided much more flexibility than I demonstrated yesterday.

This blog goes into slightly more depth than yesterday’s demonstrating how to use some of those additional features.

Sunday, 10 April 2011

Spring's Java Based Dependency Injection

One of the new features of Spring 3 is the ability to configure your good old POJOS using a new Java based dependency injection (DI) feature. This was formerly known as Spring JavaConfig and, since Spring 3 now only supports JSE 5 and above, it’s been incorporated into the core Spring Framework. This is an annotation based DI where the beans or POJOs that you’re linking together remain untouched by annotations and, being Java based, you get a lot more programmatic control over object instantiation.

Saturday, 9 April 2011

Checking for Well-Formed XML

Checking For Well-Formed XML

In several SOA projects I’ve worked on the test team generate their test XML by hand, which is a long winded, error prone business. The problem with this is that stuffing lots of broken XML into your code generates lots of invalid bugs. A top tip to negate this problem is to always check that any XML passed as arguments to your code is well-formed - and do this first. The code below demonstrates how to do this using a validator class.