View Javadoc
1   package org.kuali.ole.sys.businessobject.format;
2   
3   import java.text.ParseException;
4   import java.text.SimpleDateFormat;
5   
6   import org.apache.commons.lang.StringUtils;
7   import org.kuali.ole.sys.context.SpringContext;
8   import org.kuali.rice.core.api.config.property.ConfigurationService;
9   import org.kuali.rice.core.web.format.FormatException;
10  import org.kuali.rice.core.web.format.Formatter;
11  
12  /**
13   * Formatter which specializes in reading dates from flat files
14   */
15  public class BatchDateFormatter extends Formatter {
16      private static final String DEFAULT_FLAT_FILE_DATE_FORMAT = "default.flatFile.dateFormat";
17      private static String defaultDateFormat;
18  
19      private String dateFormat;
20      private boolean formatToTimestamp = false;
21  
22      /**
23       * Sets the date format to use for parsing
24       * @param dateFormat
25       */
26      public void setDateFormat(String dateFormat) {
27          this.dateFormat = dateFormat;
28      }
29  
30      /**
31       * @return the date format associated with this batch date format - if not specified, then the default
32       */
33      public String getDateFormat() {
34          return StringUtils.isBlank(dateFormat) ? getDefaultDateFormat() : dateFormat;
35      }
36  
37      /**
38       * @return the default date format, pulled from the application resource messages
39       */
40      public String getDefaultDateFormat() {
41          if (defaultDateFormat == null) {
42              defaultDateFormat = SpringContext.getBean(ConfigurationService.class).getPropertyValueAsString(BatchDateFormatter.DEFAULT_FLAT_FILE_DATE_FORMAT);
43          }
44          return defaultDateFormat;
45      }
46  
47      /**
48       * Determines if the date should be parsed to a java.sql.Timestamp rather than the default java.sql.Date
49       * @param formatToTimestamp true if result should be parsed as timestamp, false otherwise
50       */
51      public void setFormatToTimestamp(boolean formatToTimestamp) {
52          this.formatToTimestamp = formatToTimestamp;
53      }
54  
55      /**
56       * Parses the given String to a date
57       */
58      @Override
59      protected Object convertToObject(String string) {
60          try {
61              long time = new SimpleDateFormat(getDateFormat()).parse(string).getTime();
62              if (formatToTimestamp) {
63                  return new java.sql.Timestamp(time);
64              }
65              return new java.sql.Date(time);
66          }
67          catch (ParseException e) {
68              throw new FormatException("Date must be of the format " + dateFormat, e);
69          }
70      }
71  }