Sunday, 21 September 2014

Input in uppercase with JSF inputText, a TagHandler example


Recently there was a requirement from a client to be able to input data all in uppercase within a JSF web application.

When you write a simple JSF converter and add a CSS style class to the component to uppercase all input client side, you’re done. You can find various posts on the internet where this solution is described.

This blog shows how you can improve the solution.  You can create a JSF tagHandler which allows you to combine the adding of the converter and CSS style class, by defining your custom tag.
It is convenient and typesafe.  Typesafe Because it is a tag, so you have IDE autocompletion.  Within the name of the converter and the CSS style class name, you can make some typos which leads to an incorrect behaviour.


What is a JSF TagHandler? The tagHandler is some piece of code executed when JSF encounters your custom tag that you have placed in the xhtml page.  This code runs during the creation of the JSF component tree and thus ideal to tweak some components as we like to do for the uppercase scenario.

Your tagHandler should extend from the javax.faces.view.facelets.TagHandler JSF class.  And all your work should go into the apply method.  This method is called in response to the identification of your custom tag in the xhtml file.

This method has a UIComponent typed parameter representing the parent component your custom tag belongs to.  So adding a converter and style class to your inputText component is very straightforward:

public class UppercaseHandler extends TagHandler { 
    public UppercaseHandler(TagConfig config) { 
    public void apply(FaceletContext ctx, UIComponent parent) throws IOException { 
        if (parent instanceof HtmlInputText) { 
            HtmlInputText inputText = (HtmlInputText) parent; 
            inputText.setConverter(new UppercaseConverter()); 
            String styleClass = inputText.getStyleClass(); 
            if (styleClass == null) { 
                styleClass = ""; 
            if (!styleClass.contains("uppercase")) { 
                inputText.setStyleClass(styleClass + " uppercase"); 


The next step we have to do, is define the name of our custom tag and link the tagHandler class to it. This is done in the Facelets configuration file. Here you can define your new tag name and the tagHandler class name which is associated with it.

<facelet-taglib xmlns="" 

In other scenarios, you can assign tags to converters, custom defined components or user defined EL functions.


In the Facelets Configuration file, we have defined a namespace( in the example above)  This namespace we can be used in the xhtml file and our custom tag can be used. An example could be.

<?xml version='1.0' encoding='UTF-8' ?> 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" ""> 
<html xmlns="" 
    <h:form id="mainForm"> 
        <h:inputText id="field" value="#{someBean.value}"> 


The JSF TagHandler is a very convenient way of assigning a tag name to some custom functionality you have created.  Better because it is ‘typesafe’ and thus you get warned when you should make a typo.
In the example above, you saw how you can assign in a few lines a custom converter and CSS style class to a JSF inputText component.

Sunday, 6 July 2014

Mavenize your Custom PrimeFaces Theme


PrimeFaces relies on the ThemeRoller themes for the look of the components.  There are more then 35 already available. But it is also possible to create your own custom ones.  This blog not only describes the creation of such a new theme, which is already quit good documented, but also how you can wrap it in a maven project and add some further customisations.

Create custom theme

ThemeRoller has an online visual tool to design your custom theme.  You can specify Font and colour for various types of content like header, highlights, buttons and so on.

Once you are more or less comfortable with how the examples on the site looks, you are ready to download the theme.
On the download page, it is very important to exclude all the components, you only need the skinning style. You have a convenient ‘toggle all’ checkbox to remove all the components. Also the 1.11 version of jQuery is NOT supported, so take one of the other 2 versions noted on the page.

This zip needs a few modifications before it can be used as custom theme for PrimeFaces. Luckily this is automated and can be done on this page. 

Here you can specify the custom name for your theme and after you upload the zip to the site, you are able to get a jar file which can be used directly in your application.


Most of the time you want to perform some modifications on the theme. Some of the modifications I made recently are described further on.
So it can be very convenient to turn the jar file into a maven project where the maven package goal generates a valid PrimeFaces Theme.
This is very easy to accomplish.

Just create a minimal POM file, you just need the groupId, artifactId and version info, nothing else, and extract the contents of the  jar into the src/main/resources directory.

The directory structure should look like the image above. The contents of the downloaded jar file is extracted in the resources directory as indicated in the image.

From now on, you can generate the PrimeFaces theme with a simple mvm clean package command.


In this section, I want to share you a few of the customisations I made in my recent project.


One of the common questions on the PrimeFaces forum is how you can change the size of the text within PrimeFaces Components.  This can be done by specifying a value for the .ui-widget, .ui-widget .ui-widget  CSS selector.

Instead of putting it into the css file of your application, you can also put this value in the theme and use it in all your applications.

Put the same font information also in the body selector as some components of your application are not from PrimeFaces (for example the h:outputText) and should look the same.

Table record selection

If you look closely to a selected record in a data table component, you see that the upper border isn’t highlighted like the 3 other borders. (look at the showcase with a theme like Blitzer, there you can see it easily).

You can ‘fix’ this in your theme CSS, look for the ui-state-highlight selector.

.ui-state-highlight, .ui-widget-content .ui-state-highlight, .ui-widget-header .ui-state-highlight {
   border: 1px double "yourColor"

Replace the solid with double and you wil see that all 4 borders are identical now.

Other then these 2 customisations, you can put anything you need in that theme file. Examples are
- A different colour for the cancel type of buttons
- A different colour for the default button
- Error indication on a field with a validation error
and so on.


Creating a custom PrimeFaces theme can be done quite easily.  Starting from the ThemeRoller visual designer, you can convert it to a maven project which allows you to customise the theme even further.

Monday, 2 June 2014

Deploy Java EE in the cloud with JBoss OpenShift


In the previous blog post I described how you could create Web Applications using JSF and CDI that are running in the cloud with Google App Engine.
Using a database is also possible but is not available for free on AppEngine and that was the reason I didn’t go into detail about it.
But there exists another possibility to host your Java EE application in the cloud, and it has even more possibilities and is much easier, OpenShift of JBoss.
And best of all, you can run them for free if your requirements are not too high. 

What is it?

OpenShift is a so-called PaaS, platform as a service.  So it is not only limited to a server that you can use or a program, like a web server that is available, it is the complete stack. 
With OpenShift you can use for example a WildFly application server and a database instance to deliver you an environment for the execution of your web application. It has also a unique way of deploying you app using a GIT repository.
In this text I’ll describe the Java EE solution that you can use, but there exists also other possibilities like PHP, Tomcat with Spring, Continuous integration server, and many others.  Have a look on their site about the supported environments.

Creating an application

You first start by creating a domain.  The domain will hold one or more of your applications.  The domain name is also reflected in the URL. The structure is as follows
You can assign it an alias if you supply this URL to your DNS provider.

Creating a domain is nothing spectacular, you just have to specify the name for it.

Once you have the domain, you can create the web application in it.
And the first thing you have to do when you create an application is to specify which type of application you want.

In my case, I want to have a Java EE environment in the cloud, so I took the WildFly 8 possibility.  As said there are a lot of possibilities and maybe one that I want to mention here also is CapeDwarf. It implements fully the Google AppEngine API’s so that you can migrate easily from Google to the JBoss cloud.

In the next step you have to give some configuration options, like the application name, as said part of the URL, and if you want to have scaling and thus a load balancer for your application.

The creation of the application takes some time, as it is preparing a machine for you with all the software you need.
But when it is finished, you can already go the to URL and see the welcome page of your application, which you want to customise of course.

The overview page also gives some very important information that you need to be able to deploy and use the application.
In the case of WildFly, it gives the username and password you need to be able to log on in the console of the application server. 
It also states the GIT URL that you can use to clone the source of the application locally and start developing your application.
More on those later. 


Since my test application needs some database to store information, I can create it also on the OpenShift platform.

The idea is that you can add additional ‘cartridges’ that have certain functionality and allows you to create the ideal server for your application.
A database is the most common cartridge, but there exists also others like for example a cartridge to execute some scheduled jobs (CRON like)

Regarding the databases, you can choose between MySQL and PostGreSQL but you have also the possibility of using MongoDB.
Configuration is not needed, you add the cartridge and you receive the URL, username and password for the database to access it.
In case of MySQL, the access is through phpMyAdmin that needs to be added if you want console access directly to your database. 

Web application

I talked a lot about setting everything up, because creating your web application is very easy.
If you clone the GIT repository that was indicated on the site, you see that it is maven based. So any maven based Java EE application can be used.
No special configuration needed, no adjustments like with AppEngine. If it runs on your machine, it runs on OpenShift.

Database access

The only thing that took a little bit of research was the URL to my MySQL database that was created.

I found this knowledge base article,  where it is clearly described.

You first have to create a datasource for WildFly in the configuration files.  You can find the standalone.xml file in the .openshift/config/ directory when you have checkout the GIT repository.
You have to leave the placeholders, like ${env.OPENSHIFT_MYSQL_DB_HOST} in the configuration file so that it can properly be resolved at deployment time.

Once you have defined it there, you can define the datasource in your persistence XML file and the application is able to connect to it. 


When you push the changes to the remote GIT repository, a lot of things are happening.
First your application and WildFly server are stopped.  Then it is running the mvn package on your new code. And then the server is started again with your new version of the application deployed.  So it can take a minute or more before your push ends due to these tasks.

Client tool

Besides the option to push the code, you also have the RHC client tools. It is a ruby based tool that allows you to connect to your server. You can perform various operations which this tool which are also possible online.
These include things like
Getting started, like creating domain, applications and adding cartridges.
Working with your app as looking at your log, port forwarding so that you can open the WildFly console from your browser, etc
Account management like setting up ssh connections, authorisation, key generation etc..


OpenShift can be used free of charge.  They work with the concept of gears. Each feature uses one or more gears, categorised in small, medium and large size. 
A WildFly instance takes only 1 small gear and you get 1 GB of space with it. The space calculation takes into account the code and log size and also the database size.
So the database isn’t taking up any additional gear, a load balancer counts also for 1 small gear.
Since you have 3 small gears for free, you can run up to 3 applications with a database on their platform.


With OpenShift it becomes very easily to deploy your Java EE application in the cloud. JBoss made it possible to use a Maven based application that runs on WildFly to deploy it on their cloud infrastructure. No changes needed, only some slight modification for the datasource to access your database also hosted on their PaaS.

Thursday, 24 April 2014

PrimeFaces, JSF 2.2 and CDI on Google App Engine


Recently we did a proof of concept on Google App Engine, the cloud solution of Google. The Java version, supports servlets and you can already find various resources on the internet where the procedure is described to have the technologies listed in the title working on the platform.

But some of them are already quit old or give only a partial solution.  So I decided to put our findings together in this blog post.  All the frameworks are from the Apache group or have the Apache License.

We used version 1.9.1 of the Java GAE SDK.


The most difficult technology of the list is JSF. You can find various posts where you have to create your custom version of Mojarra to be able to deploy it.  This has to do with the use of JNDI sources which is not allowed on AppEngine.

We tried the Apache MyFaces 2.2.2 version and it went remarkable smooth.  We made the following  configuration options in the appengine-web.xml file.

        <exclude path="/**.xhtml" /> 

The least obvious things was that we needed to tell AppEngine that xhtml files aren’t static, so that we can define it as an url pattern for the faces servlet.  Using this url extension is a best practice so that you can’t retrieve the raw html files of JSF.

EL 2.2

At this point, we were already able to deploy a JSF application and had the hello world style application working.  But if we tested with method expressions, like

<h:commandButton value="Greet" actionListener="#{testAction.doGreeting()}" />

We received an error that the brackets weren’t expected.  So it was clear that only value expressions are recognised and not the method expressions.

We tried various EL expression factories, and it turned out that the one of JBoss worked best.  But we weren’t able to use the latest version of the framework. we received following security exception

access denied ("java.lang.RuntimePermission" "modifyThreadGroup")

Although it is a CR release, it did the job so we stayed with this maven artefact  org.jboss.el:jboss-el:1.0_02.CR6


Plain JSF applications aren’t attractive, that is why you use some component library like PrimeFaces which became the de facto standard.  Adding this to artefact to the maven dependencies, we hit another issue, but this time we identified it as a known GAE bug.

It has to do with the handling of the If-Modified-Since request header.  But we quickly found an excellent solution by Derek Berube.

Adding the 2 classes and define the filter in the web.xml file, the problem was solved.

We even tried the latest PrimeFaces 5.0 version (it was just before it went into his first CR release) and there was no other issue we could see at first glance.  So this means you can now create web application targeted to mobile devices on Google App Engine.


As I’m a strong believer of Java EE, so I tried to use CDI for the middleware instead of the Spring approach too many people take without considering the alternatives.

There is an excellent Apache implementation of CDI, called OpenWebBeans.  The following artefacts where added to the project

  • openwebbeans-impl
  • openwebbeans-spi
  • openwebbeans-web
  • openwebbeans-jsf
  • openwebbeans-el22

Regarding the configuration of OpenWebBeans, we just had to follow the procedure for a regular web server like Tomcat or Jetty.
After adding an empty beans.xml file and define the WebBeansConfigurationListener in the web.xml, the dependency injection worked like a charm.

Just as with JSF, there exists also for CDI an extension beyond the basic stuf and I choose CODI (Apache MyFaces Extensions CDI). Just adding the dependency was enough to make it work.

Other technologies

We also added the JPA option and used a maven plugin to handle the deploy to Google App Engine automatically when a mvn deploy command is issued.

I find it a pity that there is no database solution available for free on Google App Engine. It doesn’t need to be very powerful. Just a simple schema that you can use for demonstration purposes of your application.

This is in contrast with the JBoss OpenShift offering, where you can have a full Java EE stack with a database for free.  But that will be covered in another blog post.


Apart from one little issue (bug 8415) which can easily be bypassed, it was quit easy to assemble the required stack to have a JSF based web development environment on Google App Engine. This is in contrast with a few years back where various issues limited the possibilities.

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.