/* * 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.utils; import com.megatim.fdxcommons.model.enumeration.TypeDonnee; import com.megatim.fdxcommons.model.pojo.Constantes; import java.io.BufferedWriter; import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.nio.charset.Charset; import java.nio.file.Files; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.Map; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.apache.poi.ss.usermodel.CellValue; import org.apache.poi.ss.usermodel.DataFormatter; import org.apache.poi.ss.usermodel.DateUtil; import org.apache.poi.ss.usermodel.FormulaEvaluator; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.ss.util.NumberToTextConverter; import org.dhatim.fastexcel.reader.Cell; import org.w3c.dom.Document; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; /** * * @author ASUS */ public class ParserUtils { //Nombre be balise dans le validateur XML private static final int ENTITY_LIST_SIZE = 2; private ParserUtils() { } public static Map getValidateurElements(File file) throws Exception { byte[] bytes = Files.readAllBytes(file.toPath()); return getValidateurElements(bytes); } public static Map getValidateurElements(byte[] bytes) throws Exception { Document doc = intialize(bytes); NodeList entityList = doc.getElementsByTagName("entity"); //Liste des noeud //Map qui stocke le champ à une position, ainsi que les caractéristiques de champ(typeDonnee, taille, index de debut d'extraction) Map mapParams = new HashMap<>(); int position = 0; if (entityList.getLength() == ENTITY_LIST_SIZE) { //Liste des noeud de type du deuximème Noeud NodeList entityFileLineChildren = entityList.item(1).getChildNodes(); //parcours de la balise pour récupérer ses enfants for (int i = 0; i < entityFileLineChildren.getLength(); i++) { if (entityFileLineChildren.item(i) != null && entityFileLineChildren.item(i).getAttributes() != null) { //balise Node validation = entityFileLineChildren.item(i); if (validation != null) { position++; //Liste des assertions de la balise NodeList assertions = validation.getChildNodes(); for (int r = 0; r < assertions.getLength(); r++) { Node assertion = assertions.item(r); Map mapAttributes = new HashMap<>(); if (assertion != null && assertion.getAttributes() != null) { //Les attributs de la balise NamedNodeMap attributesAssertion = assertion.getAttributes(); for (int k = 0; k < attributesAssertion.getLength(); k++) { String nodeValue = attributesAssertion.item(k).getNodeValue(); String nodeName = attributesAssertion.item(k).getNodeName(); if (nodeName.equals("error-code")) { mapAttributes.put(nodeName, nodeValue); break; } } //Liste des balises de la balise NodeList params = assertion.getChildNodes(); Integer positionValue = null; for (int j = 0; j < params.getLength(); j++) { if (params.item(j) != null && params.item(j).getAttributes() != null) { //Les attributs de la balise NamedNodeMap attributesParamValue = params.item(j).getAttributes(); for (int k = 0; k < attributesParamValue.getLength(); k++) { String nodeValue = attributesParamValue.item(k).getNodeValue(); String nextNodeValue = attributesParamValue.item(++k).getNodeValue(); mapAttributes.put(nodeValue, nextNodeValue); if (nodeValue.equals(Constantes.POSITION)) { positionValue = Integer.valueOf(nextNodeValue); } } mapParams.put(positionValue != null ? positionValue : position, mapAttributes); } } } } } } } } return mapParams; } public static String getXlxsCellValue(org.apache.poi.ss.usermodel.Cell cell, Workbook wb, String typeDonnee, String formatDate) { if (cell != null) { String formatString = cell.getCellStyle().getDataFormatString(); switch (cell.getCellTypeEnum()) { case STRING: if (typeDonnee.equalsIgnoreCase(TypeDonnee.DATE.getValue())) { Date date = DateUtil.getJavaDate(Double.parseDouble(cell.getStringCellValue())); return formatDate(date, formatDate); } else if (typeDonnee.equalsIgnoreCase(TypeDonnee.NUMERIQUE.getValue())) { DataFormatter formatter = new DataFormatter(); String formattedValue = formatter.formatCellValue(cell); return formattedValue.replace(",", ""); } return cell.getStringCellValue(); case NUMERIC: if (typeDonnee.equalsIgnoreCase(TypeDonnee.DATE.getValue())) { Date date = DateUtil.getJavaDate(cell.getNumericCellValue()); return formatDate(date, formatDate); } else if (DateUtil.isCellDateFormatted(cell)) { return convertToDate(cell, formatDate); } else if (formatString != null && formatString.contains("%")) { return String.valueOf(cell.getNumericCellValue()); } else { return NumberToTextConverter.toText(cell.getNumericCellValue()); } case BOOLEAN: return String.valueOf(cell.getBooleanCellValue()); case BLANK: return ""; case FORMULA: FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator(); CellValue cellValue = evaluator.evaluate(cell); return cellValue.formatAsString(); default: return ""; } } return ""; } private static String convertToDate(org.apache.poi.ss.usermodel.Cell cell, String formatDate) { Date date = cell.getDateCellValue(); return formatDate(date, formatDate); } private static String formatDate(Date date, String formatDate) { SimpleDateFormat sdf = new SimpleDateFormat(formatDate != null && !formatDate.isEmpty() ? formatDate : "dd/MM/yyyy"); return sdf.format(date); } /** * Méthode permettant de convertir la données contenu dans une cellule excel * en chaîne de caractères * * @param cell * @return */ public static String getCellValueAsString(Cell cell) { String val = ""; if (cell != null) { switch (cell.getType()) { case EMPTY: break; case STRING: if (!cell.getText().equals("null")) { val = cell.getText().replaceAll("\\p{Cntrl}", ""); } break; case NUMBER: val = cell.asNumber().toPlainString(); if (val.equals("null")) { } break; case BOOLEAN: val = String.valueOf(cell.asBoolean()); if (val.equals("null")) { } break; default: break; } } return val; } /** * 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()); } } }