Kenmegne
7 days ago 23a46b4be35277e06ec89f48730eeb694e686be8
1
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
/*
 * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
 * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
 */
package com.megatim.fdxcommons.tools.database.queries.validation;
 
import com.megatim.fdxcommons.model.enumeration.TypeDonnee;
import com.megatim.fdxcommons.model.integration.json.JsonStructure;
import com.megatim.fdxcommons.tools.database.exceptions.LocalDateTimeValueParseError;
import com.megatim.fdxcommons.tools.database.queries.metadata.InsertionLocalDateTimeValue;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import org.apache.commons.validator.GenericValidator;
 
/**
 *
 * @author ASUS
 */
public class JsonDataValidationError {
 
    private final ArrayList<String> errors = new ArrayList<>();
    private final List<LinkedHashMap<String, Object>> data;
    private final JsonStructure jsonStructure;
 
    public JsonDataValidationError(List<LinkedHashMap<String, Object>> data, JsonStructure jsonStructure) {
        this.data = data;
        this.jsonStructure = jsonStructure;
    }
 
    public String validationError() {
        if (errors.isEmpty()) {
            int index = 1;
            for (Map<String, Object> dataItem : data) {
                String error = processDataItem(dataItem, jsonStructure);
 
                if (error != null && !error.trim().isEmpty()) {
                    errors.add(elementNumberString(index++) + " : " + error);
                }
            }
        }
        return error();
    }
 
    private String processDataItem(Map<String, Object> dataItem, JsonStructure jsonStruct) {
        StringBuilder lineError = new StringBuilder("");
 
        //Vérifie si une colonne obligatoire est absente
        lineError.append(addErrorForNotFoundColumn(dataItem, jsonStruct.getFields()));
 
        for (Map.Entry<String, Object> dataItemEntry : dataItem.entrySet()) {
 
            String columnName = dataItemEntry.getKey();
            Object columnValue = dataItemEntry.getValue();
 
            Optional<JsonStructure> optField = jsonStruct.getFields().stream().filter(f -> f.getName().equalsIgnoreCase(columnName)).findFirst();
 
            if (!optField.isPresent()) {
                lineError.append("La colonne ").append(columnName).append(" n'existe pas pour ce fichier;");
                continue;
            }
            JsonStructure field = optField.get();
 
            if (field.isCollection() || field.getTypeDonnee().equals(TypeDonnee.OBJET)) {
                if (field.getTypeDonnee().equals(TypeDonnee.OBJET)) {
 
                    if (field.isCollection()) {
                        if (columnValue instanceof List) {
                            List liste = (List) columnValue;
                            int i = 1;
 
                            for (Object obj : liste) {
                                if (obj instanceof Map) {
                                    lineError.append(processDataItem((Map<String, Object>) obj, field));
                                } else {
                                    lineError.append("L'élément No ").append(i++).append(" de la colonne '").append(columnName).append("' doit être un objet;");
                                }
                            }
                        } else {
                            lineError.append(" La donnée de la colonne '").append(columnName).append("' doit être une liste;");
                        }
                    } else {
                        if (columnValue instanceof Map) {
                            lineError.append(processDataItem((Map<String, Object>) columnValue, field));
                        } else {
                            lineError.append(" La donnée de la colonne '").append(columnName).append("' doit être un objet;");
                        }
                    }
                } else {
                    if (columnValue instanceof List) {
                        simpleListValueError(columnValue, field);
                    } else {
                        lineError.append(" La donnée de la colonne '").append(columnName).append("' doit être une liste;");
                    }
                }
            } else {
                columnValueError(lineError, field, columnValue);
            }
        }
        return lineError.toString();
    }
 
    private String simpleListValueError(Object columnValue, JsonStructure field) {
        List liste = (List) columnValue;
        StringBuilder arrayError = new StringBuilder("");
        int i = 1;
 
        for (Object obj : liste) {
            arrayError.append(columnValueError(obj, field, i++));
        }
        return arrayError.toString().trim();
    }
 
    private void columnValueError(StringBuilder lineError, JsonStructure field, Object columnValue) {
        String error = columnValueError(columnValue, field);
        if (error != null && !error.trim().isEmpty()) {
            lineError.append(error.trim());
        }
    }
 
    private String error() {
        StringBuilder stringBuilder = new StringBuilder("");
        errors.forEach(e -> {
            if (e != null && !e.trim().isEmpty()) {
                stringBuilder.append(e.trim()).append("\n");
            }
        }
        );
        return stringBuilder.toString();
    }
 
    private String addErrorForNotFoundColumn(Map<String, Object> dataItem, List<JsonStructure> fields) {
        StringBuilder message = new StringBuilder("");
 
        fields.forEach(f -> {
            String error = addErrorForNotFoundColumn(dataItem, f);
            if (!error.isEmpty()) {
                message.append("\n").append(error);
            }
        });
        return message.toString();
    }
 
    private String addErrorForNotFoundColumn(Map<String, Object> dataItem, JsonStructure jsonStruct) {
        String fieldName = jsonStruct.getName().toLowerCase();
        if (jsonStruct.isRequired() && !columnNameExist(dataItem, fieldName)) {
            return "La colonne " + fieldName + " est manquante. ";
        }
        return "";
    }
 
    private String columnValueError(Object columnValue, JsonStructure jsonStruct, int i) {
        TypeDonnee typeDonnee = jsonStruct.getTypeDonnee();
 
        switch (typeDonnee) {
            case ALPHANUMERIQUE:
                if (!isAlphaNumericColumn(columnValue)) {
                    return "L'élément No " + i + " doit être alphanumérique";
                } else if (!lengthLowerOrEquals((String) columnValue, jsonStruct.getLengthh())) {
                    return "La taille de l'élément No " + i + " doit être inférieure ou égale à" + jsonStruct.getLengthh() + ";";
                }
                break;
            case DECIMAL:
                if (columnValue != null) {
 
                    String stringValue = columnValue.toString();
                    if (!GenericValidator.isDouble(stringValue)) {
                        return "L'élément No " + i + " doit être décimale";
                    } else if (!lengthLowerOrEquals(stringValue, jsonStruct.getLengthh())) {
                        return "La taille de l'élément No " + i + " doit être inférieure ou égale à " + jsonStruct.getLengthh() + ";";
                    }
 
                }
                break;
            case NUMERIQUE:
                if (columnValue != null) {
 
                    String stringValue = columnValue.toString();
                    if (!GenericValidator.isLong(stringValue)) {
                        return "L'élément No " + i + " doit être numérique;";
                    } else if (!lengthLowerOrEquals(stringValue, jsonStruct.getLengthh())) {
                        return "La taille de l'élément No " + i + " doit être inférieure ou égale à " + jsonStruct.getLengthh() + ";";
                    }
 
                }
                break;
            case DATE:
                if (columnValue != null) {
 
                    String stringValue = columnValue.toString();
                    if (!GenericValidator.isDate(stringValue, jsonStruct.getFormatDate(), true)) {
                        return "L'élément No " + i + " doit être une date";
                    } else if (!lengthEquals(stringValue, jsonStruct.getLengthh())) {
                        return "La taille de l'élément No " + i + " doit être égale à " + jsonStruct.getLengthh() + ";";
                    }
 
                    try {
                        new InsertionLocalDateTimeValue(jsonStruct.getFormatDate(), columnValue).value();
                    } catch (LocalDateTimeValueParseError ex) {
                        return "Impossible de parser la valeur " + stringValue + " au format " + jsonStruct.getFormatDate() + " pour l'élément No " + i + ";";
                    }
 
                }
                break;
            default:
                break;
        }
 
        return "";
    }
 
    private String columnValueError(Object columnValue, JsonStructure jsonStruct) {
        TypeDonnee typeDonnee = jsonStruct.getTypeDonnee();
 
        switch (typeDonnee) {
            case ALPHANUMERIQUE:
                if (!isAlphaNumericColumn(columnValue)) {
                    return "La colonne " + jsonStruct.getName() + " doit être alphanumérique;";
                } else if (!lengthLowerOrEquals((String) columnValue, jsonStruct.getLengthh())) {
                    return "La taille de la colonne " + jsonStruct.getName() + " doit être inférieure ou égale à" + jsonStruct.getLengthh() + ";";
                }
                break;
            case DECIMAL:
                if (columnValue != null) {
 
                    String stringValue = columnValue.toString();
                    if (!GenericValidator.isDouble(stringValue)) {
                        return "La colonne " + jsonStruct.getName() + " doit être décimale";
                    } else if (!lengthLowerOrEquals(stringValue, jsonStruct.getLengthh())) {
                        return "La taille de la colonne " + jsonStruct.getName() + " doit être inférieure ou égale à " + jsonStruct.getLengthh() + ";";
                    }
 
                }
                break;
            case NUMERIQUE:
                if (columnValue != null) {
 
                    String stringValue = columnValue.toString();
                    if (!GenericValidator.isLong(stringValue)) {
                        return "La colonne " + jsonStruct.getName() + " doit être numérique;";
                    } else if (!lengthLowerOrEquals(stringValue, jsonStruct.getLengthh())) {
                        return "La taille de la colonne " + jsonStruct.getName() + " doit être inférieure ou égale à " + jsonStruct.getLengthh() + ";";
                    }
 
                }
                break;
            case DATE:
                if (columnValue != null) {
 
                    String stringValue = columnValue.toString();
                    if (!GenericValidator.isDate(stringValue, jsonStruct.getFormatDate(), true)) {
                        return "La colonne " + jsonStruct.getName() + " doit être une date;";
                    } else if (!lengthEquals(stringValue, jsonStruct.getLengthh())) {
                        return "La taille de la colonne " + jsonStruct.getName() + " doit être égale à " + jsonStruct.getLengthh() + ";";
                    }
 
                    try {
                        new InsertionLocalDateTimeValue(jsonStruct.getFormatDate(), columnValue).value();
                    } catch (LocalDateTimeValueParseError ex) {
                        return "Impossible de parser la valeur " + stringValue + " au format " + jsonStruct.getFormatDate() + " pour la colonne " + jsonStruct.getName() + ";";
                    }
 
                }
                break;
            default:
                break;
        }
 
        return "";
    }
 
    private boolean isAlphaNumericColumn(Object columnValue) {
        return (columnValue == null || columnValue instanceof String);
    }
 
    private boolean lengthEquals(String value, int columnMaxLength) {
        return value.trim().length() == columnMaxLength;
    }
 
    private boolean lengthLowerOrEquals(String value, int columnMaxLength) {
        return value.trim().length() <= columnMaxLength;
    }
 
    private String elementNumberString(int index) {
        return "Elément No" + index;
    }
 
    private boolean columnNameExist(Map<String, Object> dataItem, String jsonStructName) {
        return dataItem.entrySet().stream().map(e -> e.getKey()).filter(key -> key.trim().toLowerCase().equals(jsonStructName)).findAny().isPresent();
    }
}