Thursday, 5 November 2015

Show application version on your JSF screens


Sometimes it can be handy to show the application version on the screen of your application. 
Users get used to have access to this information and it can also ease the communication in a lot of situations. Especially when you are releasing very often.
  • Users can see when a new version is available
  • When issues are reported, it is easier to indicate in which version it occurred
  • Refer to the version where a certain feature appeared in the application in the documentation.

In this text, I'll show you how you can create this version automatically with Maven and read and show it on a JSF screen.

Create version

Maven has support to put a timestamp and the project version in the manifest file. This file is  specifically designed to contain this kind of information (among other things).
You can configure the maven-war-plugin (this functionality is also available in the maven-jar-plugin) to put additional info in the file which is created by default.


The format in which the timestamp is placed in the file can be environment specific, like local settings of your computer.
Therefor you should always define the timestamp format in the pom.xml file so that you have repeatable packaging between different environments.

The format can be specified by using a property like this.


The result is that we have 2 entries in the manifest file, for example
buildTime: 20151104-1123
version: 1.0.2

Read the info

Reading the information is nothing specific for Java EE of JSF.  We will use the Properties file functionality to read the file.
A lot of people use the '=' sign as delimiter between the key and value pair in the file, but the semicolon (:) is also a default delimiter as you can read from this javadoc.

So if we have a reference to the manifest file, we can feed it in the load method of the properties class and we have the version and build time (as a string).
For this info, we can use the ServletContext and the resource loading which is available.

private Properties loadManifestFile() {
    ServletContext servletContext = (ServletContext) FacesContext
      Properties prop = new Properties();
      try {
        InputStream resourceAsStream = servletContext.getResourceAsStream("/META-INF/MANIFEST.MF");  
         if (resourceAsStream != null) {
            prop.load(resourceAsStream);        }
    } catch (IOException e) {
    return prop;

As you can see in the above code, we need a reference to the FacesContext, so we need this code to be executed in the JSF context, like a @PostConstruct method of @ApplicationScoped CDI bean which keeps the version and build time, ready to shown it on a JSF screen.

Show the info

Showing the information is of course very specific for each application. And you would probably show it differently in each version.
In my last application, I showed the information  in a floating div in the bottom left area of the screen. That way, it was always visible.

<div style="position: fixed; bottom: 0; right: 0;">
   #{infoBean.version} (#{infoBean.buildTime})


With some easy configuration of maven, a simple read from the manifest file with the Properties class, we are able to show the version and built time of your application on screen. 
This can help in the good communication with your end users.
And of course, other information can be stored and used in a similar way.

Monday, 27 July 2015

Temporarily disable or conditional executing of PrimeFaces AJAX calls


In JSF 2.0, the AJAX functionality is standardised in the specification and can be used in a consistent way between JSF implementations and component libraries like PrimeFaces.
With the addition of new functionality, new usage patterns become a habit. But new usages also brings more advanced scenarios with their own issues.

The situation I want to discuss today, is where you have the need for some partial screen update with AJAX but which you don't want in all situations. The conditional aspect which I referred to in the title of the text.

Problem description

Suppose you have the following screen area:

It contains the following elements from left to right
* A field to enter an existing code. When the end user leaves the field, the code is looked up.
* A second, read only field or label, where the description of the code is placed when it is an existing one.
* A button, which is only available when the first field doesn't contain an existing code and lets you add a new one.

Within the JSF page, the structure looks something like this.

<h:panelGroup id="codeArea">
    Code :
    <p:inputText value="#{codeBean.code}id="code">
        <p:ajax event="blur" listener="#{codeBean.onBlurCode}" update="codeArea"/>
    <p:inputText value="#{codeBean.codeDescription}" disabled="true" placeholder="description"/>
    <p:commandButton icon="fa fa-plus-circle" actionListener="#{codeBean.addCode}" update="codeArea" disabled="#{empty codeBean.description}"/>

With the ajax tag within the input field, we can perform the partial screen update when we leave the input field. We need to update the complete group as the button needs to become disabled as we enter an existing code.

Conditional executing

This construct works perfectly when you tab out of the input field.  The blur event triggers the AJAX execution and the server side code checks if the code exists. Due to the partial screen update the button becomes disabled when the code doesn't exists or enabled when the code isn't found.

But there is a scenario which fails; when the focus is in the input field and we click on the command button.  You will found out that the click on the button is ignored.  

If we inspect what is happening in the network console of the browser; we see that there is an AJAX request to the server which corresponds to the blur event of the field.  But there is no request which corresponds to the click on the button.
This is because the blur event replaced the DOM element in the browser with another, for the end user identical component. So the click is on an element which no longer exist on the screen after the AJAX  completes.

So how can we solve this? Luckily PrimeFaces uses JQuery on the client side.  So when we could disable the onblur event execution in the case when we click on the button, we have a solution. And the good thing is that we can achieve this, quite easily.

The mousedown event is executed before the blur event. This is can bee seen by the following testing code. (thanks to mudassir)

So by adding the following code:


We can remove all event handlers from the input field, and thus the click is executed.


Making the AJAX functionality can be easily achieved within PrimeFaces with the help of JQuery which is already available in the browser? In this text I showed you how you can disable the blur event in the case when you click a specific button but it will be active in other scenarios.

Monday, 8 June 2015

Focus HTML element after AJAX call with PrimeFaces


The combination of AJAX updates to the screen and the focus of a field is more then once an issue for the developer. And this is not an issue of PrimeFaces, but comes with the fact of using AJAX.

This blog explains what you can due in the 2 most important scenarios what you normally encounter.

Problem description

Image you have on the screen 2 input fields, field A en field B.  There is an onBlur handler attached to field A which does a partial update of the screen, containing field B, with an AJAX call.

So what happens when the user is in field A en tabs out of the field? Leaving the field, results in the trigger of the onBlur handler. During the time that the AJAX calls is performed asynchronously, the browser performs the standard behaviour, and thus the focus is placed in the field B.

But then the AJAX call returns and results in updating the screen, and there are use cases where the developer decided to replace the field B. And since it is a replacement of the element in the DOM tree, the focus which was original in the field B is now lost because the field is replaced by another element.

Fixing focus issue

The first scenario describes the situation where the focus must be placed in a certain field which is updated by the AJAX call.  But it is always the same field regardless of the result of the server side code.

This can easily achieved by using the oncomplete attribute of the PrimeFaces widget who initiated the AJAX call.
This is JavaScript code which is performed when the AJAX call was successful (and thus there was no error) and the replacement of the DOM elements in the browser is completed.
So at this point the DOM tree is stable again and we can give a field the focus.


The above snippet places the focus in the newProjectName field when the AJAX is finished.

Conditionally define the focus

Another scenario is where the fields that needs to get the focus needs to be defined conditionally.  Lets examen this use case better with some screen example.

In the above case, we have a field to enter some kind of code.  And depending on the code, we sometimes needs additional information from the user.
So, there will be an AJAX handler (p:ajax) which call some java listener method to perform the server side functionality which defines if there is additional information needed. 

Initially the 'additional' field is disabled, so the focus is not placed in this field by the browser. And since the field is replaced by the AJAX call in the DOM tree, the focus would be lost anyway.

But from within the Java listener method, we can execute some JavaScript when the AJAX call is finished.  This is one of the great features of PrimeFaces.

So, by adding the following code in the Java method, we can place the focus in the additional field. And within Java it is easy when this focus must be placed there (the conditional aspect of this usecase)



The focus and AJAX combination has some conflicts. In the Expert group for JSF 2.3, they are considering some additional tags to handle those situations.
Within PrimeFaces, we saw with 2 usecases that you can manage the problem with the usage of the excellent integration of JavaScript within PrimeFaces. This from within the view (JSF pages) as from within Java.

Have fun.

Monday, 4 May 2015

Introducing Jerry and Valerie

Or the JSF renderer interceptor and the (bean) validation extension.


The first opensource project where I ever posted a change to, was Apache MyFaces Extension Validation, ExtVal in short. It is a framework for having a validation platform with many great features.

But the last few years, I only used a few specific parts of the platform with some of my own extensions.
Since ExtVal was designed for JSF 1.x and later extended to JSF 2.x, I decided to recreate it.  CDI the cornerstone in every aspect of the version and geared towards JSF 2.x and Bean Validation.
But if you like, you can still create all the features from ExtVal in the new version.


One of the features of ExtVal that I use a lot, is the JSF Renderer interceptor around which the complete platform is built. The idea is very simple, during registration of the renderers at startup, they are wrapped with a custom class.
This allows to have a before and after of all the important steps of a rendering; decode phase, encode begin, encode children, encode end and converted value.

This very simple concept has many possibilities. For example, you want to indicate every required input field with a special background colour.  These are the step that you need to do

1- Add Jerry to your maven project

2- Define a ComponentInitializer, this is a specific renderer interceptor which can perform some actions in the before encode begin step.

public class RequiredInitializer implements ComponentInitializer {
   public void configureComponent(FacesContext facesContext, UIComponent uiComponent, Map<String, Object> metaData) {
      InputText inputText = (InputText) uiComponent;

      if (inputText.isRequired()) {
         String style = inputText.getStyle();
         if (style == null) {
            style = "";
         inputText.setStyle(style + " background-color: #B04A4A;");


   public boolean isSupportedComponent(UIComponent uiComponent) {
      return uiComponent instanceof InputText;

The above code adds the background colour to every PrimeFaces input text field.  This class is found using CDI mechanisms, and that is the reason why we have to annotate it with ApplicationScoped.  But it gives us also the possibility to inject any other CDI bean into this initialiser method.

Jerry is used in the Java EE declarative permission security framework Octopus to handle the security on the JSF component level.


Another thing which I always find a bit annoying is that you should redefine the maximum length of a field at the JSF component level, although you have defined a Bean validation constraint on the java property.

For example, suppose you have a property for the name of a person

@Size(max = 50)
private String name;

When you have a JSF input field component pointing to to this property

<h:inputText value="#{}"/>

then, the size restriction is checked during the validation phase. But why do you let the user input a longer then allowed value? So you have to use the size attribute on the h:inputText but it should go automatically, no.

That is where Valerie comes into the scene, another extraction from the ExtVal framework. 

side note; How the names are chosen. Jerry was chosen as it sounds phonetic like JRI (JSF Renderer Interceptor) So, I needed a female name to go alone with it and it should be related to validation.

So how can we have in the above example the size restriction from the bean validation property size on the screen?

The only thing you need to do is add the Valerie dependency to your project.  


One renderer interceptor is responsible for retrieving and interpretation of the annotation information. A component initialiser then modifies the JSF component by specifying the size attribute from that info.


Jerry and Valerie are 2 small libraries extracted from the ExtVal framework.  They are centered around the JSF renderer interceptor and the extraction of bean validation information and gives you some handy features which makes your application easier to maintain.

The current version is 0.2, but since they have a firm solid history within ExtVal and are already used in a few projects, they are ready to use.  In the near future there will be some small features added and some more testing will be done before a first final version will be released.

They can be used in any Java EE 6 or Java EE 7 server (or servlet container if JSF, CDI and bean validation are present) and compiled with Java SE 6.

The basic documentation of the project can be found here and feedback, issues, feature request are welcome at the issue tracker on gitHub.

Maven artefacts are available in the C4J OpenSource Nexus 
Have fun with it.

Monday, 13 April 2015

Native GridLayout component in PrimeFaces 5.2 (panelGrid)


A while ago, I blogged here about the GridLayout component for JSF 2.X which allow you to have the responsive layout using DIV structure with CSS classes from Bootstrap or PrimeFaces. 

In the recent PrimeFaces 5.2, the panelGrid component is improved so that you can have the same functionality. 


With the new version, you can specify the CSS column class yourself, which allows you to have columns of different width.

So now it is possible to write something like this 

<p:panelGrid columns="2" columnClasses="ui-grid-col-8, ui-grid-col-4" style="width: 100%" layout="grid">

    <h:outputLabel value="First Column"/>

    <h:outputLabel value="Second Column"/>
And have 2 columns, the first twice as wide as the second one.

The old functionality is still available, so if you don't specify any columnClasses in the above example, both columns have the same width.

So if you are using PrimeFaces, there is no need anymore for my GridLayout component, unless you want to use twitter bootstrap CSS classes.

That is all for now about the new primeFaces 5.2. Enjoy it.

Sunday, 29 March 2015

Advanced File download with PrimeFaces


When your Web application needs to send a file to the browser, the classic approach is using a web servlet to serve the contents.
PrimeFaces has a specific tag for downloading a file, so that you don't need a servlet. And with a small trick, you can even update the screen in the same action.

FileDownload component

The example with the servlet can be skipped, I guess. Everyone created already a servlet which is able to send content to the browser.
When you are working with JSF, and PrimeFaces, there is an alternative for the servlet approach.
PrimeFaces has the FileDownload component. It is an ActionListener, so you can use it on a commandButton to perform the download.

Let's have an example.
<p:commandButton value="Download" ajax="false">
    <p:fileDownload value="#{fileBean.file}"/>

@ManagedBean(name = "fileBean")
public class FileDownloadController {

    public StreamedContent getFile() {
        InputStream stream = this.getClass().getResourceAsStream("/yourfile.txt");        return new DefaultStreamedContent(stream, "text/plain", "downloaded_file.txt");    }

The StreamedContent, already used by the graphicImage component, contains the data which is send to the browser. You can supply the constructor with an InputStream which has the actual contents.

This can be static file or a dynamically generated one. The PrimeFaces code is then responsible for reading from the InputStream and send it to the browser. Together with the required housekeeping like setting the mime type, http status and setting the JSF response as completed.

Advanced use case

Together with file download, there are use cases where you also need to update the screen which initiated the download.
Recently we had the use case where the end user can specify some options of the file he wants to download.  The options are presented in a dialog which should be preferably closed when the download is performed. Also the screen should be indicate the file download occurred.

Here the RemoteCommand is the solution to these cases.  The RemoteCommand allows to call some JSF bean methods and JSF lifecycle methods from JavaScript.

<p:commandButton value="Download2" ajax="false" onclick="pageRefresh();">
    <p:fileDownload value="#{fileBean.file}"/>
<p:remoteCommand update="@all" name="pageRefresh"/>

When we click on the button, the onClick activates the javaScript version of the RemoteCommand and initiates a AJAX partial page refresh of the screen. On the other hand, the click on the button also initiates the ActionListener of the FileDownload component to perform the file download.

Since we where able to initiate 2 calls, we can perform 2 actions, the download and the screen update.


With the help of the FileDownload component it becomes easier to program the download of a static or dynamic file in JSF. You no longer need a servlet to perform these kind of actions.
With the help of the very broad useable RemoteCommand component, we can even initiate 2 actions.  The file download and some screen updates.

Sunday, 15 March 2015

Override Java settings on OpenShift


With OpenShift, your server instance in the cloud is prepared with a few mouse clicks or with a single command with the rhc tool.
In most of the cases, this is all you need and you can start right away with your freshly created server instance (named gear in OpenShift terminology).
But in other situations, you want to make some changes to the Java environment, like setting system properties or changing the security settings.

In the case of the security settings, in a normal environment, you can update the file in the JRE_HOME/lib/security folder.  But on the OpenShift environment there are some constraints which makes this task a bit more difficult.  This text shows you an easy way to accomplish your goal.


We have developed a JSF application which uses OAuth2 as authentication means.  So we are using an SSL connection to the OAuth2 provider to verify the tokens which are presented to the applications.
It was working fine on OpenShift with the latest WildFly 8.2 cartridge. And last week, we created a new gear and our application throw an exception EC AlgorithmParameters not available

When we compared this new instance with the instance we had already running, we found out that the java version was different.  The newest one, is using OpenJDK 8u31.  And searching on the web for the combination of this version and the exception we received, revealed that there is an issue with this version related to Elliptic curve algorithm.

So, the next step was to edit the file to exclude the algorithm which causes problems in our cases.  
The key jdk.tls.disabledAlgorithms in the file, needs to contain the codes of the algorithms we don't want, in our situation EC,ECDHE,ECDH.

But when I opened the file and wanted to change the content, I received the warning that the film is read-only.  And you can't change it and you can't become a super user to overrule it.

And I can understand that you want to secure some parts of the server.  But it is no option for us to rewrite the Web application with Java 7 due to a, hopefully, temporarily issue with the Java which is running on the gear.


The solution was found when I found the blog of Eyal Lupu which gives a nice example of how you can override the contents of the file (the documentation in the file itself indicate already this possibility but with the example it became clear for me) and the OpenShift user guide.

So we created a file on the gear to override the key jdk.tls.disabledAlgorithms from the file. And by setting a system property using the JAVA_OPTS_EXT environment variable of the gear, we are able to make the application run again without throwing the exception.

Create the file

  •  rhc ssc gearName
  •  vi
  •  content is jdk.tls.disabledAlgorithms=EC,ECDHE,ECDH
  •  pwd -> and note down (copy) the full path location of the just created file.
  •  exit

Set the environment variable

  •  rhc env set<> -a gearName
Restart your gear/app

  •  rhc app restart -a gearName

The OPENSHIFT_DATA_DIR isn't chosen at random.  It is the only directory which isn't cleared when you push some code to the git repository. So our file is save there and will not be touched by any of the system processes.


The JAVA_OPTS_EXT environment variable is important if you want to change some settings of the Java Environment.  You can add some system properties to configure your application (like setting the JSF project stage) or to override the configuration for instance as explained in this text.

Hope this help you if you have a similar 'issue' with OpenShift.