JSR 303: Combining custom and standard validators

We are using the JSR 303 Bean validation API (Hibernate validator as the implementation) on a project and recently faced a problem.
Whenever we were using our own custom validators in combination with standard validators like NotNull and NotEmpty, the standard validators seemed to be ignored.
The result was that we were getting NullPointerExceptions in our custom validators and sometimes we were getting duplicate error messages for the same invalid field.
I haven’t poured over all of the JSR 303 documentation in detail so maybe I’ve missed a recommended best practice but the following code in the default NotBlankValidator gave me a hint.

public boolean isValid(String s,
ConstraintValidatorContext constraintValidatorContext) {
if ( s == null ) {
return true;

Why would you ever return true (i.e. valid) for an input that is null? That doesn’t make sense until you realise that validation is a *combination* of all constraints.
This means that your validator should only return false for your specific test. If it fails for a chained validation, for example if input is null, it should return true and rely on the NotNull validation to report that error.
You still have to guard for null and empty inputs but return true if they occur rather then returning false.
Hide any required basic validations inside your custom constraint annotation. For example NotBlank does that:

public @interface NotBlank {

Caching the remote interface of a Stateless Session Bean

We have asked this question several times in our organisation and I have seen it being asked many times in various web forums.
I suspect that the reason why there is no correct answer is that it all depends on your environment.
Some people report very good results with one approach but the same approach may not be efficient or not even functional somewhere else; such as in a clustered environment.
The options:
1. A common basic approach is to store the reference to the remote interface in the http session. Once it has been stored, all clients can quickly access business methods of the stateful session bean. You should use business delegates to communicate with your EJBs.
According to the specification (EJB spec 2.1FR, section 7.8):

There is no fixed mapping between clients and stateless instances. The container simply delegates a client’s work to any available instance that is method-ready.

This means that even with a single remote interface, the container will delegate what bean instance should serve a client call.
With stateful beans the case is the contrary. A remote interface will always guarantee calls are delegated to the same stateful session bean. This of course is crucial to enable a dialog between a client and a stateful bean.
2. The JNDI lookup of a home interface is the costly part of locating an EJB. As such, storing a reference to the home interface is a second approach.
Because application servers may use the create() method as load balancing trigger this approach may behave better in a clustered environment. Consider using the service locator pattern to collect all your service lookups to a single point.
3. A handle to an EJB has the advantage of being serialisable and valid between multiple JVMs. It seems to be the superior way of storing a reference to an EJB.
It is only possible to acquire a handle to EJBs that implement remote interfaces. With EJB 2.0, you will see that many EJBs implement local interfaces only to improve performance. Only the session facades will be exposing both local and remote interfaces.
To be future proof, it is safest to assume as little as possible about the behaviour of your J2EE server and avoiding short cuts.
This will ensure that your application can move from a testing environment to a full clustered, load balanced production environment or a different j2ee application server.
JNDI lookups of the home interface is the expensive operation so implement a service locator that caches home interfaces. Make sure all of your code is using this single point of looking up EJBs. It will then be possible to change the lookup strategy in the future if needed.
The server side
Service Locator pattern
EJB 2.1 Specification

Hello J2ME World

With my recent upgrade to SonyEricsson T630, a new geek opportunity presented it self: to develop Java applications for my very own mobile. Priceless.
Because I am fairly familiar with Java and the fantastic, open source, IDE NetBeans it was easy to develop and deploy my first HelloJ2MEWorld application.
NetBeans has an extension module focused on J2ME development. Download it and NetBeans will be able to help you with your Midlets, JARs and obfuscation.
NetBeans is using the Sun J2ME SDK. If you want to be more device specific, I’d recommend you to download an SDK directly from the mobile maker you are interested in. Two obvious choices are SonyEricsson and Nokia.
Try out and debug your application on one of the supplied emulators.
The last step is to transfer your application to your mobile. You have a choice between infrared, bluetooth, USB cable and Over-the-air (OTA). Since I am developing on a IR enabled laptop, ir was the best option for me.
First application that came to mind for developing was of course a mobile blogging tool. A quick search on Google returned the just started open source project MIDLog. So instead of starting from scratch and probably duplicating all work done in MIDLog, I am hoping to contribute to MIDLog.
The J2ME world is crowded with two main MIDP versions, WTK versions and various JSRs (Java Specification Requests). While many exciting features are planned for future version of J2ME, todays devices are very limited.
Example, the T630 supports the “new” multimedia API (MMAPI – JSR 135) but Sony has chosen to support the sound part only. This means that there is no support for image capturing and I suspect this will make it very difficult to develop a mobile blog tool capable of posting images.

Netbeans 3.6

I have been using NetBeans 3.6 for a couple of days now and can say it’s a very good improvement on the previous version 3.5.1.
(NetBeans is a free, open source development tool. Mainly for Java development but also suitable for C/C++)
The intention was to wait until end of summer 2004 and release version 4.0 but because of the fierce competition (Eclipse, IntelliJ, JBuilder and etc) an intermediate version was released with promises of what is to come.
The most prominent change is that the window system has been completely redone. Away with the clunky and very Java-ish interface. In with a leaner, more native looking and intuitive one.
While I suspect that this enhancement required a lot of work input, the user will not notice too much difference (this is good).
Other useful features include code folding, smart brackets, help with overriding methods, Servlet 2.4 and JSP 2.0 code completion and much more.
In previous versions it was needed to download several modules after an install but they all seem to be included in 3.6: database explorer, XML/XSL support, tasklists and more.
NetBeans 3.6 support J2SDK 1.4.1 and above but prefers 1.4.2 so make sure to update it from Sun web site.

Validating a DB Connection

You may have been tempted to execute Connection.isClosed() to test whether a connection is live and can be reused. This is however not sufficient as the Sun JDBC API guide states:

“Note that the method Connection.isClosed is guaranteed to return true only when it is called after the method Connection.close has been called. As a result, a programmer cannot depend on this method to indicate whether a connection is valid or not. Instead, a typical JDBC client can determine that a connection is invalid by catching the exception that is thrown when a JDBC operation is attempted.”

The only safe way of ensuring that a connection is valid is to execute a tiny query and catch any SQLExceptions thrown. If no exceptions are thrown, you can go on and using that connection.

If any exceptions are thrown, it is safest to close that connection, set the reference to null and create a new connection.

What query to execute?

It would be nice to execute a general (database independent) method like Connection.getMetaData(). Unfortunately I have seen some indication that this may be successful even when a connection is invalid.

To be on the safe side it is best to execute a query like “SELECT COUNT(*) FROM WHERE 1 = -1″. We are using SQL server so the table sysusers is a safe bet:

     * A method that tests whether a connection is valid by executing
simple query and catch any exceptions

    private boolean connectionIsValid(Connection dbConn) {
        //log.debug("ENTER connectionIsValid(): "+dbConn);        
        boolean result = true;
        PreparedStatement psr = null;
        try {
            //Prepared statement is used to cache the compiled SQL
            psr = dbConn.prepareStatement("SELECT COUNT(*) FROM sysusers WHERE 1 = -1");
        catch (SQLException e) {
            log.debug("Excpetion occured, connection is not valid. "+e.getMessage());
            try {
                dbConn.close()//dbConn is never null at this point
            catch (Exception ee) {
            result = false;
        finally {
            try {
                //free up resource kept by the test statement
                if (psr!=null) {
            catch (Exception e) {
        //log.debug("EXIT connectionIsValid(): "+result);
        return result;

Netbeans IDE, pros and cons

NetBeans IDE has been my prefered IDE for the last 1.5 years. The reasons are several. OpenSource software, continuously extended and last but not least, it is free. While it doesn’t have as many features as some £3,000+ IDEs, it has enough to keep you busy.
The features that I find most useful and use every day because they speed up the development.
There is the DB explorer that lets me browse a data base to see the tables, data types, values and lets me execute any queries (including updates).

Continue reading “Netbeans IDE, pros and cons”

java.io.Reader issues

I have developed an XML converter that is based on the Castor framework. It is quite simple as it takes certain Java objects (beans, collections and maps) and returns an XML representation.
Actually I have implemented it so it returns an InputSource which goes well with the next step in the process, the Xalan transformation.
The problem I am having is that the InputSource can only be used once whereas we would like to use it multiple times. At least once to log the converted XML and second time for the XSLT. As soon as the input source has been used for logging purposes of the XML, the internal reader is empty and I have not found any way of resetting it.
I see two solutions. Either redesign the XMLConverter to store the XML content internally in a different way or write a utility that copies the content of one reader to another reader, while it outputs the content.

And all that Work

I wish the title was saying ‘And all that Jazz‘ but it is not because it is Saturday noon and I am working. At least it is from my own bed and with Ginger next to me.
The annoying thing with the recent project has been lack of design and the scope of technologies that are in use simultaneously. I have no problems working with a couple of those technologies but all at once takes away some of the concentration.
We are using an unorthodox mix of Data Access Objects (DAOs) and EJB 2.0. What we learned was that you have to watch out not using both technologies to update your precious data base tables. If you do, the EJB container locks the tables and your DAO methods start failing and rolling back to left and right.
I have previously used XDoclet to help with the formalities of EJB 2.0 and Struts framework. This time we have not taken the time (pun intended) to set up XDoclets so it is a pain every time the data model changes or the EJB implementation is updated and the interfaces need to be updated accordingly. At this point of the project, nearly end, it doesn’t make sense to start adding XDoclet tags and modifying the Ant build scripts but I have made a mental note to use XDoclets from the beginning next time.
The front-end is prepared for internalization and device independent rendering by using XML/XSL. I found that the Castor frame work is great for converting your complex Java objects to an XML representation. Later Xalan is used for the XSL transformations. One trick from the big bag of tricks is to have dynamic XSL style sheets by using JSPs. This allows us to use constants from our standard Java interfaces and to internalize our pages with the help of JSTL.
Axis framework is a great help for setting up web services for cross application wide services and sending those SOAP calls.
There has not been as much JUnit testing as we first anticipated due to lack of time. Instead of writing JUnit suits for all classes I have only written tests for core utilities that are used by several modules in the application. It was quicker to write the tests and making sure the utilities pass than to face kludgy code that would need thorough debugging.
The mix of everything is fun but just when you are getting groovy with the required on-the-fly design and UML modeling you are interrupted by some nasty JavaScript debugging or even worse, CSS problems.
I wish we find the resources to have a couple of front end developers (scary, MS Word just highlighted the last word because it found the same entry in my Outlook contacts, too smart for my liking).