1 package com.github.mygreen.supercsv.cellprocessor;
2
3 import java.lang.annotation.Annotation;
4 import java.util.Collections;
5 import java.util.HashMap;
6 import java.util.List;
7 import java.util.Map;
8 import java.util.Optional;
9 import java.util.Set;
10 import java.util.stream.Collectors;
11
12 import org.slf4j.Logger;
13 import org.slf4j.LoggerFactory;
14 import org.supercsv.cellprocessor.ift.CellProcessor;
15
16 import com.github.mygreen.supercsv.annotation.conversion.CsvConversion;
17 import com.github.mygreen.supercsv.builder.BuildCase;
18 import com.github.mygreen.supercsv.builder.Configuration;
19 import com.github.mygreen.supercsv.builder.FieldAccessor;
20 import com.github.mygreen.supercsv.cellprocessor.format.TextFormatter;
21 import com.github.mygreen.supercsv.util.Utils;
22
23
24
25
26
27
28
29
30 public class ConversionProcessorHandler implements ProcessorFactory {
31
32 private static Logger logger = LoggerFactory.getLogger(ConversionProcessorHandler.class);
33
34 private final Map<Class<? extends Annotation>, ConversionProcessorFactory<?>> factoryMap = new HashMap<>();
35
36 @SuppressWarnings({"rawtypes", "unchecked"})
37 @Override
38 public Optional<CellProcessor> create(final Optional<CellProcessor> processor, final FieldAccessor field,
39 final TextFormatter<?> formatter, final Configuration config, final BuildCase buildCase, final Class<?>[] groups) {
40
41
42 final List<Annotation> annos = field.getAnnotationsByGroup(groups).stream()
43 .filter(anno -> anno.annotationType().getAnnotation(CsvConversion.class) != null)
44 .filter(anno -> Utils.containsBuildCase(anno, buildCase))
45 .collect(Collectors.toList());
46
47 Collections.reverse(annos);
48
49 Optional<CellProcessor> cp = processor;
50
51 for(Annotation anno : annos) {
52
53 final CsvConversion conversionAnno = anno.annotationType().getAnnotation(CsvConversion.class);
54
55 if(factoryMap.containsKey(anno.annotationType())) {
56
57 final ConversionProcessorFactory factory = factoryMap.get(anno.annotationType());
58 cp = factory.create(anno, cp, field, formatter, config);
59
60 } else if(conversionAnno.value().length > 0) {
61
62
63
64
65 for(Class<? extends ConversionProcessorFactory> factoryClass : conversionAnno.value()) {
66 final ConversionProcessorFactory factory =
67 (ConversionProcessorFactory) config.getBeanFactory().create(factoryClass);
68 cp = factory.create(anno, cp, field, formatter, config);
69 }
70
71 } else {
72
73 logger.warn("Not found {} with the annotation {}.", ConversionProcessorFactory.class.getSimpleName(), anno.getClass());
74 }
75
76 }
77
78 return cp;
79 }
80
81
82
83
84
85
86
87
88 public <A extends Annotation> void register(final Class<A> anno, final ConversionProcessorFactory<A> factory) {
89 factoryMap.put(anno, factory);
90 }
91
92
93
94
95
96 public Set<Map.Entry<Class<? extends Annotation>, ConversionProcessorFactory<?>>> getEntrySet() {
97 return factoryMap.entrySet();
98 }
99
100 }