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.

Saturday, 13 August 2011

Some corner cases of cross field validation with the ExtVal framework

Introduction

ExtVal has the ability to perform some cross field validations. An example is the check if two fields have the same content or to verify the relation between two dates (is one date 'before' the other). Besides the standard field validation and the object validation, it is the third way of performing validations. The advantage of the cross field validation is that the update model phase isn't required to have all the values to perform the validation. Due to the ProcessedInformationRecorder concept, the framework can record all values entered in the screen during the model validation phase. And then in a PhaseListener, these values can be used to perform the cross field validation.
This text explains what happens when you use some more exotic expressions.

No managed bean

We all use a managed bean and his properties to store the values of the inputText tags as follows

<h:inputText value="#{bean.source}" label="source" id="source"/>
 
But this isn't the only way how we can define the associated property for an input tag. Suppose you define in the faces-config file a String value under a certain name, then you can use it as attribute value. Is it useful? Certainly, imagine the case that you ask for a password and the retyped password to be certain the user hasn't made a type error. But we aren't interested in the retyped password value; we only need to know if it is equals to the other typed value.
So we can created something like this


-- faces-config
    <managed-bean>
        <managed-bean-name>StringVal</managed-bean-name>
        <managed-bean-class>java.lang.String</managed-bean-class>
        <managed-bean-scope>request</managed-bean-scope>
    </managed-bean> 

-- bean
    @Equals(value = "#{StringVal}")
    private String password;

-- screen
  password <h:inputText value="#{bean.password}" label="password" id="password"/>
  Retype <h:inputText value="#{StringVal}" label="retype" id="retype"/>

If you try this, you receive the message that the values are different, also when you put the same value in the fields. The cause for this behavior is that the cross field validation isn't implemented with this kind of usage in mind.

The cross field validation functionality supposes that the EL you have specified, contains always at least a base object and a property. It doesn't recognize that the same EL is used on the field, and thus during validation, the #{StringVal} is evaluated and not the screen value is taken. But the EL expression evaluates always to null, resulting in a difference in all cases. But there is a solution for this situation. You can place the bean scope in the EL expression. When you write #{requestScope.StringVal} in the managed bean (within the Equals annotation) and in the screen, the code behaves as expected. By the way, adding the bean scope is resulting in a better performance when the EL expression is resolved.
 

Model aware version

The cross field validation feature can use the entered value in the screen, but there is also a model aware version. In that case, the EL is evaluated when the system sees that the same expression isn't used on some inputText decoded in the same request. In this situation, the bean scope isn't required to be specified.
 

This is a possible use case: when we have defined in the faces-config a bean of type Date with the name startDate. It can contain some date, initialized by some mechanism that is used to mark the oldest date possible for a period. When the user enters a date in the screen, we can verify it is later then the value in the faces-config defined value. Here we don't need to specify the bean scope, although it is allowed.
 


-- faces-config
    <managed-bean>
        <managed-bean-name>startDate</managed-bean-name>
        <managed-bean-class>java.util.Date</managed-bean-class>
        <managed-bean-scope>application</managed-bean-scope>
    </managed-bean> 

-- bean
    @DateIs(valueOf = "#{startDate}", type = DateIsType.after)
    private Date beginDate;

-- screen
  Begin date <h:inputText value="#{bean.beginDate}" label="Begin date" id="beginDate"/> <br/>

Methods with unified expression language
 

With the Unified Expression Language, you can specify method calls in EL with (or without) parameters on containers that support EL 2.2. But these constructs can't be used in the value attribute of an input field.

<h:inputText value="#{methodBean.doMethod()}" label="method" id="method"/> <br/>

The above construct shows the return value of the method when the screen is presented. But when submitting the page, you receive an exception (from JSF, not from ExtVal) saying that it can't find the property doMethod. After all, it searches a method setDoMethod with a single parameter.
 

Now we can continue our theoretical example to see how far we can go. If we do create that required method (and you have a use case in which you can set the value on the same place then you retrieved it with the doMethod), how should the expression that we put in the ExtVal annotation look like?
 


    @Equals(value = "#{methodBean.doMethod()}")
    private String source;


This format isn't working, because the ProcessedInformationRecorder can't understand method constructs in EL. So the cross field validation performs the model variant, but doesn't see the newly typed text on the screen. And without the brackets, it interprets it as a property and looks for the method getDoMethod.
So is this an issue of ExtVal? I don't think it because I never encountered a possible use case that requires an EL method expression in an inputText tag.
Can't we use then the new features of the Unified Expression Language? Yes it is possible, as we already mentioned in the previous section. If the container supports the UEL, ExtVal uses the result of the expression to compare it to the screen entered value.
 

Conclusion
 

I have presented here some rare use cases of cross field validation and how ExtVal reacts on them. As we saw, the feature can be used without the usage of a managed bean, as long as we specify the bean scope. And with the newly introduced method expressions in UEL, you are able to use it in the model aware variant. And thus can be used to retrieve the value from other resources like JNDI. But with the upcoming new add-on, it will be easier since you have the pluggable reference resolver for the cross field validation.

Have fun with ExtVal

Thursday, 26 May 2011

Browser compatibility with Webdriver

Introduction

With selenium web driver you can write very powerful test scenarios
for your web application. The idea is that all applications need at some
point a kind of integration testing where you can see the application in
action on your screen. In the end, the whole goal of your development
effort is the web application running in your browser (if you are
developing a web application, of course). With the Selenium webdriver you
can control the browser interaction, like clicking on links and filling in
fields, from within the java code itself, there is no need any more for the
javascript scripts of selenium RC.

Beside the fact you need to know that your application works as
specified in the requirements, it is also important to know it will run in
more than one browser. This text explains how you can easily run the same
test in different browsers.

Wednesday, 30 March 2011

CDI Specializes

Introduction

CDI is what I call a modern specification / framework. The emphasis
is placed on a few concepts and their usage and not on a limited list of
functionalities that should be implemented and covered. And it is easy to
extend it or change a few internal implementations. In the specification,
there is explicitly noted that portable extensions should be possible. The
most known extensions at this moment are CODI, maintained by the MyFaces
project, and Seam 3, the JBoss lead project.

And the specializes in the title could refer to this; a blog entry
about the additional functionalities that can be found in CODI and Seam 3
on top of the standard. Because, once you are familiar with the concepts,
you have a complete new set of tools at hand to handle dependencies and
managed beans in a type safe way. And those two projects have defined for
you some very common additions that you will use very often.

But the goal of this text is different. I'll try to explain you one
of the concepts in CDI offered by the annotation
javax.enterprise.inject.Specializes. The goodies of those CDI extensions
might be a subject of another entry. In the mean time, you can read their
documentation on how to use the provided functionality.

Thursday, 10 March 2011

JSF Security

Introduction

Securing parts of the view of a JSF application is mostly done by
calling some backing bean methods in the rendered attribute of the
components. And although it works, it isn't optimal. Security is one of
those cross-cutting concerns of applications, like logging, and one should
try to give it his own seperate place in the application. It is obvious
linked to the rest of the application but it shouldn't be mixed with the
other code like business rules.