1 package com.github.mygreen.supercsv.cellprocessor.conversion;
2
3 import java.util.Collection;
4 import java.util.HashSet;
5 import java.util.Set;
6 import java.util.stream.Collectors;
7
8 import org.supercsv.cellprocessor.CellProcessorAdaptor;
9 import org.supercsv.cellprocessor.ift.StringCellProcessor;
10 import org.supercsv.util.CsvContext;
11
12
13
14
15
16
17
18
19
20 public class NullConvert extends CellProcessorAdaptor implements StringCellProcessor {
21
22 private final Set<String> tokens = new HashSet<>();
23
24 private final boolean ignoreCase;
25
26
27
28
29
30
31
32
33 public NullConvert(final Collection<String> tokens, final boolean ignoreCase) {
34 super();
35 checkPreconditions(tokens);
36 this.tokens.addAll(toIgnoreCase(tokens, ignoreCase));
37 this.ignoreCase = ignoreCase;
38 }
39
40
41
42
43
44
45
46
47
48 public NullConvert(final Collection<String> tokens, final boolean ignoreCase, final StringCellProcessor next) {
49 super(next);
50 checkPreconditions(tokens);
51 this.tokens.addAll(toIgnoreCase(tokens, ignoreCase));
52 this.ignoreCase = ignoreCase;
53 }
54
55 private static void checkPreconditions(final Collection<String> tokens) {
56 if(tokens == null) {
57 throw new NullPointerException("tokens should not be null.");
58
59 } else if(tokens.isEmpty()) {
60 throw new IllegalArgumentException("tokens should not be empty.");
61 }
62 }
63
64 private static Collection<String> toIgnoreCase(final Collection<String> value, boolean ignoreCase) {
65 if(!ignoreCase) {
66 return value;
67 }
68
69 return value.stream()
70 .map(v -> v.toLowerCase())
71 .collect(Collectors.toList());
72 }
73
74 private static String toIgnoreCase(final String value, boolean ignoreCase) {
75 if(!ignoreCase) {
76 return value;
77 }
78
79 return value.toLowerCase();
80 }
81
82 @Override
83 public <T> T execute(final Object value, final CsvContext context) {
84
85 if(value == null) {
86 return next.execute(value, context);
87 }
88
89 final String str = toIgnoreCase(value.toString(), ignoreCase);
90 if(tokens.contains(str)) {
91 return next.execute(null, context);
92 }
93
94 return next.execute(value, context);
95 }
96
97
98
99
100
101 public Set<String> getTokens() {
102 return tokens;
103 }
104
105
106
107
108
109 public boolean isIgnoreCase() {
110 return ignoreCase;
111 }
112
113 }