blog.smart-java.nl
Ordina J-Technologies – Java Blog

Archief voor March, 2010




Immutable lists

Door: Pieter van der Meer, 26 March 2010

The last couple of years there is more and more talk about concurrency. One of the main issues is the access data from the various threads that you have running.

Brian Goetz has a simple statement on how to solve this:  Use immutable objects where ever possible. Although true it is not always as simple to implement your data structures immutable. especially when you are working with Collections (List/Set/Map).

Making the collection variable immutable is easy,
(more…)




JSF 2.0 ClientBehavior: First impressions

Door: Jan-Kees van Andel, 19 March 2010

In my previous article, I wrote about my first real JSF 2.0 ClientBehavior, called ValidateBeanBehavior.

While programming, I’ve experienced some issues that, in my opinion, make the ClientBehavior less usable in many cases.

Events
A ClientBehavior is attached to a component, both on the server side and on the client side. On the client side, this simply means that an event listener is attached to an HTML element. The event listener then contains the scripts generated by the ClientBehavior.

For example, the generated JavaScript of ValidateBeanBehavior looks like this in the browser.

Do you see the onclick handler on my submit button? This is the ClientBehavior at work. I’ve attached the ClientBehavior to my submit button and you can see what it looks like in the snippet above.

Looks nice, not? No, it doesn’t. You shouldn’t use onclick for validations. Why not? Because the behavior of onclick differs between browsers with regards to form submits. For example, many users use ENTER to ‘implicitly submit’ the form. Different browsers behave differently on such implicit submits, either triggering the onclick of the default submit button (where default is also undefined) or nothing at all.

The current HTML specs are also quite vague about implicit submits. It says the following:

If a form contains more than one submit button, only the activated submit button is successful.

Sounds nice, but what does “activated” mean? When clicking a button, it’s obviously the clicked button, but what to do when pressing ENTER?

Different things may happen in different browsers. For example, in my current Firefox (3.5.8), IE8 and Chrome 4.1 browsers, the default button is the first button (first is determined as the first one in the source).

But in other, mainly older browsers, no click event may be raised. Or, it may raise a click event on the wrong button (the first one after the active input or the first one, based on tab order). This makes it a very unpredictable (and thus not very useful) mechanism.

The HTML5 spec is much clearer about implicit submission and it’s behavior. But, since many users won’t use a HTML5 browser for a while, we simply need a more reliable mechanism, like form.onsubmit. We’ve written our JavaScript validations on onsubmit for years and it simply works. But the standard JSF2 components don’t support it.

Initialization
Another issue with onclick is that it doesn’t provide any window.onload/document.ready support. It simply executes some JavaScript when the button is pressed and there is no way to initialize your JavaScript using a ClientBehavior.

For example, I would have liked to initialize my validateBean JS using the ClientBehavior. This would enable me to provide input masking support.
The mechanism for this needs to be initialized though. Some keyup/-down handlers need to be attached to the form fields and this needs to be done when the page is loaded.

ClientBehavior doesn’t support this. In the ValidateBeanBehavior, I added a @ResourceDependency for my scripts. I can put my initialization logic there, but why should I use a ClientBehavior when all I want to do is loading a JS file? I don’t know.

Default RenderKit
The default RenderKit, HTML_BASIC, attaches the event handlers inline using the “on[eventName]” attribute on the HTML tag. While this is easier for JSF implementers, I generally consider inline event handlers a bad practice. I prefer attaching them in the DOM L2 style: addEventListener (or attachEvent in IE). This allows multiple event handlers and if I really don’t care about this, I still dynamically add them using element.on[eventName]. I think this gives much better markup, because of the separation of markup and scripts.

But, 3th party components may do better here…

Supported components
All components that implement ClientBehaviorHolder may have one or more ClientBehaviors attached to them. Unfortunately, on UIForm, no event named “submit” is supported. And since submit is the most widely used event on forms, this is quite annoying, making behaviors not very useful for standard forms. After all, who wants to handle the dblclick event on a form?

Third party components may of course also implement ClientBehaviorHolder and take advantage of it.

So where is ClientBehavior useful?
Simply put, all client side event handlers you’d like to attach to EditableValueHolder or UICommand components that are triggered explicitly, for example by onchange or onclick events. I can imagine something like effects can be implemented nicely with ClientBehaviors. But OTOH, most effects in real world applications aren’t used standalone, but as a part of an Ajax transaction, so I don’t see much use there either.

The concept of ClientBehaviorHolder is generic and can be applied by any component, so I hope the ICEFaces, RichFaces and Trinidad folks take advantage of this mechanism. I think interoperability between libraries will increase with this.

But maybe I’m just negative because I’d like to completely control my JavaScript.




JSF 2.0 ClientBehavior: Bean Validation in JavaScript

Door: Jan-Kees van Andel, 17 March 2010

In the following article I’m going to show you my first “real world” ClientBehavior and my first impressions from a user’s perspective.

First, some theory. JSF has support for something called “attached objects”. This has been since the very beginning, with Converters and Validators.
Since JSF 2.0, Behaviors have been added to this list. A Behavior, when attached to a component, adds client side scripts to an object. For example, one can imagine a Behavior to do an Ajax request, load some data and show it on the page. This will be a common use case for behaviors. The Expert Group understood this and came up with a specialized AjaxBehavior, which is quite similar to the Ajax4jsf <:a4jsupport /> tag. it adds Ajax functionality to the existing component, without modifying it.

This is ClientBehavior in a nutshell. There are more subtile things to know, see this article by Andy Schwartz for a more thorough explanation of the subject.

From now on, I assume at least basic ClientBehavior knowledge and of course JSF knowledge.

The ValidateBean Behavior
With Java EE 6 we got Bean Validation. And I must admit, I like it a lot. It has a nice declarative language and one ubiquitous model for defining validations for your entire system, from database (generating Bean Validation-aware DDL with JPA 2.0) to UI (the JSF 2.0 BeanValidator, which I implemented for Apache MyFaces. That’s where my enthusiasm started).

But, one validation is missing in the spec (with good reasons of course), namely client side JavaScript validations, to improve usability and decrease server load.

Especially since JavaScript validations are often skipped because of maintenance reasons (validations implemented twice) and we now have a robust platform to implement generic validations, I tried to combine the two new technologies (ClientBehavior and Bean Validation) into one generic JavaScript validator.

The ClientBehavior implementation

This class has some interesting things. First, of course the annotations. @FacesBehavior simply registers the class as a ClientBehavior under the given name, just like how Managed Beans or Converters work. The second annotation defines a @ResourceDependency. A ResourceDependency simply says: “Hey JSF, I generate markup which depends on this file. Make sure it’s available”. And JSF 2.0 responds with: “Okay, I will”.

Also, you probably noticed my ClientBehavior to only understand buttons. That’s right, you need to attach it to a button and it takes care of wiring all field validations in the form.

It also looks for a messages component. This is used later to make sure the JS error messages are positioned the same as the by JSF generated messages. UIMessages applies to the entire view, so I don’t just look in the form. A high performance implementation may choose to start searching near the form, since most messages are positioned there, but that’s way out of scope of this article.

I know, I know, this is not the most elegant piece of code, but it nicely illustrates the point. I simply aggregates as much validation metadata as possible and writes it into one big JavaScript statement. Not that optimal, but high performance implementations may choose to dynamically generate a JS file with all metadata which only needs to be referenced from the inline JS code.

If you’d like to know how to obtain the ConstraintDescriptors (the four method calls in the above snippet), just look for the BeanValidator in the Apache MyFaces SVN. I reused the same code here.

The JavaScript
The JavaScript shown below is part of the static scripts that belong to the ValidateBeanBehavior. It contains the JavaScript code to execute the rules, as passed from the server and, if needed, show the validation errors.

It’s a lot of code, which, in essence, validates all input fields in the given form, according to the given validation rules and shows the user an error if needed. This error is positioned at the same spot as where the UIMessages would have been rendered in case of a server side error. This is a best guess though, because when the messages are not rendered (i.e. on the initial request), there is no marker in the page that I can use for positioning. A more sophisticated implementation could enrich all UIMessages in the page to always write some marker “div” with an ID to the client.

I’m going to skip the rest of the JavaScript. It’s just a bunch of validations and utilities, like utilities to convert Strings to and from Date Objects, based on a SimpleDateFormat pattern. This pattern is part of the generated JavaScript and is obtained by looking at the attached Converters.

Usage in a Facelet
To make the ClientBehavior a bit easier to use, here’s a Facelets taglib which defines a tag for the ClientBehavior (don’t forget to configure the taglib in web.xml or put it in the /META-INF of a JAR).

With the taglib in place, we can use the ClientBehavior, like this:

That’s not too much effort for a client side form validation right? And, these validations are always in-sync with the server side validations.

After a bit of cleanup, I’ll commit the code into the Apache MyFaces Sandbox, so you can download it from there when I’m done. :)




How to de-frameset a Web App with Apache Tiles 2

Door: Assen Kolov, 16 March 2010

The problem

There’s is a good old application from the days when struts still had to be invented and framesets weren’t considered evil. The problems associated with a FRAMESET are another topic, the fact is the application owner wants to get rid of them and asked me to look for a solution that would be unobtrusive and easy to implement, understand and maintain.

Current Situation

The application uses no web-app framework, each Use Case is implemented in a separate servlet, all of them neatly mapped in the web.xml. The FRAMESET setup is classic: apart from the static elements, the navigation happens in a ‘body’ and a ‘menu’ frame. The normal flow is to select a command from the menu frame, e.g. Place Order results in (<a href=”/placeorder” target=”‘body”/>), then submit a few forms in the body frame (<form action=”/placeorder” method=”POST”>…</form>). Without frameset, when a HTTP request for /placeorder reaches the application, we want the servlet response decorated with the other fragments: menu, header and the rest. The differences are essential: there is just one request/response and all page fragments have to share the same HEAD, CSS etc.

Introducing Apache Tiles 2

The good news is that version 2.x of Apache Tiles, which has started as struts extension, is now framework-independent. It offers support for JSP, Freemarker, and can be used directly from a servlet or filter. First of all, a template is needed to replace the frameset, e.g. main.jsp:

Based on that template a tile definition can render a decorated view of any servlet output (e.g. /placeorder). A definition per servlet is needed in tiles.xml:

This definition still has to be rendered, e.g. from another JSP, let’s call it placeholder_tiled.jsp:

A separate tile definition and a JSP page for each servlet would be too much code repetition. Let’s see how to the output of any servlet.

A View decorating servlet

I like the idea of having separate URLs for the servlet output and for a composite view of the same output. Thanks to Tiles 2 API, one servlet could provide decorated views of the output of all servlets. In tiles.xml, I added a tile definition with all attributes except body defined:

Let’s define a servlet that will fill in the missing body attribute for each URL ending with .tiled:

Finally, the servlet itself:

This servlet always renders the same tiles definition, providing an appropriate body. For example, a request to /showOrder.tiled?orderId=100 would render the output of /showOrder?orderId=100 as the body tile in the tiles definition. No separate tiles definition and JSP for each view are needed.

What’s next?

All the code above only provides an easy template-decorated view for each servlet output. There is sill a lot of work that has to be done manually:
- move all separate styles, scripts etc. from the separate pages to the template
- requestDispacher.forward in a servlet closes the output stream while it is still needed for the tiles template; all forwards must become includes;
- all navigation javascript referring to top.menu ot top.body has to be refatored manually.




Unit Testing a Bean Validation ConstraintValidator

Door: Jan-Kees van Andel, 12 March 2010

I’ve been playing a bit with Bean Validation and thought I found an issue: Unit testing a ConstraintValidator. Specifically, parametrized ConstraintValidators.

First, what’s a parametrized ConstraintValidator? Simple, a Validator that takes a parameter to do its job. A simple example is a length validator that takes the minimum and maximum length as parameters and validates if the value is between those two.

Parametrized ConstraintValidators are everywhere, even Bean Validation itself contains them. For example: @Min(length) and @Max(length), but also normal ConstraintValidators, like @NotNull where you can customize the error message. However, this error message parameter is not very interesting with regards to unit testing individual ConstraintValidators, because the message is generated by the Bean Validation framework.

For example, consider this ConstraintValidator, incl. corresponding annotation:

In the future, Bean Validation may become the core mechanism for ensuring correctness in your system. For example, JPA 2.0 leverages Bean Validation annotations to generate additional DDL statements and JSF 2.0 automatically uses Bean Validation when it’s available. Note: JSF 2.0 uses a new concept, called “default validators” to implement this. A default validator is invoked on every input component on a postback.

But, how do we test this stuff? After all, you can’t instantiate an annotation.

I currently have 4 options:

Using a declared annotation
The first attempt is shown below. Here, I simply declare the annotation in my test case on a dummy instance field (an annotation doesn’t live on its own) and look it up using reflection. This way, Java takes care of instantiating and initializing the annotation.

I personally quite like this approach. The test data is inside the test case. Unfortunately not in the test method, that would be better, but since you can’t put annotations everywhere in your code, it’s not easy to implement this decently.

So let’s look at the next one…

Custom annotation implementation
Since Java annotations are just a special case of interfaces, they should be fairly straightforward to implement. However, for some reason, I didn’t know this until recently. But it’s actually not different from any other interface implementation. See for yourself.

Nothing special, right? But I don’t really like it. I could have also written it inline, but I don’t like that either:

I think the above one looks like garbage. So this is also a no-go.

Dynamic proxies
Java itself uses dynamic proxies at runtime to instantiate annotations. So why not also use a Proxy to mock the annotation? See for yourself.

However inline, the implementation looks very clumsy. Unfortunately this is probably as simple as it can get, since you DO need to define the inner class.

And it will become even worse when there are multiple parameters on the bean, since you need to check which method is invoked. This will make the implementation even worse.

Mocking using Mockito
But, creating and configuring proxies, isn’t this what mocking libraries do? Exactly, let’s try.

This looks pretty nice. And it scales well with multiple attributes.

I only doubt it will be the nicest solution when the annotations become more complex. I really don’t like annotations that contain annotation parameters. Or even worse, arrays of annotation parameters. But reality is, they exist. And if they exist, they also need to be tested. But, OTOH, people who nest annotations probably don’t mind unreadable unit tests. ;)




Hibernate, lazy loading and inheritance

Door: gnoij, 8 March 2010

A common problem with typecasting a lazy loaded entity to its child is a ClassCastException. This exception occurs because the dynamic created proxy implements the baseclass and has no knowledge about its subclasses.

Suppose we have a class B which extends A and a class C which has class A as a member as shown below.

The following test will fail with a ClassCastException on the last line.

The methods save(), clearSession() and retrieve() are just helper methods which implement the Hibernate session methods save(), clear() and get().

A search on the Internet shows a couple of solutions for this problem.

  1. Using interfaces as a proxy in the hibernate mappings. This will result in accessing the object through its interface only so all methods must be exposed in the interface. I don’t want to expose every public or protected method in the interface which are not intended for use by external parties.
  2. Using the Visitor Pattern to access the correct childclass. This means that users of these objects must write a lot of code just to use some getters. I don’t want to burden someone else with a local Hibernate problem.
  3. Using ((HibernateProxy)object).getHibernateLazyInitializer().getImplementation() whenever a typecast of an object to its child class is needed.

All of the solutions mentioned above are not suitable for me so I decided on another solution which is a variant of solution 3.

With a slight modification of the method getA() in class C, exposing the HibernateProxy is avoided.

Now the test completes without failure.

This has to be done for every getter which can return a lazy loaded proxy.

And if you (like me) don’t want Hibernate code in your domain model, you can move this code to the persistence layer and use dependency injection to use it.

It’s still not an elegant solution (IMHO there isn’t one), but its the best usable for me.