net.sourceforge.stripes.validation
Class DateTypeConverter

java.lang.Object
  extended by net.sourceforge.stripes.validation.DateTypeConverter
All Implemented Interfaces:
TypeConverter<Date>

public class DateTypeConverter
extends Object
implements TypeConverter<Date>

A TypeConverter that aggressively attempts to convert a String to a java.util.Date object. Under the covers it uses DateFormat instances to do the heavy lifting, but since SimpleDateFormat is quite picky about its input a couple of measures are taken to improve our chances of parsing a Date.

First the String is pre-processed to replace commas, slashes, hyphens and periods with spaces and to collapse multiple white spaces into a single space. Then, to ensure that input like "Jan 1" and "3/19" are parseable a check is performed to see if there are only two segments in the input string (e.g. "Jan" and "1" but no "2007"). If that is the case then the current four digit year is appended to improve chances or parsing because a two segment date is not parsable by a DateFormat that expects a year.

Then an array of DateFormat instances are used in turn to attempt to parse the input. If any DateFormat succeeds and returns a Date, that Date will be returned as the result of the conversion. If all DateFormats fail, a validation error will be produced.

The set of formats is obtained from getFormatStrings(). The default set of formats used is constructed by taking the default SHORT, MEDIUM and LONG formats for the input locale (and replacing all non-space separator characters with spaces), and adding formats to obtain the following patterns:

This default set of formats can be changed by providing a different set of format strings in the Stripes resource bundle, or by subclassing and overriding getFormatStrings(). In all cases patterns should be specified using single spaces as separators instead of slashes, dashes or other characters.

The regular expression pattern used in the pre-process method can also be changed in the Stripes resource bundle, or by subclassing and overriding the getPreProcessPattern() method.

The keys used in the resource bundle to specify the format strings and the pre-process pattern are:

DateTypeConverter can also be overridden in order to change its behaviour. Subclasses can override the preProcessInput() method to change the pre-processing behavior if desired. Similarly, subclasses can override getDateFormats() to change how the DateFormat objects get constructed.


Field Summary
static String[] formatStrings
          The default set of date patterns used to parse dates with SimpleDateFormat.
static String KEY_FORMAT_STRINGS
          The key used to look up the localized format strings from the resource bundle.
static String KEY_PRE_PROCESS_PATTERN
          The key used to look up the pre-process pattern from the resource bundle.
static Pattern PRE_PROCESS_PATTERN
          A pattern used to pre-process Strings before the parsing attempt is made.
 
Constructor Summary
DateTypeConverter()
           
 
Method Summary
protected  String checkAndAppendYear(String input)
          Checks to see how many 'parts' there are to the date (separated by spaces) and if there are only two parts it adds the current year to the end by geting the Locale specific year string from a Calendar instance.
 Date convert(String input, Class<? extends Date> targetType, Collection<ValidationError> errors)
          Attempts to convert a String to a Date object.
protected  DateFormat[] getDateFormats()
          Returns an array of DateFormat objects that will be used in sequence to try and parse the date String.
protected  String[] getFormatStrings()
          Returns an array of format strings that will be used, in order, to try and parse the date.
 Locale getLocale()
           
protected  Pattern getPreProcessPattern()
          Returns the regular expression pattern used in the pre-process method.
protected  String getResourceString(String key)
          Convenience method to fetch a property from the resource bundle.
protected  String preProcessInput(String input)
          Pre-processes the input String to improve the chances of parsing it.
 void setLocale(Locale locale)
          Used by Stripes to set the input locale.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

PRE_PROCESS_PATTERN

public static final Pattern PRE_PROCESS_PATTERN

A pattern used to pre-process Strings before the parsing attempt is made. Since SimpleDateFormat strictly enforces that the separator characters in the input are the same as those in the pattern, this regular expression is used to remove commas, slashes, hyphens and periods from the input String (replacing them with spaces) and to collapse multiple white-space characters into a single space.

This pattern can be changed by providing a different value under the 'stripes.dateTypeConverter.preProcessPattern' key in the resource bundle. The default value is (?<!GMT)[\\s,-/\\.]+.


formatStrings

public static final String[] formatStrings
The default set of date patterns used to parse dates with SimpleDateFormat.


KEY_FORMAT_STRINGS

public static final String KEY_FORMAT_STRINGS
The key used to look up the localized format strings from the resource bundle.

See Also:
Constant Field Values

KEY_PRE_PROCESS_PATTERN

public static final String KEY_PRE_PROCESS_PATTERN
The key used to look up the pre-process pattern from the resource bundle.

See Also:
Constant Field Values
Constructor Detail

DateTypeConverter

public DateTypeConverter()
Method Detail

setLocale

public void setLocale(Locale locale)
Used by Stripes to set the input locale. Once the locale is set a number of DateFormat instances are created ready to convert any input.

Specified by:
setLocale in interface TypeConverter<Date>
Parameters:
locale - the locale that the TypeConverter will be converting from.

getLocale

public Locale getLocale()
Returns:
the current input locale.

getFormatStrings

protected String[] getFormatStrings()
Returns an array of format strings that will be used, in order, to try and parse the date. This method can be overridden to make DateTypeConverter use a different set of format Strings. Given that pre-processing converts most common separator characters into spaces, patterns should be expressed with spaces as separators, not slashes, hyphens etc.


getDateFormats

protected DateFormat[] getDateFormats()
Returns an array of DateFormat objects that will be used in sequence to try and parse the date String. This method will be called once when the DateTypeConverter instance is initialized. It first calls getFormatStrings() to obtain the format strings that are used to construct SimpleDateFormat instances.


convert

public Date convert(String input,
                    Class<? extends Date> targetType,
                    Collection<ValidationError> errors)
Attempts to convert a String to a Date object. Pre-processes the input by invoking the method preProcessInput(), then uses an ordered list of DateFormat objects (supplied by getDateFormats()) to try and parse the String into a Date.

Specified by:
convert in interface TypeConverter<Date>
Parameters:
input - the String being converted
targetType - the Class representing the type of the property to which the return value of the conversion will be assigned. In many cases this can be ignored as converters will return a single type more often than not.
errors - an empty collection of validation errors that should be populated by the converter for any errors that occur during validation that are user input related.
Returns:
T an instance of the converted type, or null if the input cannot be converted

getPreProcessPattern

protected Pattern getPreProcessPattern()
Returns the regular expression pattern used in the pre-process method. Looks for a pattern in the resource bundle under the key 'stripes.dateTypeConverter.preProcessPattern'. If no value is found, the pattern (?<!GMT)[\\s,-/\\.]+ is used by default. The pattern is used by preProcessInput() to replace all matches by single spaces.


preProcessInput

protected String preProcessInput(String input)
Pre-processes the input String to improve the chances of parsing it. First uses the regular expression Pattern returned by getPreProcessPattern() to remove all separator chars and ensure that components are separated by single spaces. Then invokes checkAndAppendYear(String) to append the year to the date in case the date is in a format like "12/25" which would otherwise fail to parse.


checkAndAppendYear

protected String checkAndAppendYear(String input)
Checks to see how many 'parts' there are to the date (separated by spaces) and if there are only two parts it adds the current year to the end by geting the Locale specific year string from a Calendar instance.

Parameters:
input - the date string after the pre-process pattern has been run against it
Returns:
either the date string as is, or with the year appended to the end

getResourceString

protected String getResourceString(String key)
                            throws MissingResourceException
Convenience method to fetch a property from the resource bundle.

Throws:
MissingResourceException


? Copyright 2005-2006, Stripes Development Team.