001 package org.springframework.richclient.samples.simple.ui;
002
003 import java.text.ParseException;
004 import java.text.SimpleDateFormat;
005 import java.util.Date;
006 import java.util.regex.Matcher;
007 import java.util.regex.Pattern;
008
009 import org.springframework.binding.format.Formatter;
010 import org.springframework.binding.format.InvalidFormatException;
011 import org.springframework.binding.format.support.AbstractFormatter;
012 import org.springframework.binding.format.support.DateFormatter;
013 import org.springframework.binding.format.support.SimpleFormatterFactory;
014 import org.springframework.util.StringUtils;
015
016 /**
017 * Simple formatter factory that returns a custom date/time formatter. By default, this
018 * formatter is used to format all date fields in the application.
019 *
020 * @author Keith Donald
021 */
022 public class SimpleAppFormatterFactory extends SimpleFormatterFactory {
023
024 public Formatter getDateTimeFormatter() {
025 return new AppDateFormatter();
026 }
027
028 /**
029 * Formatter for date fields in the application.
030 * @author Larry and Geoffrey (by Keith)
031 */
032 class AppDateFormatter extends AbstractFormatter {
033
034 /** Default Date format. */
035 private final DateFormatter format = new DateFormatter(new SimpleDateFormat("MM-dd-yyyy"));
036
037 /** Pattern to verify date contains full 4 digit year. */
038 private final Pattern MDY_PATTERN = Pattern.compile("[0-9]{1,2}-[0-9]{1,2}-[0-9]{4}");
039
040 protected String doFormatValue(Object value) {
041 return (value == null) ? "" : format.formatValue(value);
042 }
043
044 protected Object doParseValue(String formattedString, Class targetClass) throws InvalidFormatException,
045 ParseException {
046 String src = (String) formattedString;
047 // If the user entered slashes, convert them to dashes
048 if (src.indexOf('/') >= 0) {
049 src = src.replace('/', '-');
050 }
051 Object value = null;
052 if (StringUtils.hasText(src)) {
053
054 Matcher matcher = MDY_PATTERN.matcher(src);
055
056 if (!matcher.matches()) {
057 throw new ParseException("Invalid date format: " + src, 0);
058 }
059
060 value = format.parseValue(src, Date.class);
061 }
062 return value;
063 }
064 }
065 }