Thursday 5 November 2015

Show application version on your JSF screens

Introduction

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 manifest.mf file which is created by default.

<plugin>
   <artifactId>maven-war-plugin</artifactId>
   <version>2.4</version>
   <configuration>
      <failOnMissingWebXml>false</failOnMissingWebXml>
      <archive>
         <manifestEntries>
            <version>${project.version}</version>
            <buildTime>${maven.build.timestamp}</buildTime>
         </manifestEntries>
      </archive>
   </configuration>
   <goals>
      <goal>manifest</goal>
   </goals>
</plugin>

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.

<properties>
   <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
   <maven.build.timestamp.format>yyyyMMdd-HHmm</maven.build.timestamp.format>
</properties>

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
            .getCurrentInstance().getExternalContext().getContext(); 
      Properties prop = new Properties();
      try {
        InputStream resourceAsStream = servletContext.getResourceAsStream("/META-INF/MANIFEST.MF");  
         if (resourceAsStream != null) {
            prop.load(resourceAsStream);        }
    } catch (IOException e) {
        unexpectedTechnicalExceptionController.handleUnexpectedException(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})
</div>

Conclusion

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


Monday 27 July 2015

Temporarily disable or conditional executing of PrimeFaces AJAX calls

Introduction

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>
    <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}"/>
</h:panelGroup>

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:

onmousedown="$(PrimeFaces.escapeClientId('frm:code')).off();"

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

Conclusion

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


Introduction

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.

oncomplete="PrimeFaces.focus('frm:newProjectName');"

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)

RequestContext.getCurrentInstance().execute("PrimeFaces.focus('frm:additionalInfo');");

Conclusion

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.

A major new version is available under the Atbash umbrella: http://www.atbash.be/2018/02/26/a-renderer-interceptor-concept-for-java-serverfaces/

Introduction

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.

Jerry

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
<dependency>
   <groupId>be.rubus.web</groupId>
   <artifactId>jerry</artifactId>
   <version>${jerry.version}</version>
</dependency>

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

@ApplicationScoped
public class RequiredInitializer implements ComponentInitializer {
   @Override
   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;");

      }
   }

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

Valerie

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="#{personBean.name}"/>

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.  

<dependency>
   <groupId>be.rubus.web</groupId>
   <artifactId>valerie</artifactId>
   <version>${valerie.version}</version>
</dependency>

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.

Conclusion

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 
<url>http://nexus-osc4j.rhcloud.com/content/groups/public/</url>
Have fun with it.

Monday 13 April 2015

Native GridLayout component in PrimeFaces 5.2 (panelGrid)

Introduction

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. 

Improvements

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"/>
</p:panelGrid>
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

Introduction


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}"/>
</p:commandButton>

@ManagedBean(name = "fileBean")
@RequestScoped
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:commandButton>
<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.

Conclusion

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

Introduction


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

History

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

java.security.NoSuchAlgorithmException: 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 java.security 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 java.security 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.

Solution

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 java.security 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 java.security 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
  •  cd $OPENSHIFT_DATA_DIR
  •  vi override_security.properties
  •  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 JAVA_OPTS_EXT=-Djava.security.properties=file:<> -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.

Conclusion

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 java.security configuration for instance as explained in this text.


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

Monday 19 January 2015

GridLayout component for JSF 2.X

Introduction

It is common practice to use a CSS Grid to define the layout of your web application page.  We shouldn’t use tables for that purpose.
Also in JSF we can use this CSS Grid but it requires quit a lot of DIV elements and thus boilerplate in your page. The good thing is that we can create a custom component which reduce the amount of html we need to put in dramatically.  The component got the name gridLayout.

PrimeFaces recently introduced in his version 5.1, also CSS Grid classes.  The following example comes from the user guide.
<div class="ui-grid">
    <div class="ui-grid-row">
        <div class="ui-grid-col-4">Col1</div>
        <div class="ui-grid-col-4">Col2</div>
        <div class="ui-grid-col-4">Col2</div>
    </div>
</div>

But also other CSS Grid systems can be used with the gridLayout custom component.  The component was first used in an application that used the Bootstrap CSS grid.  And in fact, all CSS grids can be used as you specify which CSS class will be used on the row DIV and which will be used on the column DIVs.

gridLayout

The gridLayout component has 3 attributes, which are
columns: This determines the number of columns which should be created.
rowClass: Determines the CSS class which will be used on the row DIV, in above example it is ui-grid-row.
columnClasses: A comma separated list of CSS classes which will be used on the column DIVs.

The needed steps to integrate the component are described further on in this text, I already give you an example usage:

<c4j:gridLayout columns="2" rowClass="ui-grid-row" columnClasses="ui-grid-col-2, ui-grid-col-4">
    <p:outputLabel for="firstName" value="First name"/>
    <p:inputText id="firstName"/>
    <p:outputLabel for="lastName" value="Last name"/>
    <p:inputText id="lastName"/>
    <h:panelGroup/>
    <p:commandButton value="save"/>
</c4j:gridLayout>
The above example creates a layout with 2 columns. The first column, with the labels, spans 2 ‘columns’, the other column takes 4 ‘columns’ of the CSS grid.  As you can see, we don’t need to take up the complete with available.  In this example, we are just using half of the screen.
On the last row, the button is aligned with the fields due to the .

Configure the project and usage of the component.

  • Download the code from GitHub.  It is a maven project but I didn’t deploy it to Maven Central.
  • Build it locally and add it to the dependencies of your project
<dependency>
     <groupId>be.rubus.web</groupId>
     <artifactId>gridLayout</artifactId>
     <version>1.0</version>
</dependency>
  • Define the namespace on top of your xhtml page, like 
xmlns:c4j="http://www.rubus.be/component"
  • Start using it, according to the info you saw already here.

Things to know

  • It is released under the Apache V2 License.
  • It is compiled against Java 1.5
  • It is only dependent on JSF 2.0 (Java EE 6).
  • It is NOT dependent on any component library.
  • If you define less CSS classes in the columnClasses attribute, as you have defined in the columns attribute, columnClasses are reused from the beginning of the attribute value.
    So the example from the PrimeFaces user guide can be achieved by the following coding
    <c4j:gridLayout columns="3" rowClass="ui-grid-row" columnClasses="ui-grid-col-4">
  • The correct assignment of each JSF component to a certain column and row is only guaranteed if you use JSF components as children.  If you use html elements or plain text/EL expressions, the layout can be very surprising and not want you had in mind.
  • You can also put your custom CSS classes in the columnClasses attribute and even combine them.  So if you want to right align the label column, you can write something like this.
    <c4j:gridLayout columns="2" rowClass="ui-grid-row" columnClasses="ui-grid-col-2 alignRight, ui-grid-col-4">

Conclusion

The gridLayout component is a very small one but makes it easy to use the CSS Grid of your choice in your JSF Web pages.
Have fun coding.

Update

13/4/2015

With the new PrimeFaces 5.2 release, the panelGrid component is updated to have similar functionality as the GridLayout (but only for PrimeFaces CSS classes)

See http://jsfcorner.blogspot.co.at/2015/04/native-gridlayout-component-in.html.