View Javadoc
1   package com.github.mygreen.supercsv.cellprocessor.constraint;
2   
3   import java.util.Collection;
4   import java.util.List;
5   import java.util.stream.Collectors;
6   
7   import org.supercsv.cellprocessor.ift.CellProcessor;
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  /**
15   * 必須語彙を含んでいるか検証するCellProcessor.
16   * @since 2.0
17   * @author T.TSUCHIE
18   *
19   */
20  public class WordRequire extends ValidationCellProcessor implements StringCellProcessor {
21      
22      private final Collection<String> words;
23      
24      public WordRequire(final Collection<String> words) {
25          super();
26          checkPreconditions(words);
27          this.words = words.stream()
28                  .distinct()
29                  .collect(Collectors.toList());
30          
31      }
32      
33      public WordRequire(final Collection<String> words, final CellProcessor next) {
34          super(next);
35          checkPreconditions(words);
36          this.words = words.stream()
37                  .distinct()
38                  .collect(Collectors.toList());
39          
40      }
41      
42      private static void checkPreconditions(final Collection<String> words) {
43          if(words == null) {
44              throw new NullPointerException("words and field should not be null.");
45          }
46      }
47      
48      @SuppressWarnings("unchecked")
49      @Override
50      public Object execute(final Object value, final CsvContext context) {
51          
52          if(value == null) {
53              return next.execute(value, context);
54          }
55          
56          if(!words.isEmpty()) {
57              final String stringValue = value.toString();
58              
59              final List<String> requiredWords = words.stream()
60                      .filter(word -> !stringValue.contains(word))
61                      .collect(Collectors.toList());
62              
63              if(!requiredWords.isEmpty()) {
64                  final String joinedWords = String.join(", ", requiredWords);
65                  throw createValidationException(context)
66                      .messageFormat("'%s' does not contain any of the required substirng '%s'", stringValue, joinedWords)
67                      .rejectedValue(stringValue)
68                      .messageVariables("words", requiredWords)
69                      .build();
70              }
71          }
72          
73          return next.execute(value, context);
74      }
75      
76      /**
77       * 必須語彙のを取得する。
78       * @return 必須語彙
79       */
80      public Collection<String> getWords() {
81          return words;
82      }
83      
84  }