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.

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.




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.