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 {

Transforming in Wales

wales.jpgI was in a bit of a pickle: a planned training session in Wales (5 hours drive away) but a heavily pregnant wife at home refusing me being away over night.
So I squeezed it all into a single day. Up at 4am, in Bangor 8:30am, training session 9 to 5 and back in London after 10pm with some 540 miles more on the old odometer.
ETL Solutions was demoing their Transformation Manager (TM) application for data transformations with generate Java code.
It turned out to be a very powerful tool both for the initial mapping between a source model and a destination model and for running the transformations.
Supported models are XML schemas (xsd), Document Type Definitions (DTD), partial XML data, Java objects, RDBMS and a multitude of flat files.
Data transformations are a two step process:
1. visually create a mapping between a source model and a destination model and let TM generate Java code to do the transformations
2. Deploy the generated code and integrate into your application with 5-6 lines of code.
The visual mapping included drag-and-dropping of elements between the source and destination. In addition, TM is using a powerful modeling language (SML) for more advanced mappings.
The tool originated from a requirement of migrating data between Oracle databases which is evident from the strong DB support. Included are operations for transaction management and batch operations for optimisation tweaking.
The tool then evolved by supporting additional data models and by the addition of various transformation functions (financial, mathematical and similar).
The only thing I was missing was the support for XSL output when converting between two XML schemas.
I find XSL to be more portable than Java classes but when asked to specify a scenario where our company would not be able to use Java classes for a transformation, I was not able to.

Mowecam: Mobile Web Camera

Visit the Mowecam support forum to ask any questions.
What is it
Mowecam is a J2ME experiment with a camera enabled mobile phone and a publicly accessible web server.
The application takes periodical snapshots from the mobile phone camera and posts them to a web server.
The latest image is then avaible for inclusion in a web site, for example a web log (blog).
The usages are the same as for a standard web camera and can include security, watching a party progress, weather, baby monitor and many more.
Mowecam enjoys the freedom of not being dependent on a computer, nor any hard wired Internet connection. If you are within GSM network reach you can start broadcasting photos from your location.
A modern Java enabled mobile phone with a camera.
The mobile phone needs to support the Mobile Media API (and being able to take snap shots which excludes SonyEricsson T610 and T630).
Mowecam has been developed and tested on SonyEricsson K750. There will be problems on other mobile phone models but many of them can be worked out if you let me know.
First of all download the application to your computer and install it as you normally do. This may be via infrared, Bluetooth or similar. Certain phones require both the jad and the jar file, others require the jar file only.
Due to tighter security in the new J2ME version, you will be asked to confirm when the application is about to take a snapshot and when it is trying to connect to the internet. Check the manual of your phone to find out how to change the permission settings for Mowecam to “ask once only” (or else it will not be able to send images without you confirming it can go online).
Go to the settings page and enter a unique key. This will later be used to identify your image when you retrieve it via a browser. An email address is often unique and I recommend to use just that. If you are worried about the email address ending up somewhere where you don’t want it (a spam data base), add a few letters or numbers to it. FYI, the unique keys are not stored anywhere, instead a hash is being used.
The other setting is URL endpoint which is where the mobile phone will post images. Use the provided URL: http://www.davidkaspar.com/mowecam/postimage.php (this is the default URL in the application). If you have your own web server you can instead upload the post image PHP script (below) to your own server and the postage images will stay there.
The refresh rate is in seconds. Please note that each image is around 5KB and will incur costs on your mobile bill unless you are on an unlimited data plan.
Use the following code to include the image in a HTML page: <img src=”http://www.davidkaspar.com/mowecam/getimage.php? email=[unique_key_here]”>. Replace [unique_key_here] with the unique key you have provided in the application settings.
This is the first version of the Mowecam and only binary code is provided (mainly due to the source code being in such a mess).
The code has been developed on Netbeans 4.1 and its excellent j2me development kit.
It is free to use and to distribute as long as this license notice is provided with the binary.
As always with free and beta software it is provide without any warranty and the developer(s) cannot be held responsible for any bad consequences of running the application.
Download latest version
Mowecam (This URL should also work for OTA, over the air, installation if you type in the URL in your XHTML capable mobile phone)
Mowecam: Post image PHP script v 1.0, released under GNU General Public License.
The application architecture is inspired by Midlog made by Rawsocket.
The application is using a hash algorithm from www.partow.net
The application is using Base64 code from kobjects.org

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

Netbeans 4.0 Beta 1 – first impressions

The potential is great but I have mixed first feelings.
Netbeans 4.1 splashThe new Netbeans is (Ant) project oriented a la Eclipse, IntelliJ and others. Point at an Ant build script, and Netbeans will try to pick out source, target and library directories. No more mounting ad hoc mounting of directories, things have to be more organised.
Refactoring has a dedicated menu option. You will be able to rename and move classes around; Netbeans will search all of the code base and reflect the changes.
Multiple build targets is something that has always been lacking. Finally Netbeans 4.0 allows you to define a build target for each source path. Build your Servlets, EJB implementations, interfaces, utilities and etc to different targets.
I know this is just a first beta (the final release is scheduled for December 2004) but there were exceptions all over the place. Possibly because I tried to open two medium to large sized existing projects. Had I started creating a small project from scratch, it would have given NB 4.0b1 a more fair chance.
The J2EE development support preview coming in October will be interesting. Additional exciting coming feature is the Profiler. I have already tried the stand-alone preview and once again it did not manage to profile two of our main projects due to exceptions 🙁
Here is a good document on how to move from Netbeans 3.6 to Netbeans 4.0.

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”

XSLT: Sum of products from multiple nodes

The XSL method sum(/foo) sums the value of all foo nodes in current context. If you, however, want to sum the product between two or more nodes the sum(/foo * /bar) is not sufficient as the product does not return a nodeset and thus sum() fails.
I found one way to sum products of multiple nodes and is to construct a temporary variable with the products, convert that variable to a nodeset and the sum all nodes in that temporary node set.
The function that converts a variable to a nodeset seems to be XSLT specific and the solution below is for Xalan since we are using it in our app. If you are using MSXML you will have to change the namespace but the name of the function is the same.

Continue reading “XSLT: Sum of products from multiple nodes”