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



Thursday, March 18, 2010

Shopping Cart Web Application - Security

Introduction
Those of you who are familiar with the shopping cart application tutorial will be pleased to know I have finally added security to it. It was never my intention to add security to the shopping cart application as I felt it was a little out of the scope of what I was trying to achieve. However the application would never been complete unless security was added to it.

I currently maintain two different versions of the shopping cart application:
  1. 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. You should be able to import these projects into your Eclipse environment.
  2. ShoppingCartGF.zip – A JEE application that runs off GlassFish vs 3 and is built with EJB 3.0, JPA and RichFaces. This is also an Eclipse archive file that contains three Eclipse projects. You should be able to import these projects into your Eclipse environment as well.
If you would like to compile and deploy the above mentioned applications you will need the libraries that they reference. I haven't included the libraries in the downloads, however I have provided links to all the libraries I have used in the previous shopping cart tutorials. I am not going to mention all of them here so you will need to go through each tutorial in order to get them. Over and above those libraries you will also need the below mentioned ones as these are specific to this version of the application:

ShoppingCartSecurity application

ShoppingCartGF application


What we will cover
  • Form-based authentication
  • Deployment configuration
  • Login form
  • Security realms
  • Using authentication with SSL
  • New features added to the shopping cart application 


Form-based authentication
The most common authentication mechanism and the one I chose to implement for the shopping cart application is called form-based authentication. Users can navigate through unprotected areas of the website without requiring a password. Only when the user tries to access a protected page will they be redirected to  a login page.


  1. A client requests access to a protected resource.
  2. If the client is unauthenticated, the server redirects the client to a login page.
  3. The client submits the login form to the server.
  4. If the login succeeds, the server redirects the client to the resource. If the login fails, the client is redirected to an error page.


Deployment Configuration
To configure our application for form-based authentication we need to define the authentication method in our web deployment descriptor, which resources are protected and what security roles are used. Below is a snippet from the web deployment descriptor that depicts these changes:

<security-constraint>
 <web-resource-collection>
  <web-resource-name>protected</web-resource-name>
  <url-pattern>/secure/*</url-pattern>
  <http-method>GET</http-method>
  <http-method>POST</http-method>
  <http-method>HEAD</http-method>
  <http-method>PUT</http-method>
  <http-method>OPTIONS</http-method>
  <http-method>TRACE</http-method>
  <http-method>DELETE</http-method>
 </web-resource-collection>
 <auth-constraint>
  <role-name>administrator</role-name>
  <role-name>customer</role-name>
 </auth-constraint>
</security-constraint>
<login-config>
 <auth-method>FORM</auth-method>
 <realm-name>shoppingCartJDBCRealm</realm-name>
 <form-login-config>
  <form-login-page>/login.faces</form-login-page>
  <form-error-page>/error.faces</form-error-page>
 </form-login-config>
</login-config>
<security-role>
 <description>Administrators role</description>
 <role-name>administrator</role-name>
</security-role>
<security-role>
 <description>Customers role</description>
 <role-name>customer</role-name>
</security-role>

Security constraint
The security-constraint element defines the access privileges to a collection of resources using their URL mapping.
  • web-resource-collection - used to identify the resources in a web application to which a security constraint applies. In the above example the URL pattern /secure/* specifies that all resources in this application under the secure folder are protected.
  • auth-constraint - indicates the user roles that should be permitted access to this resource collection. 

Login config
The login-config element defines the authentication method (namely form-based authentication) as well as the page that will be displayed when an unauthenticated user tries to access secure content and the page that will be displayed when login fails. For the GlassFish version of the application the realm name is defined to specify which realm configured on the server should be used when authenticating users.

Security role
The security-role element specifies the role a user can belong to.

Login form
The login page can be an HTML page, a JSP page, or a servlet, and it must return an HTML page containing a form that conforms to specific naming conventions. The login page needs to contain a form with j_security_check as its action as well as a text input box called j_username and a password input box called j_password. These are the input names that need to be used in order for the application server to process the Form authentication. An example of how this is implemented can be seen in the login-form.jspx page:

<h:panelGrid id="loginGrd" columns="2">
 <h:outputText id="usernameOutTxt" value="#{msg.login_txt_username}" />
 <input id="usernameInTxt" type="text" name="j_username" />
 <h:outputText id="passwordOutTxt" value="#{msg.login_txt_password}" />
 <input id="passwordInTxt" type="password" name="j_password" />
 <f:facet name="footer">
  <input type="submit" value="#{msg.btn_login}" />
 </f:facet>
</h:panelGrid>

Realm
A realm is a repository of user names and passwords that identify valid users of a web application along with the list of roles associated with each valid user. There are a number of different realms one can configure, in our example I chose to configure a JDBC realm where the users name and authentication details are stored in a database. Each application server is unique in its configuring of realms. Below are the steps I took to configure Tomcat and GlassFish:

Tomcat
In order to add a realm to Tomcat you need to edit the server.xml file, for our example I added the following realm to the server.xml:

<Realm className="org.apache.catalina.realm.JDBCRealm" 
   connectionName="sa" 
   connectionPassword="" 
   connectionURL="jdbc:hsqldb:hsql://localhost:9001/shoppingcart" 
   debug="99" 
   digest="MD5" 
   driverName="org.hsqldb.jdbcDriver" 
   roleNameCol="role_name" 
   userCredCol="password" 
   userNameCol="username" 
   userRoleTable="user_role" 
   userTable="users"/>

GlassFish
To configure a realm in GlassFish login to the GlassFish administration console and navigate to: Configuration -> Security -> Realms. Click on the new button and complete the form as shown in the screen shot below:


This assumes a datasource with the JNDI name jdbc/__shoppingcart has already been configured.

GlassFish requires its own deployment descriptor (sun-web.xml) to be configured in order to map the roles defined in the web applications web.xml file to the groups defined on the application server:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE sun-web-app PUBLIC "-//Sun Microsystems, Inc.//DTD 
GlassFish Application Server 3.0 Servlet 3.0//EN" 
"http://www.sun.com/software/appserver/dtds/sun-web-app_3_0-0.dtd">
<sun-web-app>
 <security-role-mapping>
  <role-name>customer</role-name>
  <group-name>customer</group-name>
 </security-role-mapping>
 <security-role-mapping>
  <role-name>administrator</role-name>
  <group-name>administrator</group-name>
 </security-role-mapping>
</sun-web-app>

Using Authentication with SSL
Form-based authentication alone is not particularly secure, passwords sent between a client and a server on an unprotected session can be viewed and intercepted by third parties. In order to prevent this from happening you would need to configure your connections to run over an SSL (Secure Socket Layer) protected session. SSL is a technology which allows web browsers and web servers to communicate over a secured connection. This means that the data being sent is encrypted by one side, transmitted and then decrypted by the other side before processing. 

Usually you wouldn't have to configure your application server for SSL as you most likely would have a primary web server running that is used to handle all requests and responses from the browser to the server. The web server will therefore be configured to handle the SSL connections from the users. This web server will negotiate all SSL related functionality and then pass on any requests destined for the application server only after decrypting those requests. 

I haven't configured the shopping cart application to run over SSL. If you would like to learn more here are some useful links to get you started:


New features added to the shopping cart application 
The following additional features not mentioned above were added to the shopping cart application
  1. Three new entity classes, namely User, Role and UserRole
  2. User registration
  3. Item administration
  4. Once logged in an administrator can maintain the items list by adding, editing and removing items


Additional settings
Tomcat
  1. In order to get JSTL to work in Tomcat 6 I followed the instructions outlined in this tutorial.
  2. In the previous examples of the shopping cart application I used an in-memory database. However in this version I am not. The reason is because Tomcat would sometimes not find any user results and sometimes it would. It is a mystery to me as the Tomcat server and my application runs within the same JVM so it should be using the same database right? I lost patience and reverted to a file based database. I use an ant build script to start and stop the HSQL database. The file is called db-man-build.xml and can be located in the build folder. 
  3. The applications administrator's user name is 'admin' and the password is 'admin'. These values along with the default collection of items will automatically be imported into the shoppingcart database on application startup. 

GlassFish
  1. I configured a Derby database to use with the GlassFish version of the application. You can start and stop the Derby database by running the asadmin start-database or asadmin stop-database commands from the bin directory in the GlassFish installation directory. 
  2. The database will need to be pre-populated with data manually as this doesn't get done automatically by the application. The import sql script can be located in src folder of the shopping-cart-core-gf project. 


Screen shots
Registration modal with login form in the background


Items administration modal page with the landing page in the background


Sunday, January 17, 2010

Shopping Cart Web Application - Play Framework

 Shopping Cart Application – Play Framework

I recently spent time stepping through the yabe (yet another blog engine) tutorial for the Play Framework.

"The Play framework makes it easier to build Web applications with Java"


What is Play?
Play is a full stack open source web framework for Java that focuses on developer productivity.

"The Play framework compiles your Java sources directly and hot-reloads them into the JVM without the need to restart the server. You can then edit, reload and see your modifications immediately"


Why Play?
There are a number of reasons why the Play framework is cool and I highly recommend you take a look at it: 5 cool things you can do with Play. The one that caught my eye was that the Play framework eliminates the time spent in compiling Java source files, packaging the code into an archive and then deploying that archive to a server. Already I am hooked. This is great! For something similar to this for JEE development take a look at JRebel. Depending on which license you get you may have to pay a fee.

Shopping Cart
In an effort to learn more I decided to build my own Play web application based on the very basic Shopping Cart application I have used in the past.

Here are a few comparisons between the original Shopping Cart web application and this one written for the Play framework:

1. JPA
The Play framework supports JPA so there really isn’t any difference with the entity classes in the domain model.

2. Spring
In the original application I was mainly using Spring for dependency injection. I didn’t need to use Spring in my application but the Play framework supports Spring as well as dependency injection (in version 1.0.1).

3. JSF Components vs HTML
The original application used JSF to build the GUI interface whereas Play uses plain HTML. There are many different JSF components to choose from and you can use additional JSF component libraries besides the standard components that come with JSF such as RichFaces / ICEfaces and many more. With very little effort you can include a JSF component within your page and bind it to a Java class. It is all very cool for a Java developer who wants a nice looking website without hiring a web developer to do it for them. However there are a few drawbacks to this approach, some of the main ones being:

  • The JSF components render down to HTML and JavaScript. You have no real control over how the rendering takes place. You could be rendering a HTML table whereas you would prefer to use a DIV.
  • Some JSF components reference custom JavaScript files. These JavaScript files could be quite large and you may not even be referencing them but because they form part of the JSF library you automatically reference it. 
  • Not that easy to change the behaviour of the JSF components to do something that it was never designed to do.

The Play framework uses standard HTML as well as its own template engine. The drawbacks for a Java developer is there are no drag and dropping of components into a JSP page. However if you’re a web developer you would most likely prefer to work with plain HTML files. You have more control over your page and there are 100’s of CSS / JavaScript libraries you can pull into your project without much hassle.

4. AJAX
The original project used a very cool JSF library called RichFaces. RichFaces has many ‘rich’ components to choose from with built in Ajax support.

I used JQuery to do all the Ajax requests and responses in the Play framework. JQuery is a very powerful JavaScript library. However you are not forced to use it, you could just as easily do it with your own JavaScript or another library that offers similar functionality.

5. JUnit
Both the original application and Play use JUnit as the test framework. The Play framework has a couple of nice utilities you can use and comes with a test suite out of the box to run all your tests from.

That’s all I wanted to say on that, the Play documentation is quite good, for a taste of what you can do I highly recommend the yabe tutorial and they have an active forum for any questions.

Saturday, January 9, 2010

Shopping Cart Web Application - Part 7 - TopLink and EAR

I recently received a response from someone who was stepping through my Shopping Cart Web Application tutorial and who wanted to deploy the application on GlassFish and use TopLink Essentials (EclipseLink) as the reference implementation for JPA as opposed to Hibernate.

Thankfully there wasn't that much change that needed to be made to the existing ShoppingCartHibJpaPart7 application. This application (ShoppingCartTopLinkJpaPart7.zip) is available to download in case anyone would like to take a look. I chose to use EclipseLink which is the successor to TopLink. In order to get it working with GlassFish 2.0 there are a few simple steps to take. The biggest change I needed to make was in the persistence.xml file:

<persistence xmlns="http://java.sun.com/xml/ns/persistence"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
    http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"
 version="1.0">

 <persistence-unit name="shopping-cart"
  transaction-type="RESOURCE_LOCAL">
  <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
  <non-jta-data-source>jdbc/__shoppingcart</non-jta-data-source>
  <exclude-unlisted-classes>false</exclude-unlisted-classes>
  <properties>
   <property name="eclipselink.ddl-generation" value="drop-and-create-tables" />
   <property name="eclipselink.logging.level" value="FINE" />
  </properties>
 </persistence-unit>
</persistence>
The real difference here is the use of EclipseLink properties as opposed to Hibernate properties. I also had to define the non-jta-data-source attribute. Another one of the requirements was to have GlassFish manage the database connections so my application needed to be configured to lookup the resource via the datasource JNDI name.

Java Transaction API  (JTA) inside a web application
After doing this I was asked if I could change the transaction type from RESOURCE_LOCAL to JTA. In order to do this I made the following changes:

I changed the value of the transaction-type in the persistence.xml file from RESOURCE_LOCAL to JTA and changed the non-jta-data-source attribute to jta-data-source.

Secondly I needed to do a JNDI lookup for the EntityManager managed by the container, one way is to do it by annotation on the Dao class:

@PersistenceContext(name="persistence/ShoppingCart", unitName="shopping-cart")
public class BasketDaoImpl implements BasketDao {

and then the lookup:

Context ctx = new InitialContext();
em =  (EntityManager) ctx.lookup("java:comp/env/persistence/ShoppingCart");

Our application is managing the transaction however in a JTA entity manager entityManager.getTransaction() calls are not permitted so instead I needed to get a UserTransaction by doing a JNDI lookup for the UserTransaction:

Context ctx = new InitialContext();
(UserTransaction)ctx.lookup("java:comp/UserTransaction");

If you are interested in seeing how I implemented this you can download the ShoppingCartJtaTopLinkJpaPart7.zip file and view the DAO classes in the shopping-cart-core-jta-toplink-jpa-part7 project.

BasketDaoImpl.java
@PersistenceContext(name="persistence/ShoppingCart", unitName="shopping-cart")
public class BasketDaoImpl implements BasketDao {

  public Basket updateBasket(Basket basket) throws Exception {
    EntityManager em = null;
    UserTransaction utx = null;
    try {
      em = JPAUtil.getEntityManager();
      utx = JPAUtil.getUserTransaction();
      utx.begin();
      basket = em.merge(basket);
      utx.commit();
      return basket;
    } catch (RuntimeException e) {
      if (utx != null) {
        utx.rollback();
      }
      throw e;
    }
  }

Java Transaction API  (JTA) inside a JEE application
In this example our application is going to make use of an EJB session bean. Unlike in the previous example where our application was controlling the transaction via the UserTransaction class here the container will manage and control the transaction for us. Once again you can download the full source of the ShoppingCartEJBTopLinkJpaPart7.zip file and take a look at what I did.

Using JEE annotations it was very simple to turn the ShoppingManager class into a session bean. The @PersistenceContext annotation was used to obtain an EntityManager instance and you will also notice I got rid of the DAO classes as there really was no need for them anymore as the container manages the transaction.

ShoppingManager.java
@Stateless(name="ShoppingManager")
public class ShoppingManager implements ShoppingService {

  @PersistenceContext(unitName="shopping-cart")
  private EntityManager em;

  public Basket updateBasket(Basket basket) throws ShoppingException {
    try {
      return em.merge(basket);
    } catch (Exception e) {
      logger.error("There was an error updating the basket, exception: " + e);
      throw new ShoppingException("There was an error updating the basket", e);
    }
  }

All these applications were written in Eclipse and tested in a GlassFish 2.0 application server.