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;

or

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 http://m2eclipse.sonatype.org/sites/m2e-extras. 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
        .setId(Ljava/lang/String;)V
    at org.springframework.web.context.ContextLoader.createWebApplicationContext(
        ContextLoader.java:264)
    at org.springframework.web.context.ContextLoader.initWebApplicationContext(
        ContextLoader.java:197)
    at org.springframework.web.context.ContextLoaderListener.contextInitialized(
        ContextLoaderListener.java:47)