1 package com.github.mygreen.supercsv.cellprocessor.conversion;
2
3 import java.util.Optional;
4
5 import org.supercsv.cellprocessor.ift.CellProcessor;
6 import org.supercsv.cellprocessor.ift.StringCellProcessor;
7
8 import com.github.mygreen.supercsv.annotation.conversion.CsvWordReplace;
9 import com.github.mygreen.supercsv.builder.Configuration;
10 import com.github.mygreen.supercsv.builder.FieldAccessor;
11 import com.github.mygreen.supercsv.cellprocessor.ConversionProcessorFactory;
12 import com.github.mygreen.supercsv.cellprocessor.format.TextFormatter;
13 import com.github.mygreen.supercsv.exception.SuperCsvInvalidAnnotationException;
14 import com.github.mygreen.supercsv.localization.MessageBuilder;
15
16
17
18
19
20
21
22
23
24 public class WordReplaceFactory implements ConversionProcessorFactory<CsvWordReplace> {
25
26 @Override
27 public Optional<CellProcessor> create(final CsvWordReplace anno, final Optional<CellProcessor> next,
28 final FieldAccessor field, final TextFormatter<?> formatter, final Configuration config) {
29
30 final CharReplacerllprocessor/conversion/CharReplacer.html#CharReplacer">CharReplacer replacer = new CharReplacer();
31
32 final String[] words = anno.words();
33 final String[] replacements = anno.replacements();
34
35 if(words.length != replacements.length) {
36 throw new SuperCsvInvalidAnnotationException(anno, MessageBuilder.create("anno.CsvWordReplace.invalidSize")
37 .var("property", field.getNameWithClass())
38 .varWithAnno("anno", anno.annotationType())
39 .var("wordsSize", words.length)
40 .var("replacementsSize", replacements.length)
41 .format());
42 }
43
44 final int size = words.length;
45 for(int i=0; i < size; i++) {
46 replacer.register(words[i], replacements[i]);
47 }
48
49 if(anno.provider().length > 0) {
50 final ReplacedWordProvider./com/github/mygreen/supercsv/cellprocessor/conversion/ReplacedWordProvider.html#ReplacedWordProvider">ReplacedWordProvider provider = (ReplacedWordProvider) config.getBeanFactory().create(anno.provider()[0]);
51 provider.getReplacedWords(field)
52 .stream()
53 .forEach(word -> replacer.register(word.getWord(), word.getReplacement()));
54 }
55
56 if(words.length == 0 && anno.provider().length == 0) {
57 throw new SuperCsvInvalidAnnotationException(anno, MessageBuilder.create("anno.attr.required")
58 .var("property", field.getNameWithClass())
59 .varWithAnno("anno", anno.annotationType())
60 .var("attrName", "value or provider")
61 .format());
62 }
63
64 replacer.ready();
65
66 final WordReplacersion/WordReplace.html#WordReplace">WordReplace processor = next.map(n -> new WordReplace(replacer, (StringCellProcessor) n))
67 .orElseGet(() -> new WordReplace(replacer));
68
69 return Optional.of(processor);
70 }
71
72 }