Thursday, 30 January 2014

PrimeFaces JBoss forge plugin updated

With the announcement of the new CR release of JBoss Forge 2 (now final release), I remembered that once upon a time (already 2 years ago) I wrote a plugin for PrimeFaces for this tool.
Since then, a lot happened and that version of the plugin doesn’t support PrimeFaces 4. Although it isn’t a big problem, you can manually update the version number of the artifact to 4 in the pom.xml file, I decided to spent some time again on the plugin.
Mainly because the Forge 2 version uses a different concept and now you have the notion of addons. So a rework will be needed to keep the functionality in the new release of JBoss forge.

PrimeFaces 4

The new version of the plugin supports PrimeFaces 4 directly and you can use it to configure the Client Side Validation feature of PrimeFaces.

What are the commands that you need to specify within JBoss Forge?
forge install-plugin primefaces

This command will install the PrimeFaces plugin and is only required the one time.

new-project --named demo --topLevelPackage be.rubus.forge.demo --type war

This command will create a new maven project with packaging type war.  You can choose of course the value for the –topLevelPackage attribute. The command will also ask some questions like the location where the project must be created.

faces setup

This command will add the required maven dependencies for using JavaServer Faces development.  And it will add also some resource files like web.xml, faces-config.xml and beans.xml if you want CDI (this is a question of the command)

primefaces setup

Now the PrimeFaces dependency is added to the project. The version depends on selection you made and you are ready to go with your favourite IDE.

Additional goodies

The plugin also has some additional commands which can be handy
primefaces install-example-facelet

This adds a JSF view file (index.xhtml) which uses templating and contains a Hello World type example of using PrimeFaces.  This is handy is you are not familiar with PrimeFaces and shows you how to add the PrimeFaces namespace.  It is also an example of using the JSF 2.x template feature.

primefaces set-theme

If you execute this command, you see the list of available free themes for PrimeFaces.  It adds the required maven artifact and configures the theme in the web.xml file.

primefaces install-CSV

This is a PrimeFaces 4 specific command which configures the Client Side Validation feature in the web.xml file. See the PrimeFaces users guide how you can use this feature.

JBoss Forge 2

For the new release of the tool, the plugin will be adapted and a short guide will be posted when the addon is available. But enjoy version 1.1 of the PrimeFaces plugin from today on.

Sunday, 5 January 2014

Client Side Validation example of PrimeFaces


With the latest version of PrimeFaces, version 4, you have the possibility to perform some validations on the client, by the browser.
This features doesn’t replace the standard JSF validation on the server side but is an addition to it.  The server side validation makes sure that any data posted to the server is valid before it is processed any further. The client side validation is there to inform user faster of data problems.
By default, all the standard validations like required fields, minimum and maximum values, string lengths and so on are available.  But you can also create the JavaScript version of your custom JSF validation.
The feature is very good explained in the PrimeFaces users guide. This posts describes the steps that I have done to make a Visa card validation on the client side.


In order to activate the feature, you need to put the following content parameter in the web.xml file.

Now, your application is ready to use the client side validation feature. And whenever you want to make use of it, you just have to specify the attribute validateClient on the commandButton tag for example.

The standard validations known by PrimeFaces are then performed on the fields in the form.  Any validation error is shown by the messages or growl tag which is also available in the form.

Make sure you read the PrimeFaces users guide to know all the requirements and usages.  The most import ones are

  • Put a messages or growl tag within the form. others are not yet discovered. 
  • Severity attribute of these tags is ignored.
  • Invalid fields are marked by a red border but associated label isn’t colored

These shortcomings will be removed in the next release of the framework.

Custom validation

It is also possible to have a client side validation variant of your custom validations.  Therefor I created an example, a visa card number validation.

You start by creating a standard JSF validator, so a class that implements Validator interface.  For the Client Side Validation feature of PrimeFaces, you have to implement also the org.primefaces.validate.ClientValidator interface.

It contains 2 methods, getValidatorId which defines the name of the JavaScript function that implements the validation on the client side. If the JavaScript function needs some values defined by the validator (like the minimum value for the range validation) you have to return it by the getMetadata method.

This is the java side of the solution
public class VisaCardValidator implements Validator, ClientValidator {
    public Map<String, Object> getMetadata() {
       return null;  // No metadata required on client side

    public String getValidatorId() {
        return "custom.VisaCardCheck";

    public void validate(FacesContext someFacesContext, UIComponent someUIComponent, Object o) throws
            ValidatorException {

The JavaScript must be available on the page where we like to use it, the code is shown below.
PrimeFaces.validator['custom.VisaCardCheck'] = {
    reverse: function (s) {
        var o = '';
        for (var i = s.length - 1; i >= 0; i--)
            o += s[i];
        return o;
    throwError: function(detail) {
        throw {
            summary: 'Validation Error',
            detail: detail
    validate: function (element, value) {
        var reg = /^\d+$/,
            digits = this.reverse(value).substring(1).split(""),
            sum = 0;
        if (!value.match(reg)) {
            this.throwError("Not all digits");
        if (value.length < 13 || value.length > 16) {
            this.throwError("Length invalid");
        if (value.charAt(0) != '4') {
            this.throwError("Wrong start digit");
        for (var i = 0; i < digits.length; i++) {
            if (i%2 == 0) {
                digits[i] = digits[i] * 2;
                if (digits[i] > 9) {
                    digits[i] = digits[i] - 9
            sum += parseInt(digits[i]);
        if (value.charAt(value.length - 1) != (sum % 10)) {
            this.throwError("Check digit validation fails");

The important thing here is that the name of the validator in the JavaScript object, custom.VisaCardCheck in my case, is the same as the value returned by the getValidatorId method of the JSF validator.

Usage of the validator at the JSF level is the same as usual.
<p:inputText id="myValue" value="#{dataBean.myValue}" required="true" validator="custom.VisaCardCheck" />


With the Client Side Validation framework, we can inform the user faster about issues with data, without the need to go to the server.

The best thing is that it integrates very well with JSF and it is hard to tell if the message came from the client side validation or from the server side.

The default validations are already available in their javaScript counterpart, also if you use BeanValidation. When you create a custom validation, you have to write the JavaScript yourself, of course.

Sunday, 10 November 2013

GenericMessage for DeltaSpike supporting JSF and REST


In the post of January 2013, I described the feature of DeltaSpike to have type safe messages from within a CDI bean which are displayed within the <h:messages> tag of JSF.
It is a great feature which has a minor drawback, especially in the perspective of Java EE as a universal backend system. (see this post for the idea behind this)
In the case a CDI bean, like a service type of bean, is used in the context of JSF and REST contexts, because you have multiple types of clients, there is an issue with JsfMessage of DeltaSpike.

Custom version

Since DeltaSpike is an open source project, you can easily find out how the feature is coded. And you can create something similar which isn’t tied to JSF quit easy as you can see in this post.
First we need to define the alternative for the JsfMessage interface, lets call it BusinessMessage.
public interface BusinessMessage<T> {

    T failing();

    T warning();

    T information();

We have 3 methods, so that we can define an error, warning and information message. 

The usage of this interface will be identical to the JsfMessage one of DeltaSpike.  Se we need to define an interface which will be annotated as MessageBundle and we are ready to use it.
public interface ApplicationMessages {

    @MessageTemplate(value = "Person already registered")
    String personAlreadyRegistered();

public class AttendeeService {

    private BusinessMessage<ApplicationMessages> message;

    public void addPerson(Person person) {

Within the implementation of the BusinessMessage interface we will make, we can now make sure it will work within a JSF and REST context.

BusinessMessage implementation details

I’m not going to describe all the implementation details in this post.  In a few weeks, the code of a demo application will be made available that highlights almost all of the things that kept me busy the last year. And it is using the BusinessMessage described here.

The code is using the org.apache.deltaspike.core.impl.message.MessageBundleInvocationHandler class of DeltaSpike to have a dynamic implementation of the @MessageBundle annotated interfaces like ApplicationMessages we have in the above example block.

Once we have the message text the user wants, we will store it in a Thread local variable, maintained by a new class BusinessMessageContext.  This class makes it possible to keep some messages independent of the view technology used. So it is supporting JSF and REST style of working.

Show the messages

The last step to solve our issue is that we need use the messages stored in the BusinessMessageContext and send it to the correct view.

For JSF we can create a PhaseListener implementation which is triggered before each Render Response phase.  It can add the messages to the JSF system using the facesContext.addMessage method.

For REST, we can use a concept explained in this post, to send the messages to the client as a JSON response. Some of the aspects will be described in more detail in a future post on that blog.

In both cases, we need to do the clean up of the Thread local variable we have used to store the messages to reclaim the memory.  Therefor the class BusinessMessageContext has a method release() to perform this clean up.


JsfMessage of DeltaSpike is a great feature to have type safe messages. But in some cases your CDI bean will be used in multiple ‘environments’, JSF and REST for example. In that case, we need an alternative which works almost the same but stores the messages, at least initially, in a view neutral way.

Code will be available as part of the demo which will be released in a few weeks.

Tuesday, 8 October 2013

How to debug javascript in PrimeFaces 4.0


With each new release of PrimeFaces, the JavaScript becomes more and more important in the framework.
This is no surprise as JavaScript is needed to give the end user a rich user interface. And in the latest release there is quit a lot of new JavaScript code added for the client Side validation framework.
But if you want to debug it in the browser, you see that the code is minified. And thus stepping through it line by line is not possible.
This post describes how you can do it.

Build custom version

The source code of PrimeFaces contains the human readable code and the idea is that we build a custom jar file which contains that readable version of the JavaScript.
As the code is open source, it is available on Google code. We can do a checkout with following command.
svn checkout

Now we go to the pom.xml file and make some small changes.
The most important one is the change of the version tag.  I have changed it to 4.0-DEBUG (you can find it at the top of the pom.xml file)
PrimeFaces uses a maven plugin to generate the JSF components and configuration files. 
This plugin is located in the PrimeFaces maven repository which you must include into the pom file. Otherwise the build will fail.
When you now execute the mvn install command, you will have a customized version of PrimeFaces in your local Maven repository which contains the non minified version of JavaScript.

Using this version in your project, by specifying it in a profile so that it doesn’t go into production, you can do debugging in your favourite browser.


We following the above steps, you have a custom version of PrimeFaces where the JavaScript is not minified and thus can be debugged in the browser. Of course it is not suited to go to production with this version.

Wednesday, 25 September 2013

Generic JPA 2.1 converter for enum


Until now, an enum value could be stored in the database by its ordinal number or his name in JPA. When you have a ‘legacy’ database or when you are doing refactorings you could be in trouble.  The only option then was to rely on the implementation to allow a custom value as the representation of the numeration in the database.
In the latest release of JPA, 2.1, there is support for custom converters so you can solve these kind of issues.

JPA 2 Converter

What do you need to do to have a custom converter? The enumeration class doesn’t need any change. In the entity were you use the enum, you need to specify the converter you like to use, like this:
public class Person {

  @Convert(converter = GenderEnumConverter.class)
  private Gender gender;

The converter class can look as this
public class GenderEnumConverter implements AttributeConverter< Gender, String> {

  public String convertToDatabaseColumn(Gender attribute) {
    String result = "";
    switch (attribute) {

      case MALE:
        result = "M";
      case FEMALE:
        result = "F";
    return result;

  public Gender convertToEntityAttribute(String dbData) {
    Gender result = null;
    switch (dbData) {
      case "M":
        result = Gender.MALE;
      case "F":
        result = Gender.FEMALE;
    return result;

And the last thing you need to do is to ‘register’ the converter with JPA as no scanning is performed of the available classes.  You can specify the class name, just as you specify the entity classes in the persistence.xml file.
<persistence-unit name="converter-unit" >
  <description>Forge Persistence Unit</description>


Not OO

The above code is not ideal in several ways. If you have an enum class with a lot of values, you have to write a large if-then-else structure which is not very OO like. And you also need to write a lot of similar code which wants me to search for a more generic solution.

If we could define the database value together with the enum value, it would be a great improvement. It makes the code also much more logic as you can define the database value together with the enum value.

Since we need such functionality for each numeration that we use in the persistent objects, we can create an interface like DatabaseEnum.
public interface DatabaseEnum {

  Serializable getDatabaseValue();


And change the enum to implement this interface.
public enum Gender implements DatabaseEnum  {
  MALE("M"), FEMALE("F");

  private Serializable databaseValue;

  Gender(Serializable databaseValue) {
    this.databaseValue = databaseValue;

  public Serializable getDatabaseValue() {
    return databaseValue;


This should allow us to create a generic converter for the enums, except that the Java compiler removes the information regarding the generic types, know as type erasure. Otherwise a converter like this could be possible.
public class EnumConverter<T extends DatabaseEnum> implements AttributeConverter< T, Serializable> {

  public Serializable convertToDatabaseColumn(T attribute) {
    return attribute.getDatabaseValue();

  public T convertToEntityAttribute(Serializable dbData) {
    // There is no way we can create such a method
    return determineEnum(T, dbData);


If we would be able to define that a custom constructor needs to be called, where we supply as parameter the class T, we would get away with it.  But this is not the case.
public EnumConverter(Class<T> enumType) {..}

Almost generic converter

Based on the optimal code above, we are able to create a converter that uses a generic utility method.  It means that we still need to create a converter for each enum class we like to use, but the code is much cleaner then the first example we show in the text.
public class GenderEnumConverter implements AttributeConverter<DatabaseEnum, Serializable> {

  public Serializable convertToDatabaseColumn(DatabaseEnum attribute) {
    return attribute.getDatabaseValue();

  public Gender convertToEntityAttribute(Serializable dbData) {
    return DatabaseEnumUtil.getEnumValue(Gender.class, dbData);

And the utility method can be small and generic thanks to the not very known method getEnumConstants() of the JVM core classes.
  public static <T extends DatabaseEnum> T getEnumValue(Class<T> enumClass, Serializable dbValue) {
    T result = null;
    if (dbValue != null) {

      for (DatabaseEnum enumInstance : enumClass.getEnumConstants()) {
        if (dbValue.equals(enumInstance.getDatabaseValue())) {
          result = (T) enumInstance;
    return result;


In the latest version of JPA, a custom converter can be defined which can be very handy in a lot of situations.  You can use it to create a converter for Joda-time classes or for specifying the database value of an enum value.

The only thing that keeps us from creating a generic converter for enums is the type erasure thing of Java. Otherwise we could create a beautiful converter for all our enums.

Monday, 5 August 2013

From CODI to DeltaSpike


CODI is my favourite CDI extension framework where you can find all kind of goodies when you are working in a CDI environment.
Some time ago, there was a decision to create a new CDI extension framework which brings together all the good features of CODI and Seam 3 and other features from other CDI extension libraries.

They have gone through the incubation process at Apache and moving along steadily. The question is, can you already switch from CODI to DeltaSpike for an application?

Not all features of CODI are implemented but my 2 favourites ones are
- The additional scopes like ViewAccessScope
- The fluent API for adding FacesMessages.
So can we create a DeltaSpike application with these 2 features.


In the current version of the DeltaSpike framework, version 0.4, there is no support for something like the CODI's ViewAccessScope .
Therefor, Gerhard Petracek created an extension for DeltaSpike to have the missing scopes from CODI version 1.0.5 into DeltaSpike. See here.
So adding the required dependency to the POM

  <name>Gerhard personal repository</name>


The version of the extension is a concatenation of the 2 libraries it will bridge. So we have the structure  &CODI version&_&DS version&_&extension version&.

You only have to use the new package name to have the additional CODI scopes.  The API is identical so that existing code which works for CODI, will also work with DeltaSpike.

So for example for ViewAccessScope,

import org.apache.myfaces.extensions.cdi.core.api.scope.conversation.ViewAccessScoped;

import org.os890.cdi.ext.scope.api.scope.conversation.ViewAccessScoped;
So for any of the scope packages, you have to replace org.apache.myfaces.extensions.cdi.core with org.os890.cdi.ext.scope.


The support for a fluent messaging API is already present in DeltaSpike. So to have this kind of functionality, we don't need to use an extension as we did for having the scopes.

But here we have the issue that the API is changed and thus we need to adapt existing code.

CODI version


DeltaSpike version

Message defitions.
public interface AppMessages {
    String buttonClicked();

Within CDI bean
    private JsfMessage jsfMessage;

    public void addTestMsg(ActionEvent actionEvent) {


 The DeltaSpike application was tested successful on Glassfish and JBoss as 7.1.1.Final.

Also the original CODI version was running without a problem on the new Glassfish 4 version.

On this server, the DeltaSpike version had a problem.  There was an exception thrown in the extension as there is no problem with the DeltaSpike code itself. All the integrations tests of DeltaSpike are running also on a Weld 2 version (used in the Glassfish 4) so you can expect that it is working on it without any problem.

With the new WLS 12C server, version 12.1.2, there is also an issue running the DeltaSpike application.   The application deployment fails during validation where it can't inject an Extension class into another bean.


With the help of the DeltaSpike extension, you can create already applications that uses a lot of the features of the CODI framework.
So check what features you need and maybe you can already create your application with the DeltaSpike framework.

Friday, 7 June 2013

JSF 2.2 Pass-through attributes


Until now, you could only use attributes on the JSF tags which where recognized by the component library.
Until recently, this made sense.  Those attributes are used to ‘configure’ the JSF tag and thus other attributes have no meaning for the component and thus not needed.
But that changed with the HTML 5 specification. One of the additions is that you can define and use your own attributes which can be used by for instance by your javascript code.
Now you no longer need to use class names to store metadata and thus your html code becomes cleaner.

JSF support

But this nice feature of HTML5 is a problem for the JSF framework. Since we have no way of specifying that additional parameters needs to be passed to the generated markup, there was no easy way of supporting them.
Of course you could define them with the <f:attribute> tag and write extensions for the renderers, but native support is of course needed.
And with the new JSF 2.2 specification, there is the possibility to support them.  The feature is called pass-through attributes. And technically that is also what is happening.  Those attributes are just passed to the generated markup.

Example, input placeholder

Now we can specify the hint for an input with the placeholder attribute without the need of the component library to support it (of course, our browser need to support the HTML 5 attribute)
<html xmlns=""
        <h:inputText id="basic" value="#{bean.value}" p:placeholder="Enter text"/>

By marking attributes as belonging to the newly introduced namespace, we tell the renderers that they need to copy it to the markup.  Besides the support for literal values (like in the example above) EL expression are also allowed.

As you can see, they have also changed the namespace to instead of to emphasis that the specs are a community process and not originating from a single company (or was it just to remove the name sun?).

Multiple attributes

If you have several pass-though attributes that you need to specify, there is another way of specifying them.

The core namespace (xmlns:f="") has an additional tag now, called passThroughAttributes. It has a reference to a Map that contains all the attributes that needs to be added. The key of the map must be of String type, the value is an object or EL expression.
<f:passThroughAttributes value=”#{service.nameValuePairs}” />

You no longer need to specify them one by one, but the drawback of it, if you ask me, is that those view related metadata is specified in Java code and not in the JSF view.

Support in component libraries

For those that are writing component libraries them self (or a few components), it is easy to support those pass-through attributes on your component as well.

On the UIComponent class, they have introduced a new method getPassThroughAttributes(boolean) that you can use to retrieve the discovered attributes.

It returns the info as a Map and you can iterate over this collection and write the information on the response stream.

As this approach is generic, you can put the code in a utility class/method and call it for every component you like to have support for the pass-through components.


With the new pass-through feature of the JSF 2.2 spec, it becomes easy to support the HTML5 data attributes.  It is as simple as specifying the attributes on the JSF tag prefixed with an alias for a specific namespace to identify them as pass-through.

Also the code to support the in your custom widgets is less then 10 lines long.

The only issue you could have is that for some JSF components, it is not always immediately clear where the pass-through attributes are placed in the HTML markup when the tag generates multiple JSF elements.