1 package com.github.mygreen.supercsv.cellprocessor.constraint;
2
3 import java.util.ArrayList;
4 import java.util.Collection;
5 import java.util.List;
6 import java.util.Optional;
7
8 import org.supercsv.cellprocessor.ift.CellProcessor;
9
10 import com.github.mygreen.supercsv.annotation.constraint.CsvEquals;
11 import com.github.mygreen.supercsv.builder.Configuration;
12 import com.github.mygreen.supercsv.builder.FieldAccessor;
13 import com.github.mygreen.supercsv.cellprocessor.ConstraintProcessorFactory;
14 import com.github.mygreen.supercsv.cellprocessor.format.TextFormatter;
15 import com.github.mygreen.supercsv.cellprocessor.format.TextParseException;
16 import com.github.mygreen.supercsv.exception.SuperCsvInvalidAnnotationException;
17 import com.github.mygreen.supercsv.localization.MessageBuilder;
18
19
20
21
22
23
24
25
26
27 public class EqualsFactory<T> implements ConstraintProcessorFactory<CsvEquals> {
28
29 @SuppressWarnings({"unchecked", "rawtypes"})
30 @Override
31 public Optional<CellProcessor> create(final CsvEquals anno, final Optional<CellProcessor> next,
32 final FieldAccessor field, final TextFormatter<?> formatter, final Configuration config) {
33
34 final TextFormatter<T> typeFormatter = (TextFormatter<T>)formatter;
35
36 final List<T> equaledValues = new ArrayList<>();
37
38 if(anno.value().length > 0) {
39 for(String str : anno.value()) {
40 try {
41 equaledValues.add(typeFormatter.parse(str));
42
43 } catch(TextParseException e) {
44 throw new SuperCsvInvalidAnnotationException(anno, MessageBuilder.create("anno.attr.invalidType")
45 .var("property", field.getNameWithClass())
46 .varWithAnno("anno", anno.annotationType())
47 .var("attrName", "value")
48 .var("attrValue", str)
49 .varWithClass("type", field.getType())
50 .var("pattern", typeFormatter.getPattern().orElseGet(null))
51 .format(), e);
52 }
53 }
54
55 }
56
57 if(anno.provider().length > 0) {
58 final EqualedValueProvider./com/github/mygreen/supercsv/cellprocessor/constraint/EqualedValueProvider.html#EqualedValueProvider">EqualedValueProvider provider = (EqualedValueProvider) config.getBeanFactory().create(anno.provider()[0]);
59 equaledValues.addAll((Collection<T>)provider.getEqualedValues(field));
60
61 }
62
63 if(anno.value().length == 0 && anno.provider().length == 0) {
64 throw new SuperCsvInvalidAnnotationException(anno, MessageBuilder.create("anno.attr.required")
65 .var("property", field.getNameWithClass())
66 .varWithAnno("anno", anno.annotationType())
67 .var("attrName", "value or provider")
68 .format());
69 }
70
71 final Class<T> fieldType = (Class<T>)field.getType();
72 final Equals<T> processor = next.map(n -> new Equals<>(fieldType, equaledValues, typeFormatter, n))
73 .orElseGet(() -> new Equals<>(fieldType, equaledValues, typeFormatter));
74
75 processor.setValidationMessage(anno.message());
76
77 return Optional.of(processor);
78 }
79
80 }