Sunday, 6 July 2014

Mavenize your Custom PrimeFaces Theme

Introduction

PrimeFaces relies on the ThemeRoller themes for the look of the components.  There are more then 35 already available. But it is also possible to create your own custom ones.  This blog not only describes the creation of such a new theme, which is already quit good documented, but also how you can wrap it in a maven project and add some further customisations.

Create custom theme

ThemeRoller has an online visual tool to design your custom theme.  You can specify Font and colour for various types of content like header, highlights, buttons and so on.

Once you are more or less comfortable with how the examples on the site looks, you are ready to download the theme.
On the download page, it is very important to exclude all the components, you only need the skinning style. You have a convenient ‘toggle all’ checkbox to remove all the components. Also the 1.11 version of jQuery is NOT supported, so take one of the other 2 versions noted on the page.

This zip needs a few modifications before it can be used as custom theme for PrimeFaces. Luckily this is automated and can be done on this page. 

Here you can specify the custom name for your theme and after you upload the zip to the site, you are able to get a jar file which can be used directly in your application.

Mavenize 

Most of the time you want to perform some modifications on the theme. Some of the modifications I made recently are described further on.
So it can be very convenient to turn the jar file into a maven project where the maven package goal generates a valid PrimeFaces Theme.
This is very easy to accomplish.

Just create a minimal POM file, you just need the groupId, artifactId and version info, nothing else, and extract the contents of the  jar into the src/main/resources directory.


The directory structure should look like the image above. The contents of the downloaded jar file is extracted in the resources directory as indicated in the image.

From now on, you can generate the PrimeFaces theme with a simple mvm clean package command.

Customizations

In this section, I want to share you a few of the customisations I made in my recent project.

Font

One of the common questions on the PrimeFaces forum is how you can change the size of the text within PrimeFaces Components.  This can be done by specifying a value for the .ui-widget, .ui-widget .ui-widget  CSS selector.

Instead of putting it into the css file of your application, you can also put this value in the theme and use it in all your applications.

Put the same font information also in the body selector as some components of your application are not from PrimeFaces (for example the h:outputText) and should look the same.

Table record selection

If you look closely to a selected record in a data table component, you see that the upper border isn’t highlighted like the 3 other borders. (look at the showcase with a theme like Blitzer, there you can see it easily).

You can ‘fix’ this in your theme CSS, look for the ui-state-highlight selector.

.ui-state-highlight, .ui-widget-content .ui-state-highlight, .ui-widget-header .ui-state-highlight {
   border: 1px double "yourColor"
   ...
}

Replace the solid with double and you wil see that all 4 borders are identical now.

Other then these 2 customisations, you can put anything you need in that theme file. Examples are
- A different colour for the cancel type of buttons
- A different colour for the default button
- Error indication on a field with a validation error
and so on.

Conclusion

Creating a custom PrimeFaces theme can be done quite easily.  Starting from the ThemeRoller visual designer, you can convert it to a maven project which allows you to customise the theme even further.


Monday, 2 June 2014

Deploy Java EE in the cloud with JBoss OpenShift

Introduction 

In the previous blog post I described how you could create Web Applications using JSF and CDI that are running in the cloud with Google App Engine.
Using a database is also possible but is not available for free on AppEngine and that was the reason I didn’t go into detail about it.
But there exists another possibility to host your Java EE application in the cloud, and it has even more possibilities and is much easier, OpenShift of JBoss.
And best of all, you can run them for free if your requirements are not too high. 

What is it?

OpenShift is a so-called PaaS, platform as a service.  So it is not only limited to a server that you can use or a program, like a web server that is available, it is the complete stack. 
With OpenShift you can use for example a WildFly application server and a database instance to deliver you an environment for the execution of your web application. It has also a unique way of deploying you app using a GIT repository.
In this text I’ll describe the Java EE solution that you can use, but there exists also other possibilities like PHP, Tomcat with Spring, Continuous integration server, and many others.  Have a look on their site about the supported environments.

Creating an application

You first start by creating a domain.  The domain will hold one or more of your applications.  The domain name is also reflected in the URL. The structure is as follows
%application%-%domain%.rhcloud.com
You can assign it an alias if you supply this URL to your DNS provider.

Creating a domain is nothing spectacular, you just have to specify the name for it.

Once you have the domain, you can create the web application in it.
And the first thing you have to do when you create an application is to specify which type of application you want.

In my case, I want to have a Java EE environment in the cloud, so I took the WildFly 8 possibility.  As said there are a lot of possibilities and maybe one that I want to mention here also is CapeDwarf. It implements fully the Google AppEngine API’s so that you can migrate easily from Google to the JBoss cloud.

In the next step you have to give some configuration options, like the application name, as said part of the URL, and if you want to have scaling and thus a load balancer for your application.

The creation of the application takes some time, as it is preparing a machine for you with all the software you need.
But when it is finished, you can already go the to URL and see the welcome page of your application, which you want to customise of course.

The overview page also gives some very important information that you need to be able to deploy and use the application.
In the case of WildFly, it gives the username and password you need to be able to log on in the console of the application server. 
It also states the GIT URL that you can use to clone the source of the application locally and start developing your application.
More on those later. 

Database

Since my test application needs some database to store information, I can create it also on the OpenShift platform.

The idea is that you can add additional ‘cartridges’ that have certain functionality and allows you to create the ideal server for your application.
A database is the most common cartridge, but there exists also others like for example a cartridge to execute some scheduled jobs (CRON like)

Regarding the databases, you can choose between MySQL and PostGreSQL but you have also the possibility of using MongoDB.
Configuration is not needed, you add the cartridge and you receive the URL, username and password for the database to access it.
In case of MySQL, the access is through phpMyAdmin that needs to be added if you want console access directly to your database. 

Web application

I talked a lot about setting everything up, because creating your web application is very easy.
If you clone the GIT repository that was indicated on the site, you see that it is maven based. So any maven based Java EE application can be used.
No special configuration needed, no adjustments like with AppEngine. If it runs on your machine, it runs on OpenShift.

Database access

The only thing that took a little bit of research was the URL to my MySQL database that was created.

I found this knowledge base article,  where it is clearly described.

You first have to create a datasource for WildFly in the configuration files.  You can find the standalone.xml file in the .openshift/config/ directory when you have checkout the GIT repository.
You have to leave the placeholders, like ${env.OPENSHIFT_MYSQL_DB_HOST} in the configuration file so that it can properly be resolved at deployment time.

Once you have defined it there, you can define the datasource in your persistence XML file and the application is able to connect to it. 
        java:jboss/datasources/MySQLDS

Deploy

When you push the changes to the remote GIT repository, a lot of things are happening.
First your application and WildFly server are stopped.  Then it is running the mvn package on your new code. And then the server is started again with your new version of the application deployed.  So it can take a minute or more before your push ends due to these tasks.

Client tool

Besides the option to push the code, you also have the RHC client tools. It is a ruby based tool that allows you to connect to your server. You can perform various operations which this tool which are also possible online.
These include things like
Getting started, like creating domain, applications and adding cartridges.
Working with your app as looking at your log, port forwarding so that you can open the WildFly console from your browser, etc
Account management like setting up ssh connections, authorisation, key generation etc..

Cost

OpenShift can be used free of charge.  They work with the concept of gears. Each feature uses one or more gears, categorised in small, medium and large size. 
A WildFly instance takes only 1 small gear and you get 1 GB of space with it. The space calculation takes into account the code and log size and also the database size.
So the database isn’t taking up any additional gear, a load balancer counts also for 1 small gear.
Since you have 3 small gears for free, you can run up to 3 applications with a database on their platform.

Conclusion


With OpenShift it becomes very easily to deploy your Java EE application in the cloud. JBoss made it possible to use a Maven based application that runs on WildFly to deploy it on their cloud infrastructure. No changes needed, only some slight modification for the datasource to access your database also hosted on their PaaS.

Thursday, 24 April 2014

PrimeFaces, JSF 2.2 and CDI on Google App Engine

Introduction

Recently we did a proof of concept on Google App Engine, the cloud solution of Google. The Java version, supports servlets and you can already find various resources on the internet where the procedure is described to have the technologies listed in the title working on the platform.

But some of them are already quit old or give only a partial solution.  So I decided to put our findings together in this blog post.  All the frameworks are from the Apache group or have the Apache License.

We used version 1.9.1 of the Java GAE SDK.

JSF

The most difficult technology of the list is JSF. You can find various posts where you have to create your custom version of Mojarra to be able to deploy it.  This has to do with the use of JNDI sources which is not allowed on AppEngine.

We tried the Apache MyFaces 2.2.2 version and it went remarkable smooth.  We made the following  configuration options in the appengine-web.xml file.

    <sessions-enabled>true</sessions-enabled> 
    <threadsafe>true</threadsafe> 
    <static-files> 
        <exclude path="/**.xhtml" /> 
    </static-files>


The least obvious things was that we needed to tell AppEngine that xhtml files aren’t static, so that we can define it as an url pattern for the faces servlet.  Using this url extension is a best practice so that you can’t retrieve the raw html files of JSF.

EL 2.2

At this point, we were already able to deploy a JSF application and had the hello world style application working.  But if we tested with method expressions, like

<h:commandButton value="Greet" actionListener="#{testAction.doGreeting()}" />


We received an error that the brackets weren’t expected.  So it was clear that only value expressions are recognised and not the method expressions.

We tried various EL expression factories, and it turned out that the one of JBoss worked best.  But we weren’t able to use the latest version of the framework. we received following security exception

access denied ("java.lang.RuntimePermission" "modifyThreadGroup")

Although it is a CR release, it did the job so we stayed with this maven artefact  org.jboss.el:jboss-el:1.0_02.CR6

PrimeFaces

Plain JSF applications aren’t attractive, that is why you use some component library like PrimeFaces which became the de facto standard.  Adding this to artefact to the maven dependencies, we hit another issue, but this time we identified it as a known GAE bug.

It has to do with the handling of the If-Modified-Since request header.  But we quickly found an excellent solution by Derek Berube.

Adding the 2 classes and define the filter in the web.xml file, the problem was solved.

We even tried the latest PrimeFaces 5.0 version (it was just before it went into his first CR release) and there was no other issue we could see at first glance.  So this means you can now create web application targeted to mobile devices on Google App Engine.

CDI

As I’m a strong believer of Java EE, so I tried to use CDI for the middleware instead of the Spring approach too many people take without considering the alternatives.

There is an excellent Apache implementation of CDI, called OpenWebBeans.  The following artefacts where added to the project

  • openwebbeans-impl
  • openwebbeans-spi
  • openwebbeans-web
  • openwebbeans-jsf
  • openwebbeans-el22

Regarding the configuration of OpenWebBeans, we just had to follow the procedure for a regular web server like Tomcat or Jetty.
After adding an empty beans.xml file and define the WebBeansConfigurationListener in the web.xml, the dependency injection worked like a charm.

Just as with JSF, there exists also for CDI an extension beyond the basic stuf and I choose CODI (Apache MyFaces Extensions CDI). Just adding the dependency was enough to make it work.

Other technologies

We also added the JPA option and used a maven plugin to handle the deploy to Google App Engine automatically when a mvn deploy command is issued.

I find it a pity that there is no database solution available for free on Google App Engine. It doesn’t need to be very powerful. Just a simple schema that you can use for demonstration purposes of your application.

This is in contrast with the JBoss OpenShift offering, where you can have a full Java EE stack with a database for free.  But that will be covered in another blog post.

Conclusion

Apart from one little issue (bug 8415) which can easily be bypassed, it was quit easy to assemble the required stack to have a JSF based web development environment on Google App Engine. This is in contrast with a few years back where various issues limited the possibilities.



Thursday, 30 January 2014

PrimeFaces JBoss forge plugin updated

With the announcement of the new CR release of JBoss Forge 2 (now final release), I remembered that once upon a time (already 2 years ago) I wrote a plugin for PrimeFaces for this tool.
Since then, a lot happened and that version of the plugin doesn’t support PrimeFaces 4. Although it isn’t a big problem, you can manually update the version number of the artifact to 4 in the pom.xml file, I decided to spent some time again on the plugin.
Mainly because the Forge 2 version uses a different concept and now you have the notion of addons. So a rework will be needed to keep the functionality in the new release of JBoss forge.

PrimeFaces 4

The new version of the plugin supports PrimeFaces 4 directly and you can use it to configure the Client Side Validation feature of PrimeFaces.

What are the commands that you need to specify within JBoss Forge?
forge install-plugin primefaces

This command will install the PrimeFaces plugin and is only required the one time.


new-project --named demo --topLevelPackage be.rubus.forge.demo --type war

This command will create a new maven project with packaging type war.  You can choose of course the value for the –topLevelPackage attribute. The command will also ask some questions like the location where the project must be created.


faces setup

This command will add the required maven dependencies for using JavaServer Faces development.  And it will add also some resource files like web.xml, faces-config.xml and beans.xml if you want CDI (this is a question of the command)


primefaces setup

Now the PrimeFaces dependency is added to the project. The version depends on selection you made and you are ready to go with your favourite IDE.

Additional goodies


The plugin also has some additional commands which can be handy
primefaces install-example-facelet

This adds a JSF view file (index.xhtml) which uses templating and contains a Hello World type example of using PrimeFaces.  This is handy is you are not familiar with PrimeFaces and shows you how to add the PrimeFaces namespace.  It is also an example of using the JSF 2.x template feature.


primefaces set-theme

If you execute this command, you see the list of available free themes for PrimeFaces.  It adds the required maven artifact and configures the theme in the web.xml file.


primefaces install-CSV

This is a PrimeFaces 4 specific command which configures the Client Side Validation feature in the web.xml file. See the PrimeFaces users guide how you can use this feature.

JBoss Forge 2


For the new release of the tool, the plugin will be adapted and a short guide will be posted when the addon is available. But enjoy version 1.1 of the PrimeFaces plugin from today on.

Sunday, 5 January 2014

Client Side Validation example of PrimeFaces

Introduction

With the latest version of PrimeFaces, version 4, you have the possibility to perform some validations on the client, by the browser.
This features doesn’t replace the standard JSF validation on the server side but is an addition to it.  The server side validation makes sure that any data posted to the server is valid before it is processed any further. The client side validation is there to inform user faster of data problems.
By default, all the standard validations like required fields, minimum and maximum values, string lengths and so on are available.  But you can also create the JavaScript version of your custom JSF validation.
The feature is very good explained in the PrimeFaces users guide. This posts describes the steps that I have done to make a Visa card validation on the client side.

Configuration

In order to activate the feature, you need to put the following content parameter in the web.xml file.
    <context-param>
        <param-name>primefaces.CLIENT_SIDE_VALIDATION</param-name>
        <param-value>true</param-value>
    </context-param>

Now, your application is ready to use the client side validation feature. And whenever you want to make use of it, you just have to specify the attribute validateClient on the commandButton tag for example.

The standard validations known by PrimeFaces are then performed on the fields in the form.  Any validation error is shown by the messages or growl tag which is also available in the form.

Make sure you read the PrimeFaces users guide to know all the requirements and usages.  The most import ones are


  • Put a messages or growl tag within the form. others are not yet discovered. 
  • Severity attribute of these tags is ignored.
  • Invalid fields are marked by a red border but associated label isn’t colored

These shortcomings will be removed in the next release of the framework.

Custom validation

It is also possible to have a client side validation variant of your custom validations.  Therefor I created an example, a visa card number validation.

You start by creating a standard JSF validator, so a class that implements Validator interface.  For the Client Side Validation feature of PrimeFaces, you have to implement also the org.primefaces.validate.ClientValidator interface.

It contains 2 methods, getValidatorId which defines the name of the JavaScript function that implements the validation on the client side. If the JavaScript function needs some values defined by the validator (like the minimum value for the range validation) you have to return it by the getMetadata method.

This is the java side of the solution
@FacesValidator("custom.VisaCardCheck")
public class VisaCardValidator implements Validator, ClientValidator {
    @Override
    public Map<String, Object> getMetadata() {
       return null;  // No metadata required on client side
    }

    @Override
    public String getValidatorId() {
        return "custom.VisaCardCheck";
    }

    @Override
    public void validate(FacesContext someFacesContext, UIComponent someUIComponent, Object o) throws
            ValidatorException {
        ...
    }
}


The JavaScript must be available on the page where we like to use it, the code is shown below.
PrimeFaces.validator['custom.VisaCardCheck'] = {
    reverse: function (s) {
        var o = '';
        for (var i = s.length - 1; i >= 0; i--)
            o += s[i];
        return o;
    },
    throwError: function(detail) {
        throw {
            summary: 'Validation Error',
            detail: detail
        }
    },
    validate: function (element, value) {
        var reg = /^\d+$/,
            digits = this.reverse(value).substring(1).split(""),
            sum = 0;
        if (!value.match(reg)) {
            this.throwError("Not all digits");
        }
        if (value.length < 13 || value.length > 16) {
            this.throwError("Length invalid");
        }
        if (value.charAt(0) != '4') {
            this.throwError("Wrong start digit");
        }
        for (var i = 0; i < digits.length; i++) {
            if (i%2 == 0) {
                digits[i] = digits[i] * 2;
                if (digits[i] > 9) {
                    digits[i] = digits[i] - 9
                }
            }
            sum += parseInt(digits[i]);
        }
        if (value.charAt(value.length - 1) != (sum % 10)) {
            this.throwError("Check digit validation fails");
        }
    }
};


The important thing here is that the name of the validator in the JavaScript object, custom.VisaCardCheck in my case, is the same as the value returned by the getValidatorId method of the JSF validator.

Usage of the validator at the JSF level is the same as usual.
<p:inputText id="myValue" value="#{dataBean.myValue}" required="true" validator="custom.VisaCardCheck" />

Conclusion


With the Client Side Validation framework, we can inform the user faster about issues with data, without the need to go to the server.

The best thing is that it integrates very well with JSF and it is hard to tell if the message came from the client side validation or from the server side.

The default validations are already available in their javaScript counterpart, also if you use BeanValidation. When you create a custom validation, you have to write the JavaScript yourself, of course.

Sunday, 10 November 2013

GenericMessage for DeltaSpike supporting JSF and REST

Introduction

In the post of January 2013, I described the feature of DeltaSpike to have type safe messages from within a CDI bean which are displayed within the <h:messages> tag of JSF.
It is a great feature which has a minor drawback, especially in the perspective of Java EE as a universal backend system. (see this post for the idea behind this)
In the case a CDI bean, like a service type of bean, is used in the context of JSF and REST contexts, because you have multiple types of clients, there is an issue with JsfMessage of DeltaSpike.

Custom version

Since DeltaSpike is an open source project, you can easily find out how the feature is coded. And you can create something similar which isn’t tied to JSF quit easy as you can see in this post.
First we need to define the alternative for the JsfMessage interface, lets call it BusinessMessage.
public interface BusinessMessage<T> {

    T failing();

    T warning();

    T information();
}

We have 3 methods, so that we can define an error, warning and information message. 

The usage of this interface will be identical to the JsfMessage one of DeltaSpike.  Se we need to define an interface which will be annotated as MessageBundle and we are ready to use it.
@MessageBundle
public interface ApplicationMessages {

    @MessageTemplate(value = "Person already registered")
    String personAlreadyRegistered();
}


@ApplicationScoped
public class AttendeeService {

    @Inject
    private BusinessMessage<ApplicationMessages> message;

    public void addPerson(Person person) {
        //....
        message.failing().personAlreadyRegistered();
    }
}

Within the implementation of the BusinessMessage interface we will make, we can now make sure it will work within a JSF and REST context.

BusinessMessage implementation details

I’m not going to describe all the implementation details in this post.  In a few weeks, the code of a demo application will be made available that highlights almost all of the things that kept me busy the last year. And it is using the BusinessMessage described here.

The code is using the org.apache.deltaspike.core.impl.message.MessageBundleInvocationHandler class of DeltaSpike to have a dynamic implementation of the @MessageBundle annotated interfaces like ApplicationMessages we have in the above example block.

Once we have the message text the user wants, we will store it in a Thread local variable, maintained by a new class BusinessMessageContext.  This class makes it possible to keep some messages independent of the view technology used. So it is supporting JSF and REST style of working.

Show the messages

The last step to solve our issue is that we need use the messages stored in the BusinessMessageContext and send it to the correct view.

For JSF we can create a PhaseListener implementation which is triggered before each Render Response phase.  It can add the messages to the JSF system using the facesContext.addMessage method.

For REST, we can use a javax.ws.rs.container.ContainerResponseFilter concept explained in this post, to send the messages to the client as a JSON response. Some of the aspects will be described in more detail in a future post on that blog.

In both cases, we need to do the clean up of the Thread local variable we have used to store the messages to reclaim the memory.  Therefor the class BusinessMessageContext has a method release() to perform this clean up.

Conclusion

JsfMessage of DeltaSpike is a great feature to have type safe messages. But in some cases your CDI bean will be used in multiple ‘environments’, JSF and REST for example. In that case, we need an alternative which works almost the same but stores the messages, at least initially, in a view neutral way.

Code will be available as part of the demo which will be released in a few weeks.

Tuesday, 8 October 2013

How to debug javascript in PrimeFaces 4.0

Introduction

With each new release of PrimeFaces, the JavaScript becomes more and more important in the framework.
This is no surprise as JavaScript is needed to give the end user a rich user interface. And in the latest release there is quit a lot of new JavaScript code added for the client Side validation framework.
But if you want to debug it in the browser, you see that the code is minified. And thus stepping through it line by line is not possible.
This post describes how you can do it.

Build custom version

The source code of PrimeFaces contains the human readable code and the idea is that we build a custom jar file which contains that readable version of the JavaScript.
As the code is open source, it is available on Google code. We can do a checkout with following command.
svn checkout http://primefaces.googlecode.com/svn/primefaces/tags/4_0

Now we go to the pom.xml file and make some small changes.
The most important one is the change of the version tag.  I have changed it to 4.0-DEBUG (you can find it at the top of the pom.xml file)
    <modelVersion>4.0.0</modelVersion>
    <groupId>org.primefaces</groupId>
    <artifactId>primefaces</artifactId>
    <packaging>jar</packaging>
    <version>4.0-DEBUG</version>
    <name>primefaces</name>
    <url>http://www.primefaces.org</url>
PrimeFaces uses a maven plugin to generate the JSF components and configuration files. 
This plugin is located in the PrimeFaces maven repository which you must include into the pom file. Otherwise the build will fail.
    <pluginRepositories>
        <pluginRepository>
            <id>primeFaces_repository</id>
            <url>http://repository.primefaces.org/</url>
        </pluginRepository>
    </pluginRepositories>
When you now execute the mvn install command, you will have a customized version of PrimeFaces in your local Maven repository which contains the non minified version of JavaScript.

Using this version in your project, by specifying it in a profile so that it doesn’t go into production, you can do debugging in your favourite browser.

Conclusion

We following the above steps, you have a custom version of PrimeFaces where the JavaScript is not minified and thus can be debugged in the browser. Of course it is not suited to go to production with this version.