Home > JPA, JSF, Open Lane, Spring, Spring Web Flow > Open Lane Changes

Open Lane Changes

My Open Lane application has undergone some significant changes. I’ve added:

  1. Entity classes for a swim meet and events within the meet.
  2. Enumerators for Gender and Stroke.
  3. An AgeGroup class to encapsulate an event’s age category.
  4. JSF DataModel subclasses for Meet and Event along with a refactored SignUp backing bean.
  5. JPA services for all data input and output.
  6. JSF Converter classes for Gender, Stroke, and AgeGroup.
  7. CSV file initialization functions to populate the Swimmer, Meet, Event, and User tables.

Gender and stroke each represent a fixed set of constants which can be objectified in Java as an enumerator. An enumerator provides a clean, self-documenting, and an efficient way of coding an object model. Java enumerators can also be used to encapsulated conversion functionality.

In the case of this application the meet, event, swimmer, and entry records are imported from a CSV file. Within the event record is a stroke (i.e. Freestyle, Backstroke) filed that is coded using a number.  A “1” represents Freestyle, a “2” represents Backstroke, and so on. Stroke has been coded so that each enumerator has its import field number code associated with it. During the import process a simple call to Stroke.parse(string) generates the correct enumerator.

Instead of putting parse into Stroke I could have created a distinct converter. That would have been a cleaner separation of the code. But I don’t anticipate the conversion changing or needing to be adaptable. This way the code is simpler and straight forward.


package org.bwgz.swim.openlane.data.model;

public enum Stroke {

    private String code;

    Stroke(String code) {
    	this.code = code;

     public String getCode() {
          return code;

     public void setCode(String code) {
          this.code = code;

    public static Stroke parse(String string) {
    	Stroke result = null;

    	for (Stroke stroke : Stroke.values() ) {
    		if (stroke.getCode().equalsIgnoreCase(string)) {
				result = stroke;

		return result;

This is an example of using the Gender enumerator within a JPA query to abstract away the codes used in the database. I don’t have to concern myself with how the data is coded once it is imported into the database.

em.createQuery("select e from Event e where e.meet = :meet and (e.gender = :mixed or e.gender = :gender")
.setParameter("meet", meet)
.setParameter("mixed", Gender.MIXED)
.setParameter("gender", gender)

Later in this article is an example of how the enumerator’s parse method is used.

Eventually the JSF tables will support sorting and paging. In preparation for that I’ve moved from List and Collection to JSF’s DataModel. DataModel is a wrapper that abstracts the underlying data. I’ve also used it to store which record (object) may have been selected by the user. Previously there was an independent bean to handle that. Putting it here keeps thing a bit tidier. I created DataModel’s for Event and Meet. Later I’ll reuse the pattern for a user’s open lane applications.

I’ve decided to build out services for each entity in the data model. This provides a level of encapsulation and organization that make the code more manageable. Using @Autowired I can also create services that are built upon other services. For example, the SignUpService uses the SwimmerService.

SignUpService.java snippet.

public class SignUpServiceImpl implements SignUpService, Serializable {

     private EntityManager em;
     private SwimmerService swimmerService;

    public void setEntityManager(EntityManager em) {
    	this.em = em;
     public Boolean doSignUp(SignUp signUp) {
     Boolean result = Boolean.FALSE;

     Swimmer swimmer = swimmerService.findSwimmer(signUp.getUsasId());

As a general rule the code should have a clean separation between how data is represented internally and externally. JSF’s Converter class is one way to accomplish that. I needed a Converter for Gender, Stroke, and AgeGroup. Since Gender and Stroke were enumerators I create an abstract base class to simplify things. The Gender and Stroke converters need only supply the mappings between the internal representation (an enumerator) and string (display value).


package org.bwgz.swim.openlane.faces.converter;

import java.util.Hashtable;
import java.util.Map;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;

public abstract class AbstractEnumConverter<T> implements Converter {
	private final static int ASSOCIATION_ENUM	= 0;
	private final static int ASSOCIATION_STRING	= 1;

	private Class<T> clazz;
	private final Map<T, String> toStringMap = new Hashtable<T, String>();
	private final Map<String, T> toEnumMap = new Hashtable<String, T>();

	public AbstractEnumConverter(Class<T> clazz, Object[][] associations) {
		this.clazz = clazz;

		for (Object[] association : associations) {
			toEnumMap.put((String) association[ASSOCIATION_STRING], (T) association[ASSOCIATION_ENUM]);
			toStringMap.put((T) association[ASSOCIATION_ENUM], (String) association[ASSOCIATION_STRING]);

	public Object getAsObject(FacesContext context, UIComponent component, String value) {
		return toEnumMap.get(value);

	public String getAsString(FacesContext context, UIComponent component, Object value) {
            if (value.getClass() == clazz) {
        	 return toStringMap.get((T) value);
                throw new IllegalArgumentException(String.format("Cannot convert object - not of type %s", clazz.getSimpleName()));


package org.bwgz.swim.openlane.faces.converter;

import javax.faces.convert.FacesConverter;
import org.bwgz.swim.openlane.data.model.Stroke;

public class StrokeConverter extends AbstractEnumConverter<Stroke> {
	private final static Object associations[][] = {
		{ Stroke.FREE,		"Free" },
		{ Stroke.BACK,		"Back" },
		{ Stroke.BREAST,	"Breast" },
		{ Stroke.FLY,		"Fly" },
		{ Stroke.IM,		"IM" },

	public StrokeConverter() {
		super(Stroke.class, associations);

The AgeGroup converter encapsulates the four rules used to describe an age category.


package org.bwgz.swim.openlane.faces.converter;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;

import org.bwgz.swim.openlane.data.model.AgeGroup;

public class AgeGroupConverter implements Converter {
	private static final String SENIOR		= "Senior";
	private static final String UNDER		= "Under";
	private static final String OVER		= "Over";
	private static final String AMPERSAND	= "&";
	private static final String HYPHEN		= "-";

	private static final int LEFT	= 0;
	private static final int RIGHT	= 1;

	private Object getAsObject(String string) {
		long min = 0;
		long max = 0;

		if (string.equals(SENIOR)) {
			min = 0;
			max = 0;
		else if (string.contains(AMPERSAND)) {
			String[] fields = string.split(AMPERSAND);

			if (fields[RIGHT].equals(UNDER)) {
				min = 0;
				max = Long.parseLong(fields[LEFT]);
			else if (fields[RIGHT].equals(OVER)) {
				min = Long.parseLong(fields[LEFT]);
				max = 0;
		else if (string.contains(HYPHEN)) {
			String[] fields = string.split(HYPHEN);

			min = Long.parseLong(fields[LEFT]);
			max = Long.parseLong(fields[RIGHT]);

		return new AgeGroup(min, max);

	public Object getAsObject(FacesContext context, UIComponent component, String value) {
		return getAsObject(value);

	private String getAsString(AgeGroup ageGroup) {
		String string;

		if (ageGroup.getMin() == 0 & ageGroup.getMax() == 0) {
			string = SENIOR;
		else {
			String left;
			String seperator;
			String right;

			if (ageGroup.getMin() == 0) {
				left = String.valueOf(ageGroup.getMax());
				seperator = AMPERSAND;
				right = UNDER;
			else if (ageGroup.getMax() == 0) {
				left = String.valueOf(ageGroup.getMin());
				seperator = AMPERSAND;
				right = OVER;
			else {
				left = String.valueOf(ageGroup.getMin());
				seperator = HYPHEN;
				right = String.valueOf(ageGroup.getMax());

			string = left + seperator + right;

		return string;

	public String getAsString(FacesContext context, UIComponent component, Object value) {
            if (value instanceof AgeGroup) {
                return getAsString((AgeGroup) value);
                throw new IllegalArgumentException("Cannot convert object - not of type AgeGroup");

Meet, event, swimmer, and later entry records are imported from another system. Unfortunately the limitations of that system prevent the application from accessing them directly. Instead the data is exported to CSV files and then imported into the application.

Eventually I’ve incorporate a form of file upload within the application to provide live data import. For now some dummy (test) CSV files are included in the application and imported when the application is first accessed. Some services now have an initialize method. When called the method will read a CSV file and write the data to the database using JPA.

Using <on-start> within home-flow.xml I trigger the initializations. This is a hack for testing purposes only.

home-flow.xml snippet

        <evaluate expression="swimmerService.initialize()" />
        <evaluate expression="meetService.initialize()" />
        <evaluate expression="signupService.initialize()" />

I use FlatPack to process the CSV files. It’s a nice CSV library that I’ve used many times in the past. I particularly like that it allows you to create a map of the column names. On the other hand the map requires names for every column. This can be a bit tedious when you only need the first few columns. It can also choke when the file contains records with differing number of columns.

SwimmerServiceImpl.java snippet.

    public void initialize() {
    if (!initialized) {
        DataSet dataSet;

        Parser parser;
        parser = DefaultParserFactory.getInstance().newDelimitedParser(
            new InputStreamReader(this.getClass().getClassLoader().getResourceAsStream("/test/data/athlete.pzmap.xml")), // xml column mapping
            new InputStreamReader(this.getClass().getClassLoader().getResourceAsStream("/test/data/athlete.csv")),  // csv file to parse
            ';', // delimiter
             '"', // text qualfier
             false); // ignore the first record (may need to be done if first record contain column names)

            dataSet = parser.parse();
            while (dataSet.next()) {
                Swimmer swimmer = new Swimmer();



            initialized = true;

The code is available here on GitHub.

  1. December 6, 2012 at 4:42 am

    how to change enum Stroke {1,2,3,4,5} became {FREE,BACK,BREAST,FLY,IM} in csv file.. thanks before

  2. Mario
    October 19, 2013 at 7:21 pm

    Hi. How do you generate the tables? I don’t see any ddl in your code.

    • October 19, 2013 at 8:23 pm

      The tables are generated automatically by the persistence layer if they do not exist. It’s specified in the configuration files.

  1. No trackbacks yet.

Leave a Reply to Mario Cancel reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: