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