View Javadoc
1   package com.github.mygreen.supercsv.cellprocessor.constraint;
2   
3   import org.supercsv.cellprocessor.ift.StringCellProcessor;
4   import org.supercsv.util.CsvContext;
5   
6   import com.github.mygreen.supercsv.cellprocessor.ValidationCellProcessor;
7   
8   
9   /**
10   * 文字列に対して、正規表現に一致するか検証するCellProcessor.
11   *
12   * @since 2.0
13   * @author T.TSUCHIE
14   *
15   */
16  public class Pattern extends ValidationCellProcessor implements StringCellProcessor {
17      
18      private final java.util.regex.Pattern pattern;
19      
20      private final String description;
21      
22      public Pattern(final java.util.regex.Pattern regexPattern, final String regexDescriptoin) {
23          super();
24          checkPreconditions(regexPattern);
25          this.pattern = regexPattern;
26          this.description = regexDescriptoin;
27      }
28      
29      public Pattern(final java.util.regex.Pattern regexPattern, final String regexDescriptoin, final StringCellProcessor next) {
30          super(next);
31          checkPreconditions(regexPattern);
32          this.pattern = regexPattern;
33          this.description = regexDescriptoin;
34      }
35      
36      private static void checkPreconditions(final java.util.regex.Pattern regexPattern) {
37          if(regexPattern == null) {
38              throw new NullPointerException("regexPattern should not be null");
39          }
40      }
41      
42      @SuppressWarnings("unchecked")
43      @Override
44      public Object execute(final Object value, final CsvContext context) {
45          
46          if(value == null) {
47              return next.execute(value, context);
48          }
49          
50          final boolean matches = pattern.matcher((String) value).matches();
51          if(!matches) {
52              throw createValidationException(context)
53                  .messageFormat("'%s' does not match the regular expression '%s'", value, getRegex())
54                  .rejectedValue(value)
55                  .messageVariables("regex", getRegex())
56                  .messageVariables("flags", getFlags())
57                  .messageVariables("description", getDescription())
58                  .build();
59          }
60          
61          return next.execute(value, context);
62      }
63      
64      /**
65       * 
66       * @return 設定せれた正規表現
67       */
68      public String getRegex() {
69          return pattern.pattern();
70      }
71      
72      /**
73       * 
74       * @return 正規表現のフラグ
75       */
76      public int getFlags() {
77          return pattern.flags();
78      }
79      
80      /**
81       * 
82       * @return 正規表現の説明
83       */
84      public String getDescription() {
85          return description;
86      }
87      
88  }