Showing posts with label ExtVal. Show all posts
Showing posts with label ExtVal. 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.

Thursday, 20 October 2011

Custom reference resolver tutorial

Introduction


In the previous blog text, I described the cross field validation feature of ExtVal. In the meantime, the reference resolver add-on is released and this text shows how you can write your custom reference resolver.
And since the usage of the add-on API is easy, we are aiming a little bit higher with our example as a simple hello world. I'll explain you how you can write a resolver that checks a value stored in an MBean object.

Coding it

The reference resolver api is described here in the project documentation. There is just one method that you need to implement, resolveReference. The first parameter contains the string defined in the value attribute of the annotation (or method is repeatedly called for each string defined in the case of multiple values)


ReferencedValue resolveReference(final String targetValue, final MetaDataEntry metadataEntry);
So, first we have to 'invent' our indication how we will describe the property of the MBean where the value is stored. A possibility is using mbean@property where mbean is just the name in a certain node of our MBean server.

Our implementation of the method needs to do 3 things

  1. Get a reference to the MBean server of our environment
  2. Split the parameter in 2 parts (around the @ sign)
  3. Lookup the MBean and retrieve the value of the specified property.
If you aren't familiar with accessing JMX beans, you can find various documents on internet which explain it in detail. For this example, you can have a look at the source code placed in an apache extra repository (link). The implementation of our resolver is in the class org.os890.extval.addon.demo.resolver.MBeanReferenceResolver.

Before we can use this new resolver, we have to define a validationParameter so that we are able to use it in the cross field annotations of ExtVal. It is described in the add-on documentation on the referenceResolver page.

In our case, it results in:

public class MBeanReferenceResolver implements ReferenceResolver
{
    public interface MBeanReferenceResolverParameter extends ValidationParameter
    {
       @ParameterKey
       public Class KEY = ReferenceResolver.class;

       @ParameterValue
        public Class referenceResolverClass = MBeanReferenceResolver.class;
    }

     @Override
      public ReferencedValue resolveReference(String targetValue, MetaDataEntry metadataEntry)
      {
         // Implementation details omitted
       }
}
Now we can use this resolver in all cross field annotations like @Equals. In the example you can find a usage in the class org.os890.extval.addon.demo.view.BackingBean.

@Equals(value = "demo@TargetValue", parameters = MBeanReferenceResolver.MBeanReferenceResolverParameter.class)
private String source;
This property is linked to an inputField on a screen in the example.

Testing it

Now we are ready to run the example. If we press the 'Submit' button, a comparison will be made between the entered value and the value which is by default set in the MBean, which is 'ExtVal'. If they don't match, you see the message that the input is different.

This default value is set by the class org.os890.extval.addon.demo.startup.MBeanResolverStartupListener which is defined as JSF PhaseListener in the faces config file.

The following steps makes this example interesting. You can start up the default JMX console of your environment (look for the JConsole program) or any other JMX console that is able to connect to your (application) server. You will find between all the other MBeans, the one created by the demo application in the org.os890.extval.reference.addon node. It is called demo. The property TargetValue can be changed to another value, let's say 'Test'. If you now go back to your browser you will see that the comparison now only succeed with the new value 'Test' that you have entered in the JMX bean.

Conclusion
 This example shows how easy it is to create a new reference resolver and integrate it in ExtVal.  With the add-on you can create any reference you like that needs to be used by the cross field validation feature of ExtVal.

Sunday, 9 October 2011

Announce: Reference Resolver add-on for ExtVal


The Reference Resolver add-on for MyFaces Extensions Validator project adds the possibility to define your own reference resolver for the cross field validation option. See my previous text for some intro about cross field validation.

By default, the Apache commons JEXL engine is used to resolve the references which are defined. This allows the definition of very powerful references and in the same time keep backwards compatibility with the standard resolving of ExtVal.
The egine allowed me to create a feature which I called dynamic references.  These nested expressions allows to have EL expressions that are defined at runtime.

The documentation of the add-on can be found here.
The source code is put on bitbucket with the rest of the ExtVal add-ons.
The add-on is available as maven dependency in the os890-m2-repository project of google code.
<repository>
   <id>os890.googlecode.com</id>
   <url>svn:http://os890-m2-repository.googlecode.com/svn/trunk/os890</url>
</repository>
You can find examples in the integration test project in the source code and soon I'll post here an example of using MBeans as validation target.

Have fun with it.


Thursday, 15 September 2011

Cross field validation with JSF and ExtVal

Introduction
JSF has support for validation built in, but it is limited to a single field. Is it required, is it in the correct range, has it the correct format and so on.

With the MyFaces Extensions Validator framework (ExtVal in short), there is support for cross field validation. You can verify if two fields have the same or different content. Check the relative order of two dates and so on. For the feature we need 2 fields we can compare and this is done by specifying a reference in the annotation on one field to the other field.

And although the current possibilities to specify the other field are sufficient in 99% of your cases, I was already thinking about a mechanism for two years that allows greater flexibility and easier custom implementations.

ReferenceResolver
And since I now have almost completed the Reference Resolver add-on for ExtVal, the time has come to start blogging about the possibilities.

The add-on introduces an interface, the ReferenceResolver, when it comes to resolving the references to the other field in ExtVal. This allows the developer to implement any kind of reference he like. But since the default ExtVal functionality is enough in 99% of the cases, the requirement of the add-on was that it should recognize and correctly evaluates the current system. Backwards compatibility was in this case a requirement.

The Apache Commons JEXL project proved to be the ideal candidate. With some extensions, it correctly handles the default references of ExtVal and allowed some advanced references out of the box.

Cross field validation overview
But the details of the add-on will be explained in the next blog entry/entries I'll make. First I need to explain some concepts of the cross field validation of ExtVal before I can continue with the explanation of the add-on.

So the rest of this blog entry will only explain the default functionality and concepts of ExtVal. You don't need the add-on for this.

An example makes it more clear.

-- Managed Bean
@ManagedBean(name="bean")
@RequestScoped
public class ClassicGrammarBean {

     @Equals(value = "target")
     private String source;

     private String target;

     // setters and getters omitted
}

-- screen

<h:inputText id="source" value="#{bean.source}" label="source"/>
<h:inputText id="target" value="#{bean.target}" label="target"/>

If you use the above code, posting the screen will result in an error except when the contents in the 2 fields are the same.

How does it work? ExtVal installs a proxy for each renderer defined in the JSF system. That way, it can perform some action anytime there is a decode or encode request. One of the actions is that after the standard decode method is called, the value is 'verified' against the annotations that are present on the property in the managed bean to which the field is linked.

How is cross field validation then implemented? Another action which is performed after the decode, is that the value is stored by the ProcessedInformationRecorder for later usage. After the JSF validation lifecycle phase, there is a check for any cross field annotations on the properties used in the screen. If so, the required checks are performed based on the values stored by the ProcessedInformationRecorder. Later on I'll make some comments on this principle.

Reference methods
There are 2 options to refer to the other field that is needed in the cross field validation. One is based on EL expression, but first I'll explain the other one.

local reference (javaBean reference)
The example which is presented earlier in this text, is an example of the local reference type. In the value attribute of the annotation, we specify the property name of the other property we like to use in our comparison. Besides the referring to other simple properties (like target in the example) we can reference properties in another class as long as the object is a local property in the bean.

As always, the example makes it very clear what I mean.

public class SubBean {
     private String targetInSub;

     // setter and getter omitted
}

@ManagedBean(name="bean")
@RequestScoped
public class ClassicGrammarBean {

     @Equals(value = "subBean.targetInSub")
     private String source;

     private SubBean subBean;

     // setters and getters ommitted
}

But not all kind of java references are supported. Besides the above 2 example, the map notation is also supported. But only with a fixed key value, a literal and not a reference to another property. The contents in the value attribute of the annotation then looks like mapProperty.key where key is the string literal of the map key.

EL reference
The El references are more common because we all use them in the JSF pages. But the disadvantage is that the bean name is placed in a string attribute of the annotation. Changing the bean name will break your validation rules, which isn't the case if you can use the local reference method. But there you have the problems when you rename the properties of the bean.

Validation mode
Knowing the possible reference methods isn't enough to understand how the cross field validation works. You basically point to 2 properties of objects but the values aren't yet pushed into them. This is done in the update model phase of the JSF lifecycle which comes after the validation phase.

A very important piece of the cross field functionality is the matching of the EL references used in the JSF pages to link a component to a managed bean property and the reference specified in the attribute of the annotations.

In the case the reference of the annotation couldn't be matched to a value found in the current request, the reference is evaluated and the value stored in the model, the managed bean property in this case, is taken. This is called the model validation mode.

Conclusion
The new Reference Resolver add-on for ExtVal makes it possible to reference any kind of other value for the cross field validation functionality of ExtVal. If you have exotic requirement regarding the other party in the validation rule, you can implement them yourself using the ReferenceResolver interface.

And by default, by using the fine JEXL engine, the backward compatibility is guaranteed and opens the gate for very complex references.

In the next blog entry I'll explain how you can use the value of an MBean in the cross field validation with the new add-on.

Monday, 29 November 2010

Myfaces Extensions Validator release 4

With the latest release of the ExtVal framework, release 4, there are a few new major features and a lot of small improvements. And if you are using JSF 2.0, you definitely should upgrade to this version due to his improved integration.
Here is a list of the main features :

  1. Mapped constraint source

    It allows you to, for example, specify that the DTO classes must use the same validations as defined on the entity object. Without the need to copy those validations (DRY - Don't repeat yourself, see also here)
  2. Type safe configuration through Java API

    Until now, the configuration of the framework, if you needed to change something, could be done by specifying configuration parameters within web.xml. Now, it is also possible to specify them in Java through the StartupListener mechanism in a type-safe way. No longer typo errors.
  3. Improved integration with various frameworks

    There is now support for the @Valid annotation of bean validation, Integration with CDI (by using CODI, here) and the scripting framework (JSR 223)
  4. Performance

    There is also some major performance improvements achieved, so the overhead becomes of ExtVal becomes minimal.
  5. New and improved annotations

    There is a new @EmptyIf annotation, the reverse of the already existing @RequiredIf, and some improvement to the already existing ones like a case insensitive comparison.
  6. New add-ons

    There are 2 new major add-ons available that offer some nice functionality. It is the multi field Bean Validation and the required label add-on.
  7. There is also some effort done in better project documentation through the javadocs and a new wiki area.
See for a more complete overview

Thursday, 4 November 2010

Required field indication with ExtVal - Part 1

Introduction
By using the MyFaces extension Validation framework, ExtVal called in short, we are able to create powerful validation rules that can be used in JSF. Validation rules are no longer encoded in the view layer, the JSP or the XHTML files, but defined by placing annotations on the model and backing bean classes. And that is also where they belong, since validation is linked to the data and not the representation we happen to have or like.

But with ExtVal, we can no longer use the custom renderers we have to indicate that a field is required. Without ExtVal, is was common to have a custom renderer that looked at the required property of the field and allowed us to have some indication that the field is required. That could be a style class that changes the appearance (a yellow background on the field) or some character like an asterisk by the label that goes with the field. Such custom renderers no longer work by default, since the
components in the tree have no longer indications of the validations that are needed.