View Javadoc
1   package com.github.mygreen.supercsv.cellprocessor.constraint;
2   
3   import org.supercsv.cellprocessor.ift.CellProcessor;
4   import org.supercsv.cellprocessor.ift.StringCellProcessor;
5   import org.supercsv.exception.SuperCsvCellProcessorException;
6   import org.supercsv.exception.SuperCsvConstraintViolationException;
7   import org.supercsv.util.CsvContext;
8   
9   import com.github.mygreen.supercsv.cellprocessor.ValidationCellProcessor;
10  
11  
12  /**
13   * 文字列が最大長以下か検証するCellProcessor.
14   * 
15   * @version 2.0
16   * @author T.TSUCHIE
17   *
18   */
19  public class LengthMax extends ValidationCellProcessor implements StringCellProcessor {
20      
21      private final int max;
22      
23      public LengthMax(final int max) {
24          super();
25          checkPreconditions(max);
26          this.max = max;
27      }
28      
29      public LengthMax(final int max, final CellProcessor next) {
30          super(next);
31          checkPreconditions(max);
32          this.max = max;
33      }
34      
35      /**
36       * Checks the preconditions for creating a new {@link LengthMax} processor.
37       * 
38       * @param max
39       *            the maximum String length
40       * @throws IllegalArgumentException
41       *             {@literal if min is < 0}
42       */
43      private static void checkPreconditions(final int max) {
44          if( max <= 0 ) {
45              throw new IllegalArgumentException(String.format("max length (%d) should not be <= 0", max));
46          }
47      }
48      
49      /**
50       * {@inheritDoc}
51       * 
52       * @throws SuperCsvCellProcessorException
53       *             {@literal if value is null}
54       * @throws SuperCsvConstraintViolationException
55       *             {@literal if length is < min or length > max}
56       */
57      @SuppressWarnings("unchecked")
58      public Object execute(final Object value, final CsvContext context) {
59          
60          if(value == null) {
61              return next.execute(value, context);
62          }
63          
64          final String stringValue = value.toString();
65          final int length = stringValue.length();
66          if( length > max ) {
67              throw createValidationException(context)
68                  .messageFormat("the length (%d) of value '%s' does not lie the max (%d) values (inclusive)",
69                          length, stringValue, max)
70                  .rejectedValue(stringValue)
71                  .messageVariables("max", getMax())
72                  .messageVariables("length", length)
73                  .build();
74                  
75          }
76          
77          return next.execute(stringValue, context);
78      }
79      
80      /**
81       * 
82       * @return 設定された最大文字長を取得する
83       */
84      public int getMax() {
85          return max;
86      }
87  
88  }