1 package fr.ifremer.tutti.service.csv;
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27 import fr.ifremer.tutti.persistence.entities.TuttiEntities;
28 import fr.ifremer.tutti.persistence.entities.TuttiEntity;
29 import org.apache.commons.lang3.StringUtils;
30 import org.nuiton.csv.ValueParserFormatter;
31
32 import java.text.ParseException;
33 import java.util.List;
34 import java.util.Map;
35
36
37
38
39
40
41
42 public abstract class EntityParserFormatterSupport<E extends TuttiEntity> implements ValueParserFormatter<E> {
43
44 protected final String formatNullValue;
45
46 protected final boolean technical;
47
48 protected final Class<E> entityType;
49
50 protected Map<String, E> entitiesById;
51
52 protected boolean authorizeObsoleteReferentials;
53
54 protected EntityParserFormatterSupport(String formatNullValue, boolean technical, Class<E> entityType) {
55 this.formatNullValue = formatNullValue;
56 this.technical = technical;
57 this.entityType = entityType;
58 }
59
60 protected abstract List<E> getEntitiesWithObsoletes();
61
62 protected abstract List<E> getEntities();
63
64 protected abstract String formatBusiness(E e);
65
66 protected Map<String, E> getEntitiesById() {
67
68 if (entitiesById == null) {
69
70 List<E> entities = isAuthorizeObsoleteReferentials() ? getEntitiesWithObsoletes() : getEntities();
71 entitiesById = TuttiEntities.splitById(entities);
72
73 }
74 return entitiesById;
75
76 }
77
78 @Override
79 public E parse(String value) throws ParseException {
80
81 E result = null;
82 if (StringUtils.isNotBlank(value)) {
83
84 result = parseNotBlankValue(value);
85
86 }
87 return result;
88
89 }
90
91 @Override
92 public String format(E e) {
93
94 String value;
95 if (e == null) {
96
97 if (technical) {
98 value = "";
99 } else {
100 value = formatNullValue;
101 }
102
103 } else {
104
105 if (technical) {
106 value = formatTechnical(e);
107 } else {
108 value = formatBusiness(e);
109 }
110
111 }
112 return value;
113
114 }
115
116 protected E parseNotBlankValue(String value) {
117
118 E result = getEntitiesById().get(value);
119
120 if (result == null) {
121
122 throw new EntityNotFoundException(entityType, value);
123
124 }
125
126 return result;
127
128 }
129
130 protected String formatTechnical(E e) {
131 String value;
132 value = e.getId();
133 return value;
134 }
135
136 public boolean isAuthorizeObsoleteReferentials() {
137 return authorizeObsoleteReferentials;
138 }
139
140 public void setAuthorizeObsoleteReferentials(boolean authorizeObsoleteReferentials) {
141 this.authorizeObsoleteReferentials = authorizeObsoleteReferentials;
142 }
143
144 }