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