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.

Wednesday, 25 September 2013

Generic JPA 2.1 converter for enum

Introduction

Until now, an enum value could be stored in the database by its ordinal number or his name in JPA. When you have a ‘legacy’ database or when you are doing refactorings you could be in trouble.  The only option then was to rely on the implementation to allow a custom value as the representation of the numeration in the database.
In the latest release of JPA, 2.1, there is support for custom converters so you can solve these kind of issues.

JPA 2 Converter

What do you need to do to have a custom converter? The enumeration class doesn’t need any change. In the entity were you use the enum, you need to specify the converter you like to use, like this:
@Entity
public class Person {
...

  @Column
  @Convert(converter = GenderEnumConverter.class)
  private Gender gender;
...
}

The converter class can look as this
@Converter
public class GenderEnumConverter implements AttributeConverter< Gender, String> {

  @Override
  public String convertToDatabaseColumn(Gender attribute) {
    String result = "";
    switch (attribute) {

      case MALE:
        result = "M";
        break;
      case FEMALE:
        result = "F";
        break;
      default:
    }
    return result;
  }

  @Override
  public Gender convertToEntityAttribute(String dbData) {
    Gender result = null;
    switch (dbData) {
      case "M":
        result = Gender.MALE;
        break;
      case "F":
        result = Gender.FEMALE;
        break;
      default:
    }
    return result;
  }
}

And the last thing you need to do is to ‘register’ the converter with JPA as no scanning is performed of the available classes.  You can specify the class name, just as you specify the entity classes in the persistence.xml file.
<persistence-unit name="converter-unit" >
  <description>Forge Persistence Unit</description>

  <class>be.rubus.web.ee7.jpa.converter.model.Person</class>
  <class>be.rubus.web.ee7.jpa.converter.jpa.GenderEnumConverter</class>
</persistence-unit>

Not OO


The above code is not ideal in several ways. If you have an enum class with a lot of values, you have to write a large if-then-else structure which is not very OO like. And you also need to write a lot of similar code which wants me to search for a more generic solution.

If we could define the database value together with the enum value, it would be a great improvement. It makes the code also much more logic as you can define the database value together with the enum value.

Since we need such functionality for each numeration that we use in the persistent objects, we can create an interface like DatabaseEnum.
public interface DatabaseEnum {

  Serializable getDatabaseValue();

}

And change the enum to implement this interface.
public enum Gender implements DatabaseEnum  {
  MALE("M"), FEMALE("F");

  private Serializable databaseValue;

  Gender(Serializable databaseValue) {
    this.databaseValue = databaseValue;
  }

  public Serializable getDatabaseValue() {
    return databaseValue;
  }

}

This should allow us to create a generic converter for the enums, except that the Java compiler removes the information regarding the generic types, know as type erasure. Otherwise a converter like this could be possible.
@Converter
public class EnumConverter<T extends DatabaseEnum> implements AttributeConverter< T, Serializable> {

  @Override
  public Serializable convertToDatabaseColumn(T attribute) {
    return attribute.getDatabaseValue();
  }

  @Override
  public T convertToEntityAttribute(Serializable dbData) {
    // There is no way we can create such a method
    return determineEnum(T, dbData);
  }

}

If we would be able to define that a custom constructor needs to be called, where we supply as parameter the class T, we would get away with it.  But this is not the case.
public EnumConverter(Class<T> enumType) {..}

Almost generic converter


Based on the optimal code above, we are able to create a converter that uses a generic utility method.  It means that we still need to create a converter for each enum class we like to use, but the code is much cleaner then the first example we show in the text.
@Converter
public class GenderEnumConverter implements AttributeConverter<DatabaseEnum, Serializable> {

  @Override
  public Serializable convertToDatabaseColumn(DatabaseEnum attribute) {
    return attribute.getDatabaseValue();
  }

  @Override
  public Gender convertToEntityAttribute(Serializable dbData) {
    return DatabaseEnumUtil.getEnumValue(Gender.class, dbData);
  }
}

And the utility method can be small and generic thanks to the not very known method getEnumConstants() of the JVM core classes.
  public static <T extends DatabaseEnum> T getEnumValue(Class<T> enumClass, Serializable dbValue) {
    T result = null;
    if (dbValue != null) {

      for (DatabaseEnum enumInstance : enumClass.getEnumConstants()) {
        if (dbValue.equals(enumInstance.getDatabaseValue())) {
          result = (T) enumInstance;
          break;
        }
      }
    }
    return result;
  }

Conclusion


In the latest version of JPA, a custom converter can be defined which can be very handy in a lot of situations.  You can use it to create a converter for Joda-time classes or for specifying the database value of an enum value.

The only thing that keeps us from creating a generic converter for enums is the type erasure thing of Java. Otherwise we could create a beautiful converter for all our enums.

Monday, 5 August 2013

From CODI to DeltaSpike

Introduction

CODI is my favourite CDI extension framework where you can find all kind of goodies when you are working in a CDI environment.
Some time ago, there was a decision to create a new CDI extension framework which brings together all the good features of CODI and Seam 3 and other features from other CDI extension libraries.

They have gone through the incubation process at Apache and moving along steadily. The question is, can you already switch from CODI to DeltaSpike for an application?

Not all features of CODI are implemented but my 2 favourites ones are
- The additional scopes like ViewAccessScope
- The fluent API for adding FacesMessages.
So can we create a DeltaSpike application with these 2 features.

Scopes

In the current version of the DeltaSpike framework, version 0.4, there is no support for something like the CODI's ViewAccessScope .
Therefor, Gerhard Petracek created an extension for DeltaSpike to have the missing scopes from CODI version 1.0.5 into DeltaSpike. See here.
So adding the required dependency to the POM


<repositories>
 <repository>
  <id>os890</id>
  <name>Gerhard personal repository</name>
  <url>http://os890-m2-repository.googlecode.com/svn/tags/os890/</url>
  <layout>default</layout>
 </repository>
</repositories>

<dependency>
    <groupId>org.os890.cdi.ext.scope.modules</groupId>
    <artifactId>os890-cdi-ext-jsf2-module-impl</artifactId>
    <version>1.0.5_0.4_01</version>
    <scope>runtime</scope>
</dependency>



The version of the extension is a concatenation of the 2 libraries it will bridge. So we have the structure  &CODI version&_&DS version&_&extension version&.

You only have to use the new package name to have the additional CODI scopes.  The API is identical so that existing code which works for CODI, will also work with DeltaSpike.


So for example for ViewAccessScope,

import org.apache.myfaces.extensions.cdi.core.api.scope.conversation.ViewAccessScoped;

becomes 
import org.os890.cdi.ext.scope.api.scope.conversation.ViewAccessScoped;
So for any of the scope packages, you have to replace org.apache.myfaces.extensions.cdi.core with org.os890.cdi.ext.scope.

Messaging


The support for a fluent messaging API is already present in DeltaSpike. So to have this kind of functionality, we don't need to use an extension as we did for having the scopes.

But here we have the issue that the API is changed and thus we need to adapt existing code.

CODI version

messageContext.message().text("{msgKey}").add();

DeltaSpike version

Message defitions.
@MessageBundle
public interface AppMessages {
    @MessageTemplate("{msgKey}")
    String buttonClicked();
}

Within CDI bean
    @Inject
    private JsfMessage jsfMessage;

     
    public void addTestMsg(ActionEvent actionEvent) {
        jsfMessage.addInfo().buttonClicked();
    }


Servers

 The DeltaSpike application was tested successful on Glassfish 3.1.2.2 and JBoss as 7.1.1.Final.

Also the original CODI version was running without a problem on the new Glassfish 4 version.

On this server, the DeltaSpike version had a problem.  There was an exception thrown in the extension as there is no problem with the DeltaSpike code itself. All the integrations tests of DeltaSpike are running also on a Weld 2 version (used in the Glassfish 4) so you can expect that it is working on it without any problem.

With the new WLS 12C server, version 12.1.2, there is also an issue running the DeltaSpike application.   The application deployment fails during validation where it can't inject an Extension class into another bean.

Conclusion

With the help of the DeltaSpike extension, you can create already applications that uses a lot of the features of the CODI framework.
So check what features you need and maybe you can already create your application with the DeltaSpike framework.