Tuesday, 23 December 2014

My 3 Christmas wishes for Java EE Security

Introduction

Recently, there was the start up of the new Java EE Security JSR, JSR 375. For me, it is one of the areas, together with Integration testing, where the Java EE specs can be improved greatly.
Over the years, I did a few large scale enterprise applications and those applications could benefit a lot if some of the following things would be standardised or available out of the box.

This blog post describes my needs and/or proposals that I have for Security from the JavaSever Faces view technology angle. And I know, there is much more that is vital for a good security implementation.

LoginModule

LoginModule is an interface, part of the Java Authentication and Authorization Service (JAAS), some of the security basics of Java SE.

The LoginModule is responsible for taking the credentials (most of the time, they are the username and the password of the user) and verify it against some kind of store (database, LDAP, file, etc …)

The issue is that JAAS is only standardised within Java SE, so there is nothing specified how the Application servers should integrate it.

Glassfish for instance requires that you extend a custom class (which implements LoginModule of course) and WebSphere has his own extension of the Subject (the class which represents the end user) class.
And all the application servers have heir own way of defining the LoginModule within the configuration.

So why not standardise this, by introducing a new annotation like @Realm, which defines the name of the realm and the LoginModule to use for it.

This name can then be defined in the web.xml file and that is basically all the things you need to do.

Permission Based security

In almost all the cases, you only hear about role based access models as security means.  I have done several, quit large enterprise projects and I never used the role based model.
Simply because it is not flexibel enough. Because any change in what the user role is allowed to do, results in recompilation of the code.  And I’m not even talking about the nightmare it is to properly test the role based security model over and over.

Permission based security on the other hand is much simpler. Every action the end user can perform or any data piece which needs to be displayed conditionally, gets a permission assigned. And the end user needs this permission to be able to perform the action or view the data.
The main task is now the configuration which permissions are assigned to a user.  But this is done outside the application, no recompilation is need as this info can be stored in a database for instance. There can be many permissions, I once had a set of almost 1000 permissions, so you can group them before you assign the groups to users.

The main difference between permissions and roles is that a permission is undividable and guards a single piece of the application.  A role is linked to the end user and what the end user is allowed to do can change over time.

So I would like to see the term Permission appear in the specifications and how they are linked or mapped to users and roles.
And the classic role base model also fits in this model.  Just replace the term Permission with Role and assign the Permission/Role to multiple areas of application.

Declarative security for JSF Components

This is specific for JavaServer Faces, which is the view technology I use most of the time. When data or a button shouldn’t be shown to the end user, the rendered attribute is used in most cases


But rendered attribute can contain also business logic rules that determine the visibility of the button.
But security is a cross cutting concern and should thus be separated from the other logic. So the ideal situation is that you use tags to indicate which permission is needed to render the button.

Some years ago, I prototyped already such functionality.  You can read more on that topic in this blog text.

 

The framework allows you to define some voters that determine if a certain user is allowed to see the button based on a permission.

Beginning of this year, I integrated this feature in a larger security framework called Octopus.  There it is combined with Apache Shiro to have declarative security for JSF components, URL protection and secured methods of EJB and CDI beans.  See this text for some more info.

But enough promotion for my work, the JSF tags for security are very handy and very readable. But it needs something like a Renderer interceptor and although possible today, it should be described in the specs and promoted as the preferred way for security.

OAuth2

Oke, I had already my 3 wishes, but what about other authentication ways which doesn’t fit into the LoginModule concept like OAuth2.  Social media is everywhere and thus also OAuth2 security providers which we can and should use.

JSR 375

This JSR is a good start to modernise the security specification of Java EE.  But I’m also sceptic.  As said, security is a cross cutting concern and therefor can be seen separately from the rest.
But many aspects are specific for the view technology, like the JSF security tags of Octopus.  And will those kind of interaction be tackled by this JSR?

But since the JSR process is much more open nowadays, lets provide them with usecases we need.  This was my contribution to that process.




Friday, 31 October 2014

Overriding defaults of PrimeFaces component properties

Introduction

The prime faces components can be customised with many options.  They can be specified by using the properties on the components.  For all these customisation possibilities, there are defaults active so that you don’t need to specify each option.

But what if that default value doesn’t fit for your project. What are your options?  I’ll show you how you can override the default in the case of the datable component.  but other components can be modified in the same way.

Paginator for dataTable.


The dataTable component can show the paginator bar to do navigation in a table with a lot of records.  By default, this bar is shown on top and at the bottom of the table.

But what can you do when you only want to show it at the bottom of the table?

Use the property


Of course, everywhere you place the table on a screen, you can specify the paginatorPosition property and set it to bottom.

    <p:dataTable value="#{personBean.persons}" var="person" paginator="true" rows="3" paginatorPosition="bottom"> 
        <p:column headerText="name"> #{person.name}

    </p:dataTable>

This will work of course but is more work and it can be forgotten by the developers. especially in larger scale applications.

And what happens if they decide that after all, they want to show it as it ways, on top and at the bottom? Change everything again?

CSS is everywhere

Since PrimeFaces relies heavily on CSS, a solution can be found in specifying some CSS style which hide the top paginator bar.

If you inspect the HTML in the browser, you can easily see that the top paginator has a style class with the name ui-paginator-top.

So the following CSS is able to hide the top paginator bar.

    <style type="text/css"> 
        .ui-paginator-top { 
            display: none; 
        } 
    </style>

But this solution is not ideal. The paginator is suppressed in a general way, so we don’t need to change the xhtml files individually.  But the server sends this information to the browser.  So the size of the response is too large because some parts aren’t shown anyway.

Change the defaults


There exists another way to achieve our goal.  You can alter the defaults of PrimeFaces quite easily since PrimeFaces is designed with extensibility in mind. 
The default values are coded in the class org.primefaces.component.datatable.DataTable.

There exists for example a method getPaginatorPosition() which retrieves the values specified in the xhtml file or, when not specified, returns the value “both” which is the default for this property.

So when you extend this class, you can overwrite this method and return, for instance always the value “bottom” and we now have override the default (well we basically ignore the property and always return the same value)

public class MyDataTable extends DataTable { 
    @Override 
    public String getPaginatorPosition() { 
        return "bottom"; 
    } 
}

Just overriding the method in the extended class is not enough.  You need to inform JSF that your version must be used as component class.

This can be done by specifying the following snippet in the faces-config.xml file.

    <component> 
        <component-type>org.primefaces.component.DataTable</component-type> 
        <component-class>be.rubus.web.primefaces.MyDataTable</component-class> 
    </component>

And if you now run the application, you will see that there is no top paginator bar and it isn’t even present in the generated HTML.

How can you know which value you need to use for component-type?  Look in the PrimeFaces faces-config.xml file (you can find it in the META-INF directory of the PrimeFaces jar) and look for the component class you override.  That is the value you need to use.

Conclusion


You can easily override the default values for the PrimeFaces component properties.  Just extend the PrimeFaces component class and put any value you like in the overriding method.  You just have to specify then your component class in the  faces-config.xml file.

Sunday, 21 September 2014

Input in uppercase with JSF inputText, a TagHandler example

Introduction

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.

TagHandler

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) { 
        super(config); 
    } 
 
    @Override 
    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"); 
            } 
        } 
    } 
} 

Configuration

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="http://java.sun.com/xml/ns/javaee" 
                xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
                xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facelettaglibrary_2_0.xsd" 
                version="2.0"> 
    <namespace>http://www.c4j.be/rubus</namespace> 
 
    <tag> 
        <tag-name>uppercase</tag-name> 
        <handler-class>be.sezz.handler.UppercaseHandler</handler-class> 
    </tag> 
 
</facelet-taglib>

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

Example

In the Facelets Configuration file, we have defined a namespace(http://www.c4j.be/rubus 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" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml" 
      xmlns:h="http://java.sun.com/jsf/html" 
      xmlns:r="http://www.c4j.be/rubus"> 
 
... 
 
<h:body> 
    <h:form id="mainForm"> 
        <h:inputText id="field" value="#{someBean.value}"> 
            <r:uppercase/> 
        </h:inputText> 
    </h:form> 
</h:body> 
</html> 

Conclusion

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

Introduction

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.

Mavenize 

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.

Customizations

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

Font

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.

Conclusion

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

Introduction 

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
%application%-%domain%.rhcloud.com
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. 

Database

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. 
        java:jboss/datasources/MySQLDS

Deploy

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..

Cost

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.

Conclusion


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

Introduction

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.

JSF

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.

    <sessions-enabled>true</sessions-enabled> 
    <threadsafe>true</threadsafe> 
    <static-files> 
        <exclude path="/**.xhtml" /> 
    </static-files>


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

PrimeFaces

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.

CDI

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.

Conclusion

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

Introduction

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.

Configuration

In order to activate the feature, you need to put the following content parameter in the web.xml file.
    <context-param>
        <param-name>primefaces.CLIENT_SIDE_VALIDATION</param-name>
        <param-value>true</param-value>
    </context-param>

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
@FacesValidator("custom.VisaCardCheck")
public class VisaCardValidator implements Validator, ClientValidator {
    @Override
    public Map<String, Object> getMetadata() {
       return null;  // No metadata required on client side
    }

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

    @Override
    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" />

Conclusion


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.