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.




Friday, 31 October 2014

Overriding defaults of PrimeFaces component properties

Introduction

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

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

Paginator for dataTable.


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

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

Use the property


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

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

    </p:dataTable>

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

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

CSS is everywhere

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

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

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

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

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

Change the defaults


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

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

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

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

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

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

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

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

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

Conclusion


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