Wednesday, May 8, 2013

Learning Play! Framework 2

I was sent a copy of the recently published book "Learning Play! Framework 2" from Packt Publishing. For the past couple of months I have been planning on experimenting with Play 2 and on building my own web application with this awesome framework but I have just been so busy with work that I haven't had the time or the energy to do anything about it. Now that I have this additional resource to help me get going I have even more motivation to spend time building this app of mine using Play!.


Thursday, September 8, 2011

Play Framework Cookbook


In my opinion the Play Framework is the most exciting framework to develop web applications using Java. I recently received a copy of the Play Framework Cookbook by Packt Publications I am looking forward in working my way through it.

I think Play's online documentation is pretty good although it probably is not as comprehensive as one would like it to be. It is this reason why I am very glad to see that another book as been published about the Play Framework.


Thursday, September 23, 2010

Apache ActiveMQ - integrated lightweight JNDI provider

I am testing an existing application that relies heavily on JMS message processing. For development I wanted to test outside of the container instead of running a server and deploying to it every time I made a change . After a quick search in Google I stumbled upon the JNDI Support reference page for Apache ActiveMQ. I have heard of it before but I have never used it.  

"ActiveMQ will work with any JNDI provider capable of storing Java objects. However it is common to require a JNDI initial context to be able to run many JMS example programs. So we provide a simple JNDI InitialContextFactory which can be used to lookup JMS connection factory objects as well as Destination objects."

I just tried it out now and it works like a charm. My day just got a whole lot better  :-) 


Wednesday, June 16, 2010

Group pattern matching with regular expressions in Java and Scala

Even though this has been around for some time I have only recently used it and think it is quite nice and worth blogging about.

The use case is pretty straight forward, you have a string of data and you want to extract values out of the string based on a pattern. An example would be a date “16-Jun-2010” and you want to extract the day, month and year. Another example could be an email address where you want to extract the username and domain. I will show you an example of extracting the day, month and year values from a string using regular expressions. Regular expressions allows us to match the format of the string as well as to group matches within the string so that we can get our day, month and year values.

Java
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class GroupCaptureEx {
  public static void main(String[] args) {
   String input = "16-Jun-2010";
   String patternStr = "(\\d{2})-([a-zA-Z]{3})-(\\d{4})";

   Pattern pattern = Pattern.compile(patternStr);
   Matcher matcher = pattern.matcher(input);
   if (matcher.find() && matcher.groupCount() == 3) {
      System.out.println("Day is: " + matcher.group(1));
      System.out.println("Month is: " + matcher.group(2));
      System.out.println("Year is: " + matcher.group(3));
    } else {
      System.out.println("No match found or unexpected match found");
    }
  }
}


The Scala version uses a Scala Regex class to simplify matters a little. It compiles the pattern by default so you don’t have to explicitly do that. It is also an Extractor which is used to extract the data you are looking for from the string based on the group matching and then to bind those values to the returned elements. The only thing we need to concern ourselves with is Scala’s pattern matching ability. The pattern we are interested in matching on would look like:

DateRegex(day, month, year)

We then use Scala’s match expression (similar to switch in Java) on the input string. If the pattern DateRegex(day, month, year) matches the string than we have a match

Scala
object RegExGroupCapture {
  def main(args : Array[String]) : Unit = {
    val Input = "16-Jun-2010"
    val DateRegex = """(\d{2})-([a-zA-Z]{3})-(\d{4})""".r
  
    Input match {
      case DateRegex(day, month, year) => {
        println("match found")
        println("Day: " + day)
        println("Month: " + month)
        println("Year: " + year)
      } case _ => println("No match found")
    }
  }
}

Thursday, June 3, 2010

Programming in Scala is fun

In learning more about what Scala can do I decided to work on the problems listed in the Project Euler website.

"Project Euler is a series of challenging mathematical/computer programming problems that will require more than just mathematical insights to solve. Although mathematics will help you arrive at elegant and efficient methods, the use of a computer and programming skills will be required to solve most problems."

I have only completed the first ten and have thoroughly enjoyed it. Not only have a learnt some neat tricks one can do with Scala I have also learnt about a number of different mathematical algorithms. At some point I would like to go back over some of the problems and see how one would do them in Java just to compare the difference between Java and Scala. I can only imagine it would be a lot less enjoyable and perhaps even a little painful.

Thursday, April 8, 2010

Spring Transactions - Sample Applications

Introduction
A while back I created four simple Java applications demonstrating Spring's transaction management implementation and recently thought it would be nice to share them. They may be too simple for most people but for someone new to Spring they may actually be helpful.

If you want to learn about transaction management in Spring then a good place to start is the Spring documentation and for the running examples you can download the spring-transactions-samples.zip Eclipse archive file. The four sample applications are broken down into four of Spring's transaction management abstractions, i.e.:
  • Declarative
    • XML
    • Annotations
  • Programmatic
    • TransactionTemplate
    • PlatformTransactionManager

In the examples that follow I have used the Spring DataSourceTransactionManager implementation as it is linked to a JDBC DataSource. I am using an in-memory database provided by HSQLDB and therefore don't have to do much except define configuration settings for the datasource in the Spring bean configuration file: 

transaction-test.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
 xsi:schemaLocation="http://www.springframework.org/schema/beans 
      http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
 
 <bean id="testDataSource" class="org.apache.commons.dbcp.BasicDataSource">
  <property name="driverClassName" value="org.hsqldb.jdbcDriver" />
  <property name="url" value="jdbc:hsqldb:testdb" />
  <property name="username" value="sa" />
  <property name="password" value="" />
 </bean>
 
 <bean id="transactionManager"
  class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
  <property name="dataSource" ref="testDataSource" />
 </bean>

</beans>

Declarative - XML
Declarative transaction management is the most common Spring implementation as it has the least impact on application code. The XML declarative approach configures the transaction attributes in a Spring bean configuration file. The sample application for this implementation can be found in the com.mydomain.spring.transaction.declarative.xml package. There are a few simple methods with different transaction settings configured to demonstrate some of the possible scenarios. I recommend running the sample application and viewing the logs to see what Spring prints out. 

xml-test.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
 xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx"
 xsi:schemaLocation="http://www.springframework.org/schema/beans 
      http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
      http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
          http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">

 <import resource="classpath:transaction-test.xml" />
 
 <bean id="transactionTestService" class="com.mydomain.spring.transaction.declarative.xml.XmlTransactionTestService" />

 <tx:advice id="txAdvice" transaction-manager="transactionManager">
  <tx:attributes>
   <tx:method name="readOnly*" read-only="true" />
   <tx:method name="*" />
  </tx:attributes>
 </tx:advice>

 <aop:config>
  <aop:pointcut id="xmlTransactionTestServiceOperation"
   expression="execution(* com.mydomain.spring.transaction.declarative.xml.XmlTransactionTestService.*(..))" />
  <aop:advisor advice-ref="txAdvice" pointcut-ref="xmlTransactionTestServiceOperation" />
 </aop:config>
</beans>

The <tx:advice/> definition makes the service object TransactionTestService bean transactional and defines all methods starting with 'readOnly' to execute in the context of a read-only transaction, and all other methods to execute with the default transaction semantics.

The <aop:config/> definition ensures that the transactional advice defined by the txAdvice bean executes at the appropriate points in the program.

The above configuration will be used to create a transactional proxy around the object that is created from the transactionTestService bean definition. The proxy will be configured with the transactional advice, so that when an appropriate method is invoked on the proxy, a transaction is started, suspended, marked as read-only, and so on, depending on the transaction configuration associated.

XmlTransactionTestService.java
public class XmlTransactionTestService implements TransactionTestService {
 private final static Log log = LogFactory.getLog(XmlTransactionTestService.class);
 
 public void readOnlyCommitExampleTransaction() {
  log.info("-- XmlTransactionTestService.readOnlyCommitExampleTransaction -- expects transaction commit and read-only");
  // do stuff
 }
 
 public void readOnlyRollbackExampleTransaction() {
  log.info("-- XmlTransactionTestService.readOnlyRollbackExampleTransaction -- expects transaction rollback and read-only");
  // do stuff
  throw new RuntimeException("readOnlyRollbackExampleTransaction Exception");
 }
 
 public void readWriteCommitExampleTransaction() {
  log.info("-- XmlTransactionTestService.readWriteCommitExampleTransaction -- expects transaction commit");
  // do stuff
 }
 
 public void readWriteRollbackExampleTransaction() {
  log.info("-- XmlTransactionTestService.readWriteRollbackExampleTransaction -- expects transaction rollback");
  // do stuff
  throw new RuntimeException("readWriteRollbackExampleTransaction Exception");
 }
}

When you run this example you will see by the logs that method names starting with readOnly execute in the context of a transaction with read-only semantics and that the other methods execute in the context of a transaction with read-write semantics. You will also notice that the transactions will rollback where an exception is thrown otherwise the transaction will commit.

Declarative - Annotations
The annotation declarative approach configures the transaction attributes via annotations in the Java source file. The sample application for this implementation can be found in the com.mydomain.spring.transaction.declarative.annotations package. 

annotations-test.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:tx="http://www.springframework.org/schema/tx"
 xsi:schemaLocation="http://www.springframework.org/schema/beans 
      http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
      http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
 
 <import resource="classpath:transaction-test.xml" />
 
 <bean id="transactionTestService" class="com.mydomain.spring.transaction.declarative.annotations.AnnotationsTransactionTestService" />

   <tx:annotation-driven transaction-manager="transactionManager"/>
</beans>

The definition switches on the transactional behaviour, the rest of the configuration is done via annotations in the Java source.

AnnotationsTransactionTestService.java
public class AnnotationsTransactionTestService implements TransactionTestService {
 private final static Log log = LogFactory.getLog(AnnotationsTransactionTestService.class);

 @Transactional(readOnly = true)
 public void readOnlyCommitExampleTransaction() {
  log.info("-- AnnotationsTransactionTestService.readOnlyCommitExampleTransaction -- expects transaction commit and read-only");
  // do stuff
 }
 
 @Transactional(readOnly = true)
 public void readOnlyRollbackExampleTransaction() {
  log.info("-- AnnotationsTransactionTestService.readOnlyRollbackExampleTransaction -- expects transaction rollback and read-only");
  // do stuff
  throw new RuntimeException("readOnlyRollbackExampleTransaction Exception");
 }
 
 @Transactional
 public void readWriteCommitExampleTransaction() {
  log.info("-- AnnotationsTransactionTestService.readWriteCommitExampleTransaction -- expects transaction commit");
  // do stuff
 }
 
 @Transactional
 public void readWriteRollbackExampleTransaction() {
  log.info("-- AnnotationsTransactionTestService.readWriteRollbackExampleTransaction -- expects transaction rollback");
  // do stuff
  throw new RuntimeException("readWriteRollbackExampleTransaction Exception");
 }
}

When you run this example you will see by the logs that the methods that have the readOnly element set to true for the Transactional annotation execute in the context of a transaction with read-only semantics and that the methods that don't execute in the context of a transaction with read-write semantics. You will also notice that the transactions will rollback where an exception is thrown otherwise the transaction will commit.

Programmatic - TransactionTemplate
This is the recommended approach when using programmatic transaction management. The sample application for this implementation can be found in the com.mydomain.spring.transaction.programmatic.template package. 

template-test.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
 xsi:schemaLocation="http://www.springframework.org/schema/beans 
      http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
 
 <import resource="classpath:transaction-test.xml" />
 
 <bean id="transactionTestService" class="com.mydomain.spring.transaction.programmatic.template.TemplateTransactionTestService">
  <property name="transactionManager" ref="transactionManager"/>
 </bean>
</beans>

TemplateTransactionTestService.java
public class TemplateTransactionTestService implements TransactionTestService {
 private final static Log log = LogFactory.getLog(TemplateTransactionTestService.class);
 
 private PlatformTransactionManager transactionManager = null;
 
 public PlatformTransactionManager getTransactionManager() {
  return transactionManager;
 }

 public void setTransactionManager(PlatformTransactionManager transactionManager) {
  this.transactionManager = transactionManager;
 }
 
 public void readOnlyCommitExampleTransaction() {
  log.info("-- TemplateTransactionTestService.readOnlyCommitExampleTransaction -- expects transaction commit and read-only");
  final TransactionTemplate tt = new TransactionTemplate(transactionManager);
  tt.setReadOnly(true);
  tt.execute(new TransactionCallbackWithoutResult() {
   public void doInTransactionWithoutResult(TransactionStatus status) {
    log.info("-- doInTransactionWithoutResult -- expects transaction commit");
    // do stuff
   }
  });
 }
 
 public void readOnlyRollbackExampleTransaction() {
  log.info("-- TemplateTransactionTestService.readOnlyRollbackExampleTransaction -- expects transaction rollback and read-only");
  final TransactionTemplate tt = new TransactionTemplate(transactionManager);
  tt.setReadOnly(true);
  tt.execute(new TransactionCallbackWithoutResult() {
   public void doInTransactionWithoutResult(TransactionStatus status) {
    log.info("-- doInTransactionWithoutResult -- expects transaction rollback");
    // do stuff
    status.setRollbackOnly();
   }
  });
 }
 
 public void readWriteCommitExampleTransaction() {
  log.info("-- TemplateTransactionTestService.readWriteCommitExampleTransaction -- expects transaction commit");
  final TransactionTemplate tt = new TransactionTemplate(transactionManager);
  tt.execute(new TransactionCallbackWithoutResult() {
   public void doInTransactionWithoutResult(TransactionStatus status) {
    log.info("-- doInTransactionWithoutResult -- expects transaction commit");
    // do stuff
   }
  });
 }
 
 public void readWriteRollbackExampleTransaction() {
  log.info("-- TemplateTransactionTestService.readWriteRollbackExampleTransaction -- expects transaction rollback");
  final TransactionTemplate tt = new TransactionTemplate(transactionManager);
  tt.execute(new TransactionCallbackWithoutResult() {
   public void doInTransactionWithoutResult(TransactionStatus status) {
    log.info("-- doInTransactionWithoutResult -- expects transaction rollback");
    // do stuff
    status.setRollbackOnly();
   }
  });
 }
}

Programmatic - PlatformTransactionManager
ptm-test.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
 xsi:schemaLocation="http://www.springframework.org/schema/beans 
      http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
 
 <import resource="classpath:transaction-test.xml" />
 
 <bean id="transactionTestService" class="com.mydomain.spring.transaction.programmatic.ptm.PtmTransactionTestService">
  <property name="transactionManager" ref="transactionManager"/>
 </bean>
</beans>

PtmTransactionTestService.java
public class PtmTransactionTestService implements TransactionTestService {
private final static Log log = LogFactory.getLog(PtmTransactionTestService.class);
 
 private PlatformTransactionManager transactionManager = null;
 
 public PlatformTransactionManager getTransactionManager() {
  return transactionManager;
 }

 public void setTransactionManager(PlatformTransactionManager transactionManager) {
  this.transactionManager = transactionManager;
 }
 
 public void readOnlyCommitExampleTransaction() {
  log.info("-- PtmTransactionTestService.readOnlyCommitExampleTransaction -- expects transaction commit and read-only");
  DefaultTransactionDefinition def = new DefaultTransactionDefinition();
  def.setReadOnly(true);
  TransactionStatus status = transactionManager.getTransaction(def);
  // do stuff
  transactionManager.commit(status);
 }
 
 public void readOnlyRollbackExampleTransaction() {
  log.info("-- PtmTransactionTestService.readOnlyRollbackExampleTransaction -- expects transaction rollback and read-only");
  DefaultTransactionDefinition def = new DefaultTransactionDefinition();
  def.setReadOnly(true);
  TransactionStatus status = transactionManager.getTransaction(def);
  // do stuff
  transactionManager.rollback(status);
 }
 
 public void readWriteCommitExampleTransaction() {
  log.info("-- PtmTransactionTestService.readWriteCommitExampleTransaction -- expects transaction commit");
  DefaultTransactionDefinition def = new DefaultTransactionDefinition();
  TransactionStatus status = transactionManager.getTransaction(def);
  // do stuff
  transactionManager.commit(status);
 }
 
 public void readWriteRollbackExampleTransaction() {
  log.info("-- PtmTransactionTestService.readWriteRollbackExampleTransaction -- expects transaction rollback");
  DefaultTransactionDefinition def = new DefaultTransactionDefinition();
  TransactionStatus status = transactionManager.getTransaction(def);
  // do stuff
  transactionManager.rollback(status);
 }
}

Programmatic or declarative transaction management?
"Programmatic transaction management is usually a good idea only if you have a small number of transactional operations. For example, if you have a web application that require transactions only for certain update operations, you may not want to set up transactional proxies using Spring or any other technology. In this case, using the TransactionTemplate may be a good approach. Being able to set the transaction name explicitly is also something that can only be done using the programmatic approach to transaction management. 

On the other hand, if your application has numerous transactional operations, declarative transaction management is usually worthwhile. It keeps transaction management out of business logic, and is not difficult to configure. When using the Spring Framework, rather than EJB CMT, the configuration cost of declarative transaction management is greatly reduced."

Friday, March 19, 2010

Shopping Cart Web Application - Bean Validation

Introduction
In my previous blog entry I wrote about adding security to the shopping cart web application. Part of the change I made to the application was adding a form to register users and a form to add and update items. It made sense to add validation to the fields so that we could maintain the integrity of our data.

I currently maintain two different versions of the application:
  • ShoppingCartSecurity.zip – A standard web application that runs off Tomcat 6 and is built with Hibernate, Spring, JPA and RichFaces. This is an Eclipse archive file that contains two Eclipse projects. 
  • ShoppingCartGF.zip – A JEE application that runs off GlassFish vs 3 and is built with EJB 3.0, JPA and RichFaces.

There are a number of different approaches one can take when doing validation. A common approach is using client side form validation which uses JavaScript to validate the form fields. There is no round trip to the server so the validation is nice and fast. The jQuery Javascript library has a nice plugin to use if you are interested in this approach. Even though client side validation is nice it isn't essential however server side validation is not an option and should be implemented to ensure data integrity. For the shopping cart application I decided to only use server side validation so that I was using a common validation implementation. In order to get the same user experience as client side validation I chose to use the Ajax JSF RichFaces library.

The validation  framework I have chosen to use is the standard validation framework (JSR 303: Bean Validation) implemented in Java EE 6. As of version 4.x Hibernate Validator is based on a new code base which is the reference implementation for JSR 303.

"JSR 303 defines a metadata model and API for JavaBean validation. The default metadata source is annotations, with the ability to override and extend the meta-data through the use of XML validation descriptors. The API is not tied to a specific application tier or programming model. It is specifically not tied to either the web tier or the persistence tier, and is available for both server-side application programming, as well as rich client Swing application developers."

What we will cover
  • Defining constraints
  • Custom validation
  • Spring injection into custom validators
  • Validating constraints
  • RichFaces Ajax validation for JSF inputs


Constraints
Constraints in Bean Validation are expressed via Java annotations. There are three different types of constraint annotations, namely: field, property, and class-level annotations. An example of property annotations can be seen in the User class:

@Column(name="username", nullable=false, unique=true)
@NotEmpty
@Length(min=4, max=12)
@Pattern(regexp="^[a-zA-Z\\d_]{4,12}$", message="{validator.username.invalid}")
@Username(message="{validator.username}")
public String getUsername() {
 return username;
}

The getter method for the username property specifies the following validation annotations:
  • @NotEmpty – The username cannot be null or empty.
  • @Length(min=4, max=12) – The length of the username must be at least 4 characters long and no more than 12 characters long.
  • @Pattern(regexp="^[a-zA-Z\\d_]{4,12}$", message="{validator.username.invalid}") – Match a regular expression. The username must contain alphanumeric characters. The default message is overridden with a key mapped to a message in the validation resource file. 
  • @Username(message="{validator.username}") – Custom validator to compares the usernames already stored in the database to check for duplicates.

An example of where I have used class-level annotation validation can be found in the Register.java JSF backing bean class:

@FieldMatch.List({
 @FieldMatch(first="password", second="confirmedPassword",
   message="{validator.fieldmatch.password}")
  })
public class Register extends BasePage {
 private Validator validator;
 private String password;
 private String confirmedPassword;

 @NotEmpty
 @Length(min=6, max=12)
 @Pattern(regexp = "(?=.*\\d)(?=.*[a-zA-Z]).{6,12}", message = "{validator.password.insecure}")
 public String getPassword() {
  return password;
 }

 public void validateUsername() {
  Set<ConstraintViolation<User>> constraintViolations = validator.validateProperty(getUser(), "username");
  if (constraintViolations.size() > 0) {
   String msg = constraintViolations.iterator().next().getMessage();
   addError(getUiUsername().getClientId(getFacesContext()), msg);
  }
 }
 
 public void validatePassword() {
  Set<ConstraintViolation<Register>> constraintViolations = validator.validateProperty(this, "password");
  if (constraintViolations.size() > 0) {
   String msg = constraintViolations.iterator().next().getMessage();
   addError(getUiPassword().getClientId(getFacesContext()), msg);
  }
 }
 
 public void validateConfirmedPassword() {
  Set<ConstraintViolation<Register>> constraintViolations = validator.validate(this);
  if (constraintViolations.size() > 0) {
   ConstraintViolation<Register> cv = constraintViolations.iterator().next();
   if (cv.getMessageTemplate().equals("{validator.fieldmatch.password}")) {
    addError(getUiConfirmedPassword().getClientId(getFacesContext()), cv.getMessage());    
   }
  }
 }
 
 ...
 
}

  • @FieldMatch – Custom cross field validation class-level annotation used to compare the values of two fields, namely password and confirmed password. 
  • @NotEmpty – The password cannot be null or empty.
  • @Length(min=6, max=12) – The length of the password must be at least 6 characters long and no more than 12 characters long.
  • @Pattern(regexp = "(?=.*\\d)(?=.*[a-zA-Z]).{6,12}", message="{validator.password.insecure}") – Match a regular expression. The password must contain alphanumeric characters. The default message is overridden with a key mapped to a message in the validation resource file. 

Custom Validators
As mentioned above I have two custom validators, namely Username and FieldMatch. Creating a custom validator is actually very simple and requires the following three steps:

  • Create a constraint annotation
  • Implement a validator
  • Define a default error message

I won’t go over this in too much detail as the Hibernate Validator documentation is pretty good and covers this nicely.

Username constraint annotation (Username.java)

@Target({ElementType.METHOD, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Constraint(validatedBy=UsernameValidator.class)
public @interface Username {
 String message() default "Username already exists";
 Class<?>[] groups() default {};
 Class<? extends Payload>[] payload() default {};
}

Username validator (UsernameValidator.java)

public class UsernameValidator implements ConstraintValidator<Username, Object> {
 @Autowired
 private UserDao userDao;

 public void setUserDao(UserDao userDao) {
  this.userDao = userDao;
 }

 public void initialize(Username parameters) {
 }

 public boolean isValid(final Object value, ConstraintValidatorContext context) {
  try {
   User user = userDao.findByUsername((String) value);
   if (user == null) {
    return true;
   }
  } catch (Exception e) {
   e.printStackTrace();
  }
  return false;
 }
}

Spring injection
You will notice I am injecting the UserDao class into this validator using Springs @Autowired annotation. This is made possible thanks to Spring’s LocalValidatorFactoryBean class.

"By default, the LocalValidatorFactoryBean configures a SpringConstraintValidatorFactory that uses Spring to create ConstraintValidator instances. This allows your custom ConstraintValidators to benefit from dependency injection like any other Spring bean."

I only needed to add the following line of code to the shoppingcart-database.xml Spring bean configuration file in order to use the SpringConstraintValidatorFactory:

<bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean" />

The Register.java JSF backing bean mentioned earlier gets a reference to the Spring created Validator by declaring the managed property in the faces-config.xml:

<managed-bean>
 <managed-bean-name>pc_Register</managed-bean-name>
 <managed-bean-class>com.mydomain.shoppingcart.view.Register</managed-bean-class>
 <managed-bean-scope>request</managed-bean-scope>
 <managed-property>
  <property-name>shoppingViewHelper</property-name>
  <value>#{shoppingViewHelper}</value>
 </managed-property>
 <managed-property>
  <property-name>validator</property-name>
  <value>#{validator}</value>
 </managed-property>
</managed-bean>

ValidationMessages.properties
I created a ValidationMessages.properties file and saved it in my src folder of my project. Hibernate Validator uses this file to retrieve the messages used by the validators.

Tying it together with the user interface
The login-form.jspx page includes a form for registering users. Instead of explaining each input field I am only going to step through one of them (username) and explain the validation process for it:

<h:inputText id="usrnameInTxt" binding="#{pc_Register.uiUsername}" value="#{pc_Register.user.username}" label="usrnameOutTxt" tabindex="1">
 <a4j:support id="usrnameSpt" event="onblur" reRender="usrnameMsg" limitToList="true" action="#{pc_Register.validateUsername}" />
</h:inputText>
<rich:message id="usrnameMsg" for="usrnameInTxt" errorClass="error" />

The a4j:support tag is a RichFaces tag that provides Ajax support to JSF input fields. Here it defines that the validateUsername method in the Register backing bean will be invoked when the onblur event of the input text field is triggered.

public void validateUsername() {
 Set<ConstraintViolation<User>> constraintViolations = validator.validateProperty(getUser(), "username");
 if (constraintViolations.size() > 0) {
  String msg = constraintViolations.iterator().next().getMessage();
  addError(getUiUsername().getClientId(getFacesContext()), msg);
 }
}

As you can see from the above code the validator class in the validateUsername method invokes the validateProperty method. The single property username is validated and if any constraint violations are raised an error message is added to the FacesContext.

The RichFaces rich:message tag behaves the same way as the standard JSF h:message tag except it will auto re-render itself after an Ajax request.

RichFaces Ajax Validator
RichFaces also has an Ajax validator tag that ties nicely into Hibernate Validator. I use this tag in the Items Admin modal panel of the items.jspx page.

<h:inputText id="nameInTxt" 
 value="#{pc_Items.selectedItem.name}"
 label="nameOutTxt" tabindex="1">
 <rich:ajaxValidator event="onblur" />
</h:inputText>
<rich:message id="nameMsg" for="nameInTxt" errorClass="error" />

As you can see there are no a4j:support tags or validation methods that get called. RichFaces will create its own Validator instance and call the validate property methods automatically for you. This works pretty nicely in the above example however for the registration form we are not using this tag because the validator is created for us by the Spring LocalValidatorFactoryBean class.


Registration screen shot