Tuesday 12 January 2016

Lambda expression as JSF actionListener

Introduction

Although there is no official version of JSF which supports Java 8, there are various application servers that run on it today. And thus can we use some Java 8 features today.

I'll show you in this blog post an example of using a lambda expression as an action listener. And more specific where we have a custom composite component with multiple actions sources.

And although I'm not a fan of the binding property, probably due to the issues I had with it during the early days of JSF 1.x, it is a nice use case for Lambda expressions.

Custom composite component

Short recap of what a custom composite component is.
If you have on multiple screens a set of components used in the same manner, you can create a custom component for it. The markup doesn't need to be exactly the same on all those pages or linked to the same managed bean, because you can specify parameters.

That way you can also 'build' your screens using different reusable blocks and you have a very modular approach comparable with using Java methods to increase readability.

And creating those custom composite components is very easy in JSF 2.x. Create JSF file with the definition of your component (interface  and implementation parts) in a special specific folder and you are ready to use it due to the convention principles in place.
Have a search on the internet on this topic and you find various examples how you can do it.

Assigning an action listener to a button within your custom composite components seems for some people a bit more difficult but using the actionSource attribute of the composite component namespace makes it very easy.

<ui:component xmlns="http://www.w3.org/1999/xhtml"
              xmlns:ui="http://xmlns.jcp.org/jsf/facelets"
              xmlns:cc="http://xmlns.jcp.org/jsf/composite"
              xmlns:p="http://primefaces.org/ui">

    <cc:interface>
        <cc:actionSource name="submitListener" targets="submitBtn"/>
        <cc:actionSource name="cancelListener" targets="cancelBtn"/>
    </cc:interface>
    <cc:implementation>
        <div>
            Some multiple button component 
            <p:commandButton id="submitBtn" value="Submit"/>
            <p:commandButton id="cancelBtn" value="Cancel" immediate="true"/>
        </div>
    </cc:implementation>
</ui:component>


The above example defines a custom composite component where we have 2 buttons and each of them, we can assign a different actionListener.

ActionListener

ActionListener is a JSF interface defined for those implementations which want to respond on the click on a button (for example there are other components which also generate the same event) on the screen.

The interface has just one method, as you can see;
/**
 * Invoked when an action occurs.
 * @param e the event to be processed
 */
public void actionPerformed(ActionEvent e);

This makes it an ideal candidate to use it in combination with Lambda expressions since we have a functional interface.

So the following lambda expression
e -> System.out.println("Save clicked");

is valid implementation for the actionListener interface and thus we can assign such methods to the button(s).

Binding the actionListener implementation

As a said in the introduction, with the binding attribute, it is very easy to 'bind' an implementation of the ActionListener interface to the button. 

<adv:multiple>
    <f:actionListener for="submitListener" binding="#{cityBean.save}"/>
    <f:actionListener for="cancelListener" binding="#{cityBean.cancel}"/>
</adv:multiple>
In the above example we retrieve the instance to which the listener is bound to, with a method result. The java code can be as follows.

@Modelpublic class CityBean {

   private ActionListener save;
   private ActionListener cancel;

   @PostConstruct
   public void init() {
      save = e -> System.out.println("Save clicked");
      cancel = e -> System.out.println("Cancel clicked");
   }

   public void performSearch() {
      System.out.println("Searching ");
   }

   public ActionListener getSave() {
      return save;
   }

   public ActionListener getCancel() {
      return cancel;
   }

}
As you can see, this is a nice,clean usage of lambda expressions where we have multiple actionListener targets in the custom composite component.

Conclusion

Using a lambda expression for an ActionListener implementation make your code much more readable and reduces the boilerplate in those cases where you need multiple actionSources for a custom composite component.

Enjoy Java 8 and Java EE!



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.