View Javadoc

1   /**
2    * Copyright 2005-2012 The Kuali Foundation
3    *
4    * Licensed under the Educational Community License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    * http://www.opensource.org/licenses/ecl2.php
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  package org.kuali.rice.krad.datadictionary.validation.constraint;
17  
18  import org.apache.commons.lang.StringUtils;
19  import org.kuali.rice.core.api.CoreConstants;
20  import org.kuali.rice.core.api.config.property.ConfigContext;
21  import org.kuali.rice.krad.datadictionary.parse.BeanTag;
22  import org.kuali.rice.krad.datadictionary.parse.BeanTagAttribute;
23  import org.kuali.rice.krad.datadictionary.parse.BeanTags;
24  
25  import java.util.ArrayList;
26  import java.util.Arrays;
27  import java.util.Collections;
28  import java.util.List;
29  
30  /**
31   * DatePatternConstraint constrains a field to only allow dates which are part of the formats
32   * defined in the system. Constraining a field all these formats is often not appropriate for
33   * fields, and you may want to constrain the input to a subset of the allowed formats in the system.
34   * This can be done by setting the allowed formats to this subset (see BasicDatePatternConstraint
35   * bean for example)
36   *
37   * @author Kuali Rice Team (rice.collab@kuali.org)
38   */
39  @BeanTags({@BeanTag(name = "datePatternConstraint", parent = "DatePatternConstraint"),
40          @BeanTag(name = "basicDatePatternConstraint", parent = "BasicDatePatternConstraint")})
41  public class DatePatternConstraint extends ValidDataPatternConstraint {
42  
43      private List<String> allowedFormats;
44  
45      /**
46       * Returns a regex representing all the allowed formats in the system. If allowedFormats is
47       * supplied, returns a regex representing only those formats.
48       *
49       * @see org.kuali.rice.krad.datadictionary.validation.constraint.ValidDataPatternConstraint#getRegexString()
50       */
51      @Override
52      protected String getRegexString() {
53          List<String> dateFormatParams = parseConfigValues(ConfigContext.getCurrentContextConfig().getProperty(
54                  CoreConstants.STRING_TO_DATE_FORMATS));
55          if (allowedFormats != null && !allowedFormats.isEmpty()) {
56              if (dateFormatParams.containsAll(allowedFormats)) {
57                  dateFormatParams = allowedFormats;
58              } else {
59                  //throw new Exception("Some of these formats do not exist in configured allowed date formats: " + allowedFormats.toString());
60              }
61          }
62  
63          if (dateFormatParams.isEmpty()) {
64              //exception
65          }
66          String regex = "";
67          int i = 0;
68          for (String format : dateFormatParams) {
69              if (i == 0) {
70                  regex = "(^" + convertDateFormatToRegex(format.trim()) + "$)";
71              } else {
72                  regex = regex + "|(^" + convertDateFormatToRegex(format.trim()) + "$)";
73              }
74              i++;
75          }
76          return regex;
77      }
78  
79      /**
80       * Converts a date format supplied to the appropriate date format regex equivalent
81       *
82       * @param format
83       * @return
84       */
85      private String convertDateFormatToRegex(String format) {
86          format = format.replace("\\", "\\\\").replace(".", "\\.").replace("-", "\\-").replace("+", "\\+").replace("(",
87                  "\\(").replace(")", "\\)").replace("[", "\\[").replace("]", "\\]").replace("|", "\\|").replace("yyyy",
88                  "((19|2[0-9])[0-9]{2})").replace("yy", "([0-9]{2})").replaceAll("M{4,}",
89                  "([@]+)") //"(January|February|March|April|May|June|July|August|September|October|November|December)")
90                  .replace("MMM", "([@]{3})") //"(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)")
91                  .replace("MM", "(0[1-9]|1[012])").replace("M", "(0?[1-9]|1[012])").replace("dd",
92                          "(0[1-9]|[12][0-9]|3[01])").replace("d", "(0?[1-9]|[12][0-9]|3[01])").replace("hh",
93                          "(1[0-2]|0[1-9])").replace("h", "(1[0-2]|0?[1-9])").replace("HH", "(2[0-3]|1[0-9]|0[0-9])")
94                  .replace("H", "(2[0-3]|1[0-9]|0?[0-9])").replace("kk", "(2[0-4]|1[0-9]|0[1-9])").replace("k",
95                          "(2[0-4]|1[0-9]|0?[1-9])").replace("KK", "(1[01]|0[0-9])").replace("K", "(1[01]|0?[0-9])")
96                  .replace("mm", "([0-5][0-9])").replace("m", "([1-5][0-9]|0?[0-9])").replace("ss", "([0-5][0-9])")
97                  .replace("s", "([1-5][0-9]|0?[0-9])").replace("SSS", "([0-9][0-9][0-9])").replace("SS",
98                          "([0-9][0-9][0-9]?)").replace("S", "([0-9][0-9]?[0-9]?)").replaceAll("E{4,}",
99                          "([@]+)")//"(Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday)")
100                 .replaceAll("E{1,3}", "([@]{3})")//"(Mon|Tue|Wed|Thu|Fri|Sat|Sun)")
101                 .replace("DDD", "(3[0-6][0-5]|[1-2][0-9][0-9]|0[0-9][1-9])").replace("DD",
102                         "(3[0-6][0-5]|[1-2][0-9][0-9]|0?[0-9][1-9])").replace("D",
103                         "(3[0-6][0-5]|[1-2][0-9][0-9]|0?[0-9]?[1-9])").replace("F", "([1-5])").replace("ww",
104                         "(5[0-3]|[1-4][0-9]|0[1-9])").replace("w", "(5[0-3]|[1-4][0-9]|[1-9])").replace("W", "([1-5])")
105                 .replaceAll("z{4,}", "([@]+)").replaceAll("z{1,3}", "([@]{1,4})").replaceAll("a{1,}", "([aApP][mM])")
106                 .replaceAll("G{1,}", "([aA][dD]|[bB][cC])").replace(" ", "\\s").replace("@", "a-zA-Z");
107 
108         return format;
109 
110     }
111 
112     /**
113      * The dateTime config vars are ';' seperated.
114      *
115      * @param configValue
116      * @return
117      */
118     private List<String> parseConfigValues(String configValue) {
119         if (configValue == null || "".equals(configValue)) {
120             return Collections.emptyList();
121         }
122         return Arrays.asList(configValue.split(";"));
123     }
124 
125     /**
126      * @return the allowedFormats
127      */
128     @BeanTagAttribute(name = "allowedFormats", type = BeanTagAttribute.AttributeType.LISTVALUE)
129     public List<String> getAllowedFormats() {
130         return this.allowedFormats;
131     }
132 
133     /**
134      * Sets the alloweFormats for this constraint, this must be a subset of the system configured
135      * formats for a date - this list should be used for most fields where you are expecting a user
136      * to enter a date in a specific format
137      *
138      * @param allowedFormats the allowedFormats to set
139      */
140     public void setAllowedFormats(List<String> allowedFormats) {
141         this.allowedFormats = allowedFormats;
142     }
143 
144     /**
145      * This overridden method ...
146      *
147      * @see org.kuali.rice.krad.datadictionary.validation.constraint.ValidDataPatternConstraint#getValidationMessageParams()
148      */
149     @Override
150     public List<String> getValidationMessageParams() {
151         if (validationMessageParams == null) {
152             validationMessageParams = new ArrayList<String>();
153             if (allowedFormats != null && !allowedFormats.isEmpty()) {
154                 validationMessageParams.add(StringUtils.join(allowedFormats, ", "));
155             } else {
156                 List<String> dateFormatParams = parseConfigValues(ConfigContext.getCurrentContextConfig().getProperty(
157                         CoreConstants.STRING_TO_DATE_FORMATS));
158                 validationMessageParams.add(StringUtils.join(dateFormatParams, ", "));
159             }
160         }
161         return validationMessageParams;
162     }
163 
164 }