Kenmegne
7 days ago b3d0580439b9a00c7eb918085de1694151066004
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
/*
 * 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.fdxconvert.util;
 
import com.megatim.typefichier.validator.model.enums.FileExtension;
import com.megatim.typefichier.validator.utilities.Constantes;
import com.megatim.fdxconvert.exceptions.ValidatorException;
import com.megatim.fdxconvert.model.Validateur;
import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Map;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.NodeList;
 
/**
 *
 * @author ASUS
 */
public class ParserUtils {
 
    private ParserUtils() {
 
    }
 
    public static boolean isConvertDataBeforeValidation(File file) throws Exception {
        String extension = null;
        boolean result = true;
        Document doc = intialize(file);
        NodeList entityList = doc.getElementsByTagName("entity"); //Liste des noeud <entity>
 
        //Le validateur XML doit avoir au moins deux balises <entity> pour être conforme
        if (entityList.getLength() >= 2) {
            NamedNodeMap attributes = entityList.item(1).getAttributes();
 
            for (int i = 0; i < attributes.getLength(); i++) {
                String assertionAttributeName = attributes.item(i).getNodeName();
                String assertionAttributeValue = attributes.item(i).getNodeValue();
 
                if (assertionAttributeName.equalsIgnoreCase(Constantes.EXTENSION)) {
                    extension = assertionAttributeValue;
 
                    if (extension != null
                            && (extension.equalsIgnoreCase(FileExtension.CSV.name())
                            || extension.equalsIgnoreCase(FileExtension.XLS.name())
                            || extension.equalsIgnoreCase(FileExtension.XLSX.name()))) {
                        result = false;
                        break;
                    }
                }
            }
        }
        return result;
    }
 
    /**
     * Méthode qui extrait les informations de validation d'un fichier xml et
     * les renvoie dans une map
     *
     * @param validateur : Validateur dont on veut extraire les infos
     * @return : retourne une map de la forme
     * <position_colonne_dans_une_ligne_de_donnee, informations_sur_la_colonne>
     * @throws Exception
     */
    public static Map<Integer, Map> getValidateurElements(Validateur validateur) throws Exception {
        return com.megatim.typefichier.validator.utilities.ParserUtils.getValidateurElements(validateur.getContent());
    }
 
    /**
     * Méthode qui retire le caractère retour charriot dans une chaîne
     *
     * @param str
     * @return
     */
//    public static String removeReturnCharriot(String str) {
//        String result = str;
//
//        if (str != null && !str.isEmpty()) {
//            String[] tab = str.split("\n");
//            result = "";
//
//            for (String s : tab) {
//                result += s;
//            }
//        }
//        return result;
//    }
    /**
     * Méthode utilitaire pour extraire les données dans un fichier xml
     *
     * @param array
     * @return
     * @throws Exception
     */
    private static Document intialize(byte[] array) throws Exception {
 
        /**
         * Défini un factory qui aide à obtenir un parseur qui produit un arbre
         * d'objets DOM à partir d'un docuent XML.
         */
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
 
        /**
         * création d'un objet du builder pour parser le fichier XML.
         */
        DocumentBuilder db = dbf.newDocumentBuilder();
 
        Document doc = db.parse(new ByteArrayInputStream(array));
 
        doc.getDocumentElement().normalize();
 
        return doc;
    }
 
    private static Document intialize(File file) throws Exception {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document doc = db.parse(file);
        doc.getDocumentElement().normalize();
 
        return doc;
    }
 
    /**
     * Méthode pour obtenir l'objet de typr char correspondant à chaque
     * délimiteur
     *
     * @param delimiteur
     * @return
     */
    public static char characterOfDelimiteur(String delimiteur) {
        char character;
 
        switch (delimiteur) {
            case "\\t":
                character = '\t';
                break;
            case "\\n":
                character = '\n';
                break;
            case "":
                character = '\0';
                break;
            default:
                character = delimiteur.charAt(0);
        }
 
        return character;
    }
 
    /**
     * Méthode permettant d'encoder une chaîne de caractères
     *
     * @param datas : tableau de String à encoder
     * @param charset : encodage à utiliser
     * @return
     */
    public static String[] encodeStrings(String[] datas, Charset charset) {
        String[] encodedStrings = new String[datas.length];
 
        for (int i = 0; i < encodedStrings.length; i++) {
            byte[] bytesOfString = datas[i].getBytes();
            encodedStrings[i] = new String(bytesOfString, charset);
 
        }
        return encodedStrings;
    }
 
    /**
     * Méthode qui extrait une sous-chaîne dans une chaîne de caractères en
     * utilisant un délimiteur
     *
     * @param line : chaîne mère à séparer
     * @param character : délimiteur de chaîne
     * @return : retourne un tableau contenant les châines extraites
     */
    public static String[] splitIntoColumns(String line, char character) {
 
        int count = 0;
 
        for (int i = 0; i < line.length(); i++) {
 
            if (line.charAt(i) == character) {
                count++;
            }
 
        }
 
        String[] columns = new String[count + 1];
 
        StringBuilder builder = new StringBuilder(0);
 
        count = 0;
 
        for (int i = 0; i < line.length(); i++) {
 
            if (line.charAt(i) == character) {
 
                columns[count] = builder.toString();
 
                builder = new StringBuilder(0);
 
                count++;
 
            } else {
 
                builder.append(line.charAt(i));
            }
 
        }
 
        columns[count] = builder.toString();
 
        return columns;
    }
 
    /**
     * Méthode qui écrit dans un fichier
     *
     * @param finalColumnsTableLine : liste des châines à écrire dans le fichier
     * @param bufferWriter : ressource permettant d'écrire dans le fichier
     */
    public static void writeToFile(String[] finalColumnsTableLine, final BufferedWriter bufferWriter) throws IOException {
 
        //Ecriture dans le fichier output
        StringBuilder safeLineBuilder = new StringBuilder(0);
 
        for (String s : finalColumnsTableLine) {
            safeLineBuilder.append(s);
        }
 
        String safeLine = safeLineBuilder.toString();
 
        if (safeLine.length() > 0) {
            bufferWriter.write(safeLine + System.lineSeparator());
 
        }
    }
}