View Javadoc
1   package com.github.mygreen.supercsv.cellprocessor.constraint;
2   
3   import java.util.Optional;
4   import java.util.regex.PatternSyntaxException;
5   
6   import org.supercsv.cellprocessor.ift.CellProcessor;
7   import org.supercsv.cellprocessor.ift.StringCellProcessor;
8   
9   import com.github.mygreen.supercsv.annotation.constraint.CsvPattern;
10  import com.github.mygreen.supercsv.builder.Configuration;
11  import com.github.mygreen.supercsv.builder.FieldAccessor;
12  import com.github.mygreen.supercsv.cellprocessor.ConstraintProcessorFactory;
13  import com.github.mygreen.supercsv.cellprocessor.format.TextFormatter;
14  import com.github.mygreen.supercsv.exception.SuperCsvInvalidAnnotationException;
15  import com.github.mygreen.supercsv.localization.MessageBuilder;
16  import com.github.mygreen.supercsv.util.Utils;
17  
18  /**
19   * アノテーション{@link CsvPattern}をハンドリングして、CellProcessorの{@link Pattern}を作成する。
20   *
21   * @since 2.0
22   * @author T.TSUCHIE
23   *
24   */
25  public class PatternFactory implements ConstraintProcessorFactory<CsvPattern> {
26      
27      @Override
28      public Optional<CellProcessor> create(final CsvPattern anno, final Optional<CellProcessor> next,
29              final FieldAccessor field, final TextFormatter<?> formatter, final Configuration config) {
30          
31          final int flags = Utils.buildRegexFlags(anno.flags());
32          final java.util.regex.Pattern pattern;
33          try {
34              pattern = java.util.regex.Pattern.compile(anno.regex(), flags);
35              
36          } catch(PatternSyntaxException e) {
37              throw new SuperCsvInvalidAnnotationException(anno, MessageBuilder.create("anno.attr.invalidType")
38                      .var("property", field.getNameWithClass())
39                      .varWithAnno("anno", anno.annotationType())
40                      .var("attrName", "regex")
41                      .var("attrValue", anno.regex())
42                      .var("type", "{key.regex}")
43                      .format(true));
44          }
45          
46          final Patternonstraint/Pattern.html#Pattern">Pattern processor = next.map(n -> new Pattern(pattern, anno.description(), (StringCellProcessor)n))
47                  .orElseGet(() -> new Pattern(pattern, anno.description()));
48          
49          processor.setValidationMessage(anno.message());
50          
51          return Optional.of(processor);
52      }
53      
54  }