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   * 
17   * @since 2.0
18   * @author T.TSUCHIE
19   *
20   */
21  public class WordForbid extends ValidationCellProcessor implements StringCellProcessor {
22      
23      private final Collection<String> words;
24      
25      public WordForbid(final Collection<String> words) {
26          super();
27          checkPreconditions(words);
28          this.words = words.stream()
29                  .distinct()
30                  .collect(Collectors.toList());
31      }
32      
33      public WordForbid(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      private static void checkPreconditions(final Collection<String> words) {
42          if(words == null) {
43              throw new NullPointerException("words and field should not be null.");
44          }
45      }
46      
47      @SuppressWarnings("unchecked")
48      @Override
49      public Object execute(final Object value, final CsvContext context) {
50          if(value == null) {
51              return next.execute(value, context);
52          }
53          
54          final String stringValue = value.toString();
55          
56          final List<String> hitWords = words.stream()
57                  .filter(word -> stringValue.contains(word))
58                  .collect(Collectors.toList());
59          
60          if(!hitWords.isEmpty()) {
61              final String joinedWords = String.join(", ", hitWords);
62              throw createValidationException(context)
63                  .messageFormat("'%s' contains the forbidden substring '%s'", stringValue, joinedWords)
64                  .rejectedValue(stringValue)
65                  .messageVariables("words", hitWords)
66                  .build();
67          }
68          
69          return next.execute(value, context);
70      }
71      
72      /**
73       * 禁止語彙を取得する。
74       * @return 禁止語彙
75       */
76      public Collection<String> getWords() {
77          return words;
78      }
79      
80  }