View Javadoc
1   package com.github.mygreen.supercsv.cellprocessor.constraint;
2   
3   import org.supercsv.cellprocessor.ift.BoolCellProcessor;
4   import org.supercsv.cellprocessor.ift.CellProcessor;
5   import org.supercsv.cellprocessor.ift.DateCellProcessor;
6   import org.supercsv.cellprocessor.ift.DoubleCellProcessor;
7   import org.supercsv.cellprocessor.ift.LongCellProcessor;
8   import org.supercsv.cellprocessor.ift.StringCellProcessor;
9   import org.supercsv.util.CsvContext;
10  
11  import com.github.mygreen.supercsv.cellprocessor.ValidationCellProcessor;
12  
13  /**
14   * 値が必須かどうかチェックする制約のCellProcessor。
15   *
16   * @since 2.0
17   * @author T.TSUCHIE
18   *
19   */
20  public class Require extends ValidationCellProcessor 
21          implements BoolCellProcessor, DateCellProcessor, DoubleCellProcessor, LongCellProcessor, StringCellProcessor {
22      
23      private final boolean considerEmpty;
24      
25      private final boolean considerBlank;
26      
27      public Require(final boolean considerEmpty, final boolean considerBlank) {
28          super();
29          this.considerEmpty = considerEmpty;
30          this.considerBlank = considerBlank;
31      }
32      
33      public Require(final boolean considerEmpty, final boolean considerBlank, final CellProcessor next) {
34          super(next);
35          this.considerEmpty = considerEmpty;
36          this.considerBlank = considerBlank;
37      }
38      
39      @Override
40      public <T> T execute(final Object value, final CsvContext context) {
41          
42          if (!validate(value)){
43              throw createValidationException(context)
44                  .message("null or empty value encountered")
45                  .messageVariables("considerEmpty", considerEmpty)
46                  .messageVariables("considerBlank", considerBlank)
47                  .rejectedValue(value)
48                  .build();
49          }
50          
51          return next.execute(value, context);
52      }
53      
54      private boolean validate(final Object value) {
55          
56          if(value == null) {
57              return false;
58          }
59          
60          if(value instanceof String) {
61              final String strValue = (String)value;
62              if(considerEmpty && strValue.isEmpty()) {
63                  return false;
64              }
65              
66              if(considerBlank && strValue.trim().isEmpty()) {
67                  return false;
68              }
69          }
70          
71          return true;
72      }
73      
74      /**
75       * 空文字を考慮するかどうか。
76       * @return trueの場合、空文字を考慮します。
77       */
78      public boolean isConsiderEmpty() {
79          return considerEmpty;
80      }
81      
82      /**
83       * 空白文字を考慮するかどうか。
84       * @return trueの場合、空白文字を考慮します。
85       */
86      public boolean isConsiderBlank() {
87          return considerBlank;
88      }
89      
90  }