Showing posts with label Java EE 6. Show all posts
Showing posts with label Java EE 6. Show all posts

Monday, 4 May 2015

Introducing Jerry and Valerie

Or the JSF renderer interceptor and the (bean) validation extension.

A major new version is available under the Atbash umbrella: http://www.atbash.be/2018/02/26/a-renderer-interceptor-concept-for-java-serverfaces/

Introduction

The first opensource project where I ever posted a change to, was Apache MyFaces Extension Validation, ExtVal in short. It is a framework for having a validation platform with many great features.

But the last few years, I only used a few specific parts of the platform with some of my own extensions.
Since ExtVal was designed for JSF 1.x and later extended to JSF 2.x, I decided to recreate it.  CDI the cornerstone in every aspect of the version and geared towards JSF 2.x and Bean Validation.
But if you like, you can still create all the features from ExtVal in the new version.

Jerry

One of the features of ExtVal that I use a lot, is the JSF Renderer interceptor around which the complete platform is built. The idea is very simple, during registration of the renderers at startup, they are wrapped with a custom class.
This allows to have a before and after of all the important steps of a rendering; decode phase, encode begin, encode children, encode end and converted value.

This very simple concept has many possibilities. For example, you want to indicate every required input field with a special background colour.  These are the step that you need to do

1- Add Jerry to your maven project
<dependency>
   <groupId>be.rubus.web</groupId>
   <artifactId>jerry</artifactId>
   <version>${jerry.version}</version>
</dependency>

2- Define a ComponentInitializer, this is a specific renderer interceptor which can perform some actions in the before encode begin step.

@ApplicationScoped
public class RequiredInitializer implements ComponentInitializer {
   @Override
   public void configureComponent(FacesContext facesContext, UIComponent uiComponent, Map<String, Object> metaData) {
      InputText inputText = (InputText) uiComponent;

      if (inputText.isRequired()) {
         String style = inputText.getStyle();
         if (style == null) {
            style = "";
         }
         inputText.setStyle(style + " background-color: #B04A4A;");

      }
   }

   @Override
   public boolean isSupportedComponent(UIComponent uiComponent) {
      return uiComponent instanceof InputText;
   }
}

The above code adds the background colour to every PrimeFaces input text field.  This class is found using CDI mechanisms, and that is the reason why we have to annotate it with ApplicationScoped.  But it gives us also the possibility to inject any other CDI bean into this initialiser method.

Jerry is used in the Java EE declarative permission security framework Octopus to handle the security on the JSF component level.

Valerie

Another thing which I always find a bit annoying is that you should redefine the maximum length of a field at the JSF component level, although you have defined a Bean validation constraint on the java property.

For example, suppose you have a property for the name of a person

@Size(max = 50)
private String name;

When you have a JSF input field component pointing to to this property

<h:inputText value="#{personBean.name}"/>

then, the size restriction is checked during the validation phase. But why do you let the user input a longer then allowed value? So you have to use the size attribute on the h:inputText but it should go automatically, no.

That is where Valerie comes into the scene, another extraction from the ExtVal framework. 

side note; How the names are chosen. Jerry was chosen as it sounds phonetic like JRI (JSF Renderer Interceptor) So, I needed a female name to go alone with it and it should be related to validation.

So how can we have in the above example the size restriction from the bean validation property size on the screen?

The only thing you need to do is add the Valerie dependency to your project.  

<dependency>
   <groupId>be.rubus.web</groupId>
   <artifactId>valerie</artifactId>
   <version>${valerie.version}</version>
</dependency>

One renderer interceptor is responsible for retrieving and interpretation of the annotation information. A component initialiser then modifies the JSF component by specifying the size attribute from that info.

Conclusion

Jerry and Valerie are 2 small libraries extracted from the ExtVal framework.  They are centered around the JSF renderer interceptor and the extraction of bean validation information and gives you some handy features which makes your application easier to maintain.

The current version is 0.2, but since they have a firm solid history within ExtVal and are already used in a few projects, they are ready to use.  In the near future there will be some small features added and some more testing will be done before a first final version will be released.

They can be used in any Java EE 6 or Java EE 7 server (or servlet container if JSF, CDI and bean validation are present) and compiled with Java SE 6.

The basic documentation of the project can be found here and feedback, issues, feature request are welcome at the issue tracker on gitHub.

Maven artefacts are available in the C4J OpenSource Nexus 
<url>http://nexus-osc4j.rhcloud.com/content/groups/public/</url>
Have fun with it.

Sunday, 6 January 2013

DeltaSpike JSF message system

Introduction

One of the main aspects of the Java EE 6 version was type safety. With the introduction of CDI, there are many tasks that can be done in a type safe way, with no needs of Strings anymore.
This improves the quality of the code since it reduces the chance of typo errors. During compilation, you can be warned of your mistake.
DeltaSpike is a CDI extension that combines all the goodies of the Apache CODI and SEAM 3 frameworks. It is a work in progress and lately the work on some JSF goodies is started.
In this text, I want to explain the message feature of DeltaSpike. And although there is still some String handling required, at least it makes it very flexible and extensible.  This is not the case with the default JSF functionality.

Getting started

The message feature is based on some advanced features of CDI where we can define our message as methods in an interface where no implementation is needed. Lets explain this based on the classic Hello world style example.
So we start with an interface that we annotate with MessageBundle

@MessageBundle
public interface ApplicationMessages
{
    String helloWorld(String name);
}
In a managed bean/controller we can inject then the message component and ask for the text linked with the message.  This is an example of a managed bean using the JsfMessage.

@Named
@RequestScoped
public class ControllerView
{
    private String name;
    @Inject
    private JsfMessage msg;
    public void doGreeting()
    {
        msg.addInfo().helloWorld(name);
    }
}

In the typical Hello world style where there is an input field on the screen linked with the name property and a button linked to the doGreeting method, the above code shows a JSF Info message on the screen.

JsfMessage is also an interface and can take only as type parameter an interface which is annotated with MessageBundle such as in our example above.
On the JsfMessage interface there are methods available to add a message to the JSF Message system with a certain severity, like info in our example, add the message for a certain component or just get the text of the message, without adding it.

The default implementation takes care of looking up the correct locale, message text and assembles the resulting String.

It isn't CDI as it wasn't customizable and extensible. But before we look at the possibilities, I have to explain first where, by default, it looks for the text definition.

In the above example, a resource bundle ApplicationMessages in the same directory as the package of the interface is interrogated for the key helloWorld.
So by default, it looks in the same directory for a key which equals the method name.
 
helloWorld=Welcome %s

Also pay attention on how you need to specify the place of the parameter in the text.  The default version uses the String#format() method which requires the %-character as placeholder indicator.  This is different from the standard JSF where we used the {0} type of placeholder.

But this can be customized by the MessageInterpolator but first try some easy configuration options.

Configuration options

In the previous section, we used the JsfMessage feature in his most basic format.  We used all the default settings and implementations.  In this section, I'll explain how you can customize the ResourceBundle and the key which will be used.

On the methods, we can place the MessageTemplate annotation.  With this annotation we can specify the key or the entire text which will be used. In case it is a key in the resource bundle, we need to wrap it inside {} characters as you can see in the example below.
The second customization is the ResourceBundle name which will be searched, in addition to the default one. It can be specified by the MessageContextConfig#messageSource member.

As you noticed in my wording, it defines additional ResourceBundles, so be careful if you define multiple candidates where the resource key can be found.

@MessageBundle
@MessageContextConfig(messageSource = {"org.apache.deltaspike.example.message.ApplicationMessages" }) 
public interface CustomizedMessages
{
    @MessageTemplate(value = "{nowMessage}")
    String getTimestampMessage(Date now);
}

When we use the above code, we look for a key nowMessage in the ApplicationMessages ResourceBundle. Without the curly brackets, the text itself would be used without looking up a ResourceBundle.

Pay attention to the typos in the messageSource member. When you specify a non existing ResourceBundle, you don’t get a warning or error and of course, the text won’t be displayed correctly.

Customizing individual MessageBundles

With the MessageContextConfig annotation, when can also customize other functionality of the Message system. In this section I'll explain how you can change the MessageInterpolator back to the standard JSF version.

The MessageFormatMessageInterpolator class uses the java.text.MessageFormat to replace the placeholders in the string with the arguments as we are used too. The class implements the interpolate method from the MessageInterpolator interface.

The Custom annotation is a CDI qualifier that I created and is required before the example can work.  I'll explain in a moment the reason for this.

@Custom
public class MessageFormatMessageInterpolator implements MessageInterpolator
{
    @Override
    public String interpolate(String messageText, Serializable[] arguments, Locale locale)
    {
        return MessageFormat.format(messageText, arguments);
    }
}

As already mentioned, with the MessageContextConfig annotation we can decide to use this MessageInterpolator on certain MessageBundles like this

@MessageBundle
@MessageContextConfig(messageInterpolator = MessageFormatMessageInterpolator.class)
public interface CustomizedMessages
{

Why do we need a CDI qualifier on our implementation?  We are not using it for injection, we refer to it by its class name!  Since the default implementation is also available in the Bean archive, the CDI container has 2 implementations available and don't know which one to choose when he needs to inject a MessageInterpolator into the default JsfMessage implementation.

So without the qualifier, our application will fail during deployment with an ambiguous dependency error.

So it is easier and probably also much more useful to replace the default implementation with your version.  This is explained in the next section.

Replace default implementation

In the previous section we changed the behavior for one MessageBundle.  But most of the time, we need to change the default implementation and don't want to specify this for each MessageBundle we create in our application.

As an example, I'll show you how you can define that the message bundle in the Faces config file is also used when a resource key is searched in the ResourceBundles.

@Specializes
public class CustomMessageResolver extends DefaultMessageResolver
{
    @Override
    public String getMessage(MessageContext messageContext, String messageTemplate, String category)
    {
        addMessageBundleFromFacesConfig(messageContext);
        return super.getMessage(messageContext, messageTemplate, category);
    }
    private void addMessageBundleFromFacesConfig(MessageContext someMessageContext)
    {
        String messageBundle = FacesContext.getCurrentInstance().getApplication().getMessageBundle();
        if (messageBundle != null && messageBundle.length() > 0)
        {
            someMessageContext.messageSource(messageBundle);
        }
    }
}

For this, we need to override the DefaultMessageResolver and intercept the call to the getMessage method.  This is the only method in the MessageResolver interface and is responsible for looking up the resource key in resource bundles.  But custom implementation can be written to look up the message text in a database system for example.

Here we use the CDI specilization functionality.  When we annotate an extended CDI bean with Specializes, CDI will use our version, the CustomMessageResolver, in all the cases where DefaultMessageResolver would be used.  Without the need of a CDI qualifier and without the issue of having an ambiguous dependency error.

In our extension of the default functionality, we look in the faces configuration to see if there is a MessageBundle defined.  If so, we add it to the list of messageSources maintained and searched to find the requested message.

The same procedure can be used to define a custom MessageInterpolator and LocaleResolver, dedicated to find the language in which the message text must be returned.

Plain message text

In the hello World example at the beginning of the text, we used the JsfMessage DeltaSpike functionality to add a JSF message.  We can also ask for the text without the need to show it as a JSF Message.
The JsfMessage interface has the get() method for this purpose.  The following snippet could be used to display the current time as text on the screen with #{bean.now}

    public String getNow()
    {
        return custom.get().getTimestampMessage(new Date());
    }

Conclusion

There is no type safety, which is popular in Java EE6, with the JsfMessage feature of DeltaSpike because you always need to specify somehow the resource key that needs to be used when the text is looked up.  But you have a flexible and extensible system that is much more readable due to the builder like pattern.
The JsfMessage feature is currently (begin January 2013) under development in the 0.4-INCUBATING version and the code can be found here.
In the JsfExample module you can find the examples described in this text.

Monday, 10 December 2012

Java EE6 as the universal backend

Introduction

Java EE6 is referred to by many people to be the most easy, productive, lightweight and best version of the enterprise environment. As a developer you can concentrate on the business logic and you don't have to spend time on the infrastructure side of the application.
Since J2EE 1.4, they made great efforts for simplifying the creation of Enterprise applications.  With the principles of 'convention over configuration', intelligent defaults and the usage of annotations, you can create EJB's or REST style webservices in minutes.
Due to the lightweight aspect of the current application servers, like JBoss AS 7 starts up in 7 seconds, you can have short development cycles where you can quickly test your new code.
In addition to these developments in the standard, there are other great initiatives which makes the Java EE 6 environment very attractive.
  • You have the Arquillian framework which gives the term testing a complete new dimension.  As it is a container-oriented testing framework, it allows you to execute integration tests in a real container as if it were unit tests.  Since they are portable, you can test for cross container compatibility of your application.
  • Another great framework is MyFaces CODI, a CDI extension, which is currently integrated with JBoss Seam3 into Apache DeltaSpike. It unleashes the power of the CDI framework and enables you to use Dependency Injection in radical new ways.
  • A third initiative I want to mention here is PrimeFaces. The PrimeFaces JSF components became very popular with JSF 2. They allow you to create powerful modern Rich Internet Application and yet keep the component library easy to use.

All on Java EE 6

In October, I had the privilege to give a course and presentation together with Çagatay Çivici, project lead of PrimeFaces project. During my presentation I showed a few cases where you can use the Java EE 6 environment as backend for your applications.
In that week, PrimeUI was first announced. And it made my realize that my story about the Java EE 6 environment could be extended even further. There was yet another type of applications that I could add to the picture.
So here is a short overview of the types of applications that are possible with Java EE 6
  1. JavaServer Faces
    This is the most obvious type of applications since JSF is part of the Java EE 6 specification.  But due to the nature of the framework, it is best suited for administrative applications which run in the browser of the desktop. With his component based nature and the standard facilities for conversion and validation, it makes it excellent for handling user input.
    However it requires some state kept in the session memory of the user. And although they have made quit some improvements in the JSF 2.x versions, it isn't the best choice for high volume websites.
  2. Mobile apps
    With the popularity of smartphones, there is a whole new market emerged that creates applications for the mobile devices.  They are native apps, running on the device itself and can access the services of the device easily.  But most of them also need data that are supplied from an external source, mostly in JSON format.
    With the JAX-RS component of Java EE 6, you can create easily some restful services that, annotated correctly, supply the caller the requested data in JSON format or take some data in. By just adding the @Path annotation to a CDI or EJB bean, you have created a restful services endpoint. This allows you to reuse your knowledge (and even functionality if needed) and support your native application quickly.
  3. Browser based mobile application
    The downside for mobile applications is the fact that you need to learn, or use, a specific language, like Objective C, and that your application is not compatible between all the type of devices.  With PrimeFaces Mobile, based on JQuery Mobile, you can create web applications that run in the browser of the mobile device but has the look and feel of a native app.
    PrimeFaces Mobile is just a component library, so it can be used easily by someone that knows JSF. And of course, here you can also use the complete power and functionality of the Java EE 6 stack.
These type of applications where presented during my presentation and can be summarized in the following picture.
Universal_Java_EE6_Backend

But don't focus on the database in the picture, in the demos I also used Hazelcast as a NoSQL solution and integrated it with CDI.

StatelessPrime

The fourth option in the picture is something I'm experimenting with since October. With PrimeUI, the widgets of the PrimeFaces component library will be available as a JavaScript version.  As communication, JSON data will be used. So why not using Java EE 6 stack then?


That is how the idea of StatelessPrime was born.  Creating stateless Web applications with HTML5, CSS, JavaScript and PrimeUI on the client side and Java EE 6 with the JAX RS module that does the communication in JSON format on the server side.
But the idea goes further. Is it possible to create a component library that allows some kind of compiler to generate the HTML5, JavaScript and JAX RS classes?  That way you can reuse your JSF and CDI knowledge to rapidly create stateless web applications.

You can follow my experiments on the StatelessPrime blog.