typefichier-validator/nb-configuration.xml
New file @@ -0,0 +1,18 @@ <?xml version="1.0" encoding="UTF-8"?> <project-shared-configuration> <!-- This file contains additional configuration written by modules in the NetBeans IDE. The configuration is intended to be shared among all the users of project and therefore it is assumed to be part of version control checkout. Without this configuration present, some functionality in the IDE may be limited or fail altogether. --> <properties xmlns="http://www.netbeans.org/ns/maven-properties-data/1"> <!-- Properties that influence various parts of the IDE, especially code formatting and the like. You can copy and paste the single properties, into the pom.xml file and the IDE will pick them up. That way multiple projects can share the same settings (useful for formatting rules for example). Any value defined here will override the pom.xml file value but is only applicable to the current project. --> <netbeans.hint.jdkPlatform>JDK_1.8</netbeans.hint.jdkPlatform> </properties> </project-shared-configuration> typefichier-validator/pom.xml
New file @@ -0,0 +1,120 @@ <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.megatim.typefichier.validator</groupId> <artifactId>typefichier-validator</artifactId> <version>1.0</version> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> <exec.mainClass>com.megatim.typefichier.validator.App</exec.mainClass> </properties> <dependencies> <dependency> <groupId>com.megatim</groupId> <artifactId>dynamicjsonparser</artifactId> <version>1.0</version> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.20</version> <scope>provided</scope> </dependency> <dependency> <groupId>com.megatim</groupId> <artifactId>moteur.predicat.validation</artifactId> <version>1.0-SNAPSHOT</version> </dependency> <dependency> <groupId>commons-validator</groupId> <artifactId>commons-validator</artifactId> <version>1.6</version> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j --> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-core</artifactId> <version>2.17.0</version> </dependency> <dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>18.0</version> </dependency> <dependency> <groupId>org.apache.tika</groupId> <artifactId>tika-parser-text-module</artifactId> <version>2.9.0</version> </dependency> <dependency> <groupId>org.burningwave</groupId> <artifactId>core</artifactId> <version>12.64.2</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.dataformat</groupId> <artifactId>jackson-dataformat-xml</artifactId> <version>2.15.2</version> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-text</artifactId> <version>1.10.0</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.17</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>3.17</version> </dependency> <dependency> <groupId>org.dhatim</groupId> <artifactId>fastexcel</artifactId> <version>0.14.0</version> </dependency> <!-- https://mvnrepository.com/artifact/org.dhatim/fastexcel-reader --> <dependency> <groupId>org.dhatim</groupId> <artifactId>fastexcel-reader</artifactId> <version>0.15.7</version> </dependency> </dependencies> <build> <plugins> <plugin> <artifactId>maven-assembly-plugin</artifactId> <version>3.0.0</version> <configuration> <archive> <manifest> <addClasspath>true</addClasspath> <mainClass>com.megatim.typefichier.validator.App</mainClass> </manifest> </archive> <descriptorRefs> <descriptorRef>jar-with-dependencies</descriptorRef> </descriptorRefs> </configuration> <executions> <execution> <id>make-my-jar-with-dependencies</id> <phase>package</phase> <goals> <goal>single</goal> </goals> </execution> </executions> </plugin> </plugins> </build> </project> typefichier-validator/src/main/java/com/megatim/dynamicjsonparser/pojo/Indexe.java
New file @@ -0,0 +1,46 @@ /* * 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.dynamicjsonparser.pojo; /** * * @author ASUS */ public class Indexe { private int position; private String fullQualifiedNameOfField; public Indexe(int position) { this.position = position; } public Indexe(int position, String fullQualifiedNameOfField) { this.position = position; this.fullQualifiedNameOfField = fullQualifiedNameOfField; } public Indexe(String fullQualifiedNameOfField) { this.fullQualifiedNameOfField = fullQualifiedNameOfField; } public int getPosition() { return position; } public void setPosition(int position) { this.position = position; } public String getFullQualifiedNameOfField() { return fullQualifiedNameOfField; } public void setFullQualifiedNameOfField(String fullQualifiedNameOfField) { this.fullQualifiedNameOfField = fullQualifiedNameOfField; } } typefichier-validator/src/main/java/com/megatim/dynamicjsonparser/pojo/JsonStructure.java
New file @@ -0,0 +1,60 @@ /* * 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.dynamicjsonparser.pojo; import com.megatim.dynamicjsonparser.enums.TypeDonnee; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlTransient; import lombok.Getter; import lombok.Setter; /** * * @author ASUS */ @Getter @Setter @XmlRootElement @XmlAccessorType(XmlAccessType.FIELD) public class JsonStructure implements Serializable { @XmlAttribute private TypeDonnee typeDonnee; @XmlAttribute private String name; @XmlAttribute private int lengthh; @XmlAttribute private boolean required; @XmlAttribute private boolean collection; @XmlAttribute private String formatDate; @XmlAttribute private String codeDelimiteurDate; @XmlTransient private TypeFichierJson typeFichierJson; @XmlTransient private JsonStructure parent; @XmlElement(name = "jsonStructure") private List<JsonStructure> fields = new ArrayList<>(); } typefichier-validator/src/main/java/com/megatim/dynamicjsonparser/pojo/TypeFichierJson.java
New file @@ -0,0 +1,28 @@ /* * 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.dynamicjsonparser.pojo; import java.io.Serializable; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; /** * @author ASUS */ @Getter @Setter @NoArgsConstructor @XmlRootElement(name = "typeFichierJson") @XmlAccessorType(XmlAccessType.FIELD) public class TypeFichierJson implements Serializable { private JsonStructure jsonStructure; } typefichier-validator/src/main/java/com/megatim/dynamicjsonparser/pojo/ValidationResult.java
New file @@ -0,0 +1,24 @@ /* * 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.dynamicjsonparser.pojo; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; /** * * @author ASUS */ @Getter @Setter @NoArgsConstructor @AllArgsConstructor public class ValidationResult { private int nbLines; private boolean valid; } typefichier-validator/src/main/java/com/megatim/dynamicjsonparser/pojo/exceptions/ValidatorException.java
New file @@ -0,0 +1,26 @@ /* * 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.dynamicjsonparser.pojo.exceptions; /** * * @author ASUS */ public class ValidatorException extends RuntimeException { public ValidatorException(String message) { super(message); } public ValidatorException(Throwable cause) { super(cause); } public ValidatorException(String message, Throwable cause) { super(message, cause); } } typefichier-validator/src/main/java/com/megatim/typefichier/validator/App.java
New file @@ -0,0 +1,66 @@ /* * 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.typefichier.validator; import com.google.common.io.ByteStreams; import com.megatim.typefichier.validator.model.ConfigStreamValidator; import com.megatim.typefichier.validator.model.ConfigValidator; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author STEPHANIE */ public class App { //private static final String INPUT_DIR = "C:\\Users\\STEPHANIE\\Desktop\\FDX\\IN\\DGI_NIU"; private static final String OUTPUT_DIR = "C:\\Users\\ASUS\\Documents\\VALIDATEURS\\TEST"; private static final String ERROR_DIR = "C:\\Users\\ASUS\\Documents\\VALIDATEURS\\TEST"; private static final String PREDICATE = "C:\\Users\\ASUS\\Documents\\VALIDATEURS\\TEST\\predicate.xml"; // private static final String VALIDATOR = "C:\\Users\\ASUS\\Documents\\VALIDATEURS\\TEST\\Fdx-ValidateurDGBART.xml"; private static final String VALIDATOR = "C:\\Users\\ASUS\\Documents\\VALIDATEURS\\Fdx-ValidatorDGBART-20260130-145525.xml"; public static void main(String[] args) { try { InputStream predicateStream = new FileInputStream(new File(PREDICATE)); InputStream validatorStream = new FileInputStream(new File(VALIDATOR)); File file = new File("C:\\Users\\ASUS\\Documents\\VALIDATEURS\\TEST\\DGBARTCSV.csv"); List<File> files = new ArrayList<>(); files.add(file); ConfigValidator configValidator = new ConfigValidator(PREDICATE,//chemin absolu vers le fichier de prédicat VALIDATOR, // CHEMIN ABSOLU VERS LE VALIDATEUR ERROR_DIR, //Répertoire de sortie des fichiers d'erreurs OUTPUT_DIR,//Répertoire de sortie des fichiers de succès files); // liste des fichiers à fichiers à valider Validator validator = new Validator(); ConfigStreamValidator val = new ConfigStreamValidator( ByteStreams.toByteArray(predicateStream),// Stream contenant le fichier de prédicat ByteStreams.toByteArray(validatorStream), // Stream contenant le validateur ERROR_DIR, //Répertoire de sortie des fichiers d'erreurs file );// liste des fichiers à fichiers à valider boolean result = new Validator().validate(val, Boolean.FALSE, Boolean.FALSE, 1); System.out.println("------------- result " + result); // ResultValidation resVal = validator.validate(val, // Boolean.FALSE, // précise si on veut déplacer les fichiers contenant des erreurs // Boolean.FALSE // précise si on veut déplacer les fichiers à succès // ); } catch (Exception ex) { Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex); } } } typefichier-validator/src/main/java/com/megatim/typefichier/validator/Validator.java
New file @@ -0,0 +1,132 @@ /* * 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.typefichier.validator; import com.megatim.dynamicjsonparser.extender.JsonDataValidator; import com.megatim.dynamicjsonparser.utils.Utility; import com.megatim.typefichier.validator.model.ConfigJsonValidator; import com.megatim.typefichier.validator.model.ConfigStreamValidator; import com.megatim.typefichier.validator.predicat.TypeFichierValidatorEngine; import com.megatim.typefichier.validator.utilities.TypeFichierJsonUnMarshaller; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.logging.Level; import java.util.logging.Logger; import javax.xml.bind.JAXBException; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; /** * * @author STEPHANIE */ @Getter @Setter @NoArgsConstructor public class Validator { public static final String ERROR_EXTENSION = ".err"; public boolean validate(final ConfigStreamValidator config, Boolean moveErrorFiles, Boolean moveSuccessFiles, int nbThreads) { File errDir = new File(config.getErrDir()); File outputDir; File errorFile = new File(errDir, config.getFileToValidate().getName() + ERROR_EXTENSION); errorFile.delete(); boolean valid = TypeFichierValidatorEngine.getInstance().validateTypeFichier(config, errorFile, nbThreads); try { if (!valid) { if (moveErrorFiles) { Files.deleteIfExists(Paths.get(errDir.getAbsolutePath(), config.getFileToValidate().getName())); Files.move(config.getFileToValidate().toPath(), Paths.get(errDir.getAbsolutePath(), config.getFileToValidate().getName())); if (config.getOriginalFile() != null && config.getOriginalFile().exists()) { Files.deleteIfExists(Paths.get(errDir.getAbsolutePath(), config.getOriginalFile().getName())); Files.move(config.getOriginalFile().toPath(), Paths.get(errDir.getAbsolutePath(), config.getOriginalFile().getName())); } } } else { if (errorFile.exists() && Files.size(errorFile.toPath()) == 0) { errorFile.delete(); } if (moveSuccessFiles && config.getOutputDir() != null && !config.getOutputDir().isEmpty()) { //Si on désire déplacer le fichier traité outputDir = new File(config.getOutputDir()); Files.deleteIfExists(Paths.get(outputDir.getAbsolutePath(), config.getFileToValidate().getName())); Files.move(config.getFileToValidate().toPath(), Paths.get(outputDir.getAbsolutePath(), config.getFileToValidate().getName())); if (config.getOriginalFile() != null && config.getOriginalFile().exists()) { Files.deleteIfExists(Paths.get(outputDir.getAbsolutePath(), config.getOriginalFile().getName())); Files.move(config.getOriginalFile().toPath(), Paths.get(outputDir.getAbsolutePath(), config.getOriginalFile().getName())); } } } } catch (Exception ex) { Logger.getLogger(Validator.class.getName()).log(Level.SEVERE, ex.getMessage(), ex); } return valid; } public boolean validate(final ConfigStreamValidator config, int nbThreads) { return TypeFichierValidatorEngine.getInstance().validateTypeFichier(config, nbThreads); } public boolean validate(String validatorPath, ConfigJsonValidator config, String storePath, Boolean moveErrorFiles, Boolean moveSuccessFiles, int nbThreads) throws IOException, JAXBException { config.setJsonFields(TypeFichierJsonUnMarshaller.unMarshallOne(validatorPath)); return doValidation(config, storePath, moveErrorFiles, moveSuccessFiles, nbThreads); } public boolean validate(ConfigJsonValidator config, String storePath, Boolean moveErrorFiles, Boolean moveSuccessFiles, int nbThreads) throws IOException { return doValidation(config, storePath, moveErrorFiles, moveSuccessFiles, nbThreads); } private boolean doValidation(ConfigJsonValidator config, String storePath, Boolean moveErrorFiles, Boolean moveSuccessFiles, int nbThreads) throws IOException { final String packageName = "com.megatim.dynamicjsonparser.generated"; JsonDataValidator jsonDataRetriever = new JsonDataValidator(); boolean result = jsonDataRetriever.validateDatas(config.getJsonFields(), storePath, packageName, config.getFileToValidate(), nbThreads); if (!result) { Utility.writeToFile(jsonDataRetriever.getParsedData().getErrors(), Paths.get(config.getErrorDir(), fileName(config.getFileToValidate().getName()) + ".txt.err")); if (moveErrorFiles) { //Supprimer fichier dans la destination Files.deleteIfExists(Paths.get(config.getErrorDir(), config.getFileToValidate().getName())); Files.move(config.getFileToValidate().toPath(), Paths.get(config.getErrorDir(), config.getFileToValidate().getName()) ); } } else { if (moveSuccessFiles) { String outputDir = config.getOutputDir(); //Supprimer fichier dans la destination Files.deleteIfExists(Paths.get(outputDir, config.getFileToValidate().getName())); Files.move(config.getFileToValidate().toPath(), Paths.get(outputDir, config.getFileToValidate().getName()) ); } } return result; } private String fileName(String name) { int extensionIndex = name.lastIndexOf("."); return name.substring(0, extensionIndex); } } typefichier-validator/src/main/java/com/megatim/typefichier/validator/model/ConfigJsonValidator.java
New file @@ -0,0 +1,37 @@ /* * 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.typefichier.validator.model; import com.megatim.dynamicjsonparser.pojo.JsonField; import java.io.File; import java.util.ArrayList; import java.util.List; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.Setter; /** * * @author ASUS */ @Getter @Setter @AllArgsConstructor public class ConfigJsonValidator { private String errorDir; private String outputDir; private File fileToValidate; List<JsonField> jsonFields = new ArrayList<>();// Objet contenant la liste des champs de la classe et leur description public ConfigJsonValidator(String errorDir, String outputDir, File fileToValidate) { this.errorDir = errorDir; this.outputDir = outputDir; this.fileToValidate = fileToValidate; } } typefichier-validator/src/main/java/com/megatim/typefichier/validator/model/ConfigStreamValidator.java
New file @@ -0,0 +1,39 @@ /* * 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.typefichier.validator.model; import java.io.File; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.Setter; /** * * @author STEPHANIE */ @Getter @Setter @AllArgsConstructor public class ConfigStreamValidator { private byte[] predicate; private byte[] validator; private String errDir; private String outputDir; private File fileToValidate; private File originalFile; public ConfigStreamValidator(byte[] predicate, byte[] validator, String errDir, File fileToValidate) { this.predicate = predicate; this.validator = validator; this.errDir = errDir; this.fileToValidate = fileToValidate; } } typefichier-validator/src/main/java/com/megatim/typefichier/validator/model/ConfigValidator.java
New file @@ -0,0 +1,26 @@ /* * 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.typefichier.validator.model; import java.io.File; import java.util.List; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.Setter; /** * * @author STEPHANIE */ @Getter @Setter @AllArgsConstructor public class ConfigValidator { private String predicateEngine;//chemin vers le fichier de predicat private String pathToValidator;//chemin vers validateur du typefichier private String errDir; // chemin vers le repertoire des fichiers d'erreur private String outputDir; // // chemin vers le repertoire des fichiers à success private List<File> files;// liste des fichiers à valider } typefichier-validator/src/main/java/com/megatim/typefichier/validator/model/ExcelFileLine.java
New file @@ -0,0 +1,32 @@ /* * 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.typefichier.validator.model; import java.util.Map; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; /** * * @author ASUS */ @Getter @Setter @NoArgsConstructor public class ExcelFileLine { private Map<Integer, String> columns; private String codeErreur; private int lineNumber; private int nbreColonnes; public ExcelFileLine(Map<Integer, String> columns, int lineNumber, int nbreColonnes) { this.columns = columns; this.lineNumber = lineNumber; this.nbreColonnes = nbreColonnes; } } typefichier-validator/src/main/java/com/megatim/typefichier/validator/model/FileLine.java
New file @@ -0,0 +1,40 @@ /* * 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.typefichier.validator.model; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; /** * Enitité qui stocke chaque ligne du fichier à valider * * @author mela */ @Getter @Setter @NoArgsConstructor public class FileLine { private String codeErreur; private String ligne; private int taille; private String fileName; private int numero; public FileLine(String line, int length, int numero, String fileName) { this.ligne = line; this.taille = length; this.numero = numero; this.fileName = fileName; } } typefichier-validator/src/main/java/com/megatim/typefichier/validator/model/FileValidator.java
New file @@ -0,0 +1,34 @@ /* * 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.typefichier.validator.model; import java.io.File; import java.util.List; import lombok.Getter; import lombok.Setter; /** * * @author STEPHANIE */ @Getter @Setter public class FileValidator { private List<File> files; private String errDir; private String validateurFile; private String predicatFile; // private String parent = ""; private String outputDir; public FileValidator(List<File> files, String errDir, String validateurFile, String predicatFile) { this.files = files; this.errDir = errDir; this.validateurFile = validateurFile; this.predicatFile = predicatFile; // if(file != null) // parent = file.getParent(); } } typefichier-validator/src/main/java/com/megatim/typefichier/validator/model/GenericTypeFichier.java
New file @@ -0,0 +1,61 @@ /* * 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.typefichier.validator.model; import java.io.File; import java.io.IOException; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; /** * stocke les info sur le nom du fichier et le nombre de ligne qu'il y a dans le * fichier (utile pour indiquer si le fichier est vide par ex) * * @author mela */ @Getter @Setter @NoArgsConstructor public class GenericTypeFichier { private File file; private String fileName; private String extension; private String fileNameWithExt; private String codeErreur; private int nbOfLines; public GenericTypeFichier(File file, int nbLines) throws IOException { this.file = file; this.fileNameWithExt = file.getName(); nbOfLines = nbLines; setAttributes(fileNameWithExt); } private void setAttributes(String name) { int lastIndex = name.lastIndexOf("."); if (lastIndex > 0) { fileName = name.substring(0, lastIndex); extension = name.substring(lastIndex + 1); } } } typefichier-validator/src/main/java/com/megatim/typefichier/validator/model/ResultValidation.java
New file @@ -0,0 +1,34 @@ /* * 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.typefichier.validator.model; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import lombok.Getter; import lombok.Setter; /** * * @author STEPHANIE */ @Getter @Setter public class ResultValidation { private Map<String, String> errors; private List<GenericTypeFichier> success; public ResultValidation() { errors = new HashMap<>(); success = new ArrayList<>(); } public void addSuccess(GenericTypeFichier gen) { this.success.add(gen); } } typefichier-validator/src/main/java/com/megatim/typefichier/validator/model/TypeFichierValidator.java
New file @@ -0,0 +1,69 @@ /* * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license * Click nbfs://nbhost/SystemFileSystem/Templates/Project/Maven2/JavaApp/src/main/java/${packagePath}/${mainClassName}.java to edit this template */ package com.megatim.typefichier.validator.model; /** * * @author STEPHANIE */ public class TypeFichierValidator { private String outputDir; private String inputDir; private String errDir; private String validateurFile; private String predicatFile; public TypeFichierValidator(String inputDir,String outputDir, String errDir, String validateurFile, String predicatFile) { this.outputDir = outputDir; this.inputDir = inputDir; this.errDir = errDir; this.validateurFile = validateurFile; this.predicatFile = predicatFile; } public String getOutputDir() { return outputDir; } public void setOutputDir(String outputDir) { this.outputDir = outputDir; } public String getInputDir() { return inputDir; } public void setInputDir(String inputDir) { this.inputDir = inputDir; } public String getErrDir() { return errDir; } public void setErrDir(String errDir) { this.errDir = errDir; } public String getValidateurFile() { return validateurFile; } public void setValidateurFile(String validateurFile) { this.validateurFile = validateurFile; } public String getPredicatFile() { return predicatFile; } public void setPredicatFile(String predicatFile) { this.predicatFile = predicatFile; } } typefichier-validator/src/main/java/com/megatim/typefichier/validator/model/ValidatorDescriptor.java
New file @@ -0,0 +1,52 @@ /* * 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.typefichier.validator.model; import com.megatim.typefichier.validator.model.enums.FileExtension; /** * * @author ASUS */ public class ValidatorDescriptor { private String lineDelimiter; private String columnDelimiter; private boolean headerPresent; private FileExtension extension; public String getLineDelimiter() { return lineDelimiter; } public void setLineDelimiter(String lineDelimiter) { this.lineDelimiter = lineDelimiter; } public String getColumnDelimiter() { return columnDelimiter; } public void setColumnDelimiter(String columnDelimiter) { this.columnDelimiter = columnDelimiter; } public boolean isHeaderPresent() { return headerPresent; } public void setHeaderPresent(boolean headerPresent) { this.headerPresent = headerPresent; } public FileExtension getExtension() { return extension; } public void setExtension(FileExtension extension) { this.extension = extension; } } typefichier-validator/src/main/java/com/megatim/typefichier/validator/model/enums/FileExtension.java
New file @@ -0,0 +1,28 @@ /* * 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.typefichier.validator.model.enums; /** * * @author ASUS */ public enum FileExtension { CSV, TXT, XLS, XLSX; public static FileExtension fromValeur(String value) { switch (value) { case "CSV": return FileExtension.CSV; case "TXT": return FileExtension.TXT; case "XLS": return FileExtension.XLS; case "XLSX": return FileExtension.XLSX; default: return null; } } } typefichier-validator/src/main/java/com/megatim/typefichier/validator/model/enums/TypeDonnee.java
New file @@ -0,0 +1,41 @@ package com.megatim.typefichier.validator.model.enums; public enum TypeDonnee { ALPHANUMERIQUE("ALPHANUMERIQUE"), NUMERIQUE("NUMERIQUE"), DECIMAL("DECIMAL"), DATE("DATE"); private final String value; private TypeDonnee(String value) { this.value = value; } public String getValue() { return value; } public static TypeDonnee fromValeur(String value) { switch (value) { case "ALPHANUMERIQUE": return TypeDonnee.ALPHANUMERIQUE; case "DATE": return TypeDonnee.DATE; case "NUMERIQUE": return TypeDonnee.NUMERIQUE; case "DECIMAL": return TypeDonnee.DECIMAL; default: return null; } } @Override public String toString() { return value; } } typefichier-validator/src/main/java/com/megatim/typefichier/validator/predicat/CalculPredicat.java
New file @@ -0,0 +1,84 @@ package com.megatim.typefichier.validator.predicat; import com.mgt.moteur.predicat.validation.context.ApplicationContext; import com.mgt.moteur.predicat.validation.core.ValidatorEngine; import java.io.ByteArrayInputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.Observable; import java.util.Observer; /** * * @author mela */ public class CalculPredicat implements Observer { //Validate un élément dans le moteur public static <T> PredicatResult<T> validateElement(final byte[] predicate, final byte[] validator, T element, int processNumber) throws Exception { PredicatResult predicatResult = new PredicatResult(); ValidatorEngine validatorEngine = new ValidatorEngine(); List<T> datas = new ArrayList<>(); datas.add(element); //On demarre la validation Map<String, List<List<?>>> result = validatorEngine.validateData(new ByteArrayInputStream(predicate), new ByteArrayInputStream(validator), processNumber, Arrays.asList(datas), null); //On recupere la liste des erreurs if (result.get(ApplicationContext.DIRTY_DATAS) != null) { List<T> errors = (List<T>) result.get(ApplicationContext.DIRTY_DATAS).get(0); predicatResult.setErrors(errors); } if (result.get(ApplicationContext.CLEAN_DATAS) != null) { List<T> success = (List<T>) result.get(ApplicationContext.CLEAN_DATAS).get(0); predicatResult.setSuccess(success); } return predicatResult; } public static <T> PredicatResult<T> validateElements(final byte[] predicate, final byte[] validator, List<T> elements, int processNumber) throws Exception { PredicatResult predicatResult = new PredicatResult(); ValidatorEngine validatorEngine = new ValidatorEngine(); //On demarre la validation Map<String, List<List<?>>> result = validatorEngine.validateData(new ByteArrayInputStream(predicate), new ByteArrayInputStream(validator), processNumber, Arrays.asList(elements), null); //On recupere la liste des erreurs if (result.get(ApplicationContext.DIRTY_DATAS) != null) { List<T> errors = (List<T>) result.get(ApplicationContext.DIRTY_DATAS).get(0); predicatResult.setErrors(errors); } if (result.get(ApplicationContext.CLEAN_DATAS) != null) { List<T> success = (List<T>) result.get(ApplicationContext.CLEAN_DATAS).get(0); predicatResult.setSuccess(success); } return predicatResult; } @Override public void update(Observable o, Object arg) { } } typefichier-validator/src/main/java/com/megatim/typefichier/validator/predicat/ConnectorImpl.java
New file @@ -0,0 +1,204 @@ /** * */ package com.megatim.typefichier.validator.predicat; import com.mgt.moteur.predicat.validation.ifaces.InvokeParam; import com.mgt.moteur.predicat.validation.ifaces.InvokeParams; import com.mgt.moteur.predicat.validation.tools.CommonToolsHelper; import java.util.HashMap; import java.util.Map; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; /** * @author * @since 18 nov. 2012 15:03:59 * */ public class ConnectorImpl { // Declaration gestionaire des logs private static Logger logger = LogManager.getLogger(ConnectorImpl.class); /** * Connecteur de négation * @param paramsMap * @return */ @InvokeParams({@InvokeParam(name="notParam", type="Boolean")}) public Boolean not(Map<String, Object> paramsMap) { // Logger method trace debug logger.trace("ConnectorImpl.not(paramsMap)"); // Method parametter trace logger.trace("not(paramsMap) : pramaValue(paramsMap) = " + CommonToolsHelper.toString(paramsMap)); Boolean notParam = (Boolean) paramsMap.get("notParam"); return (notParam == null)? true : ! notParam.booleanValue(); } /** * Unwrap Connecteur de négation * @param notParam * @return */ public Boolean not(Boolean notParam) { Map<String, Object> paramsMap = new HashMap<String, Object>(); paramsMap.put("notParam", notParam); return not(paramsMap); } /** * Connecteurs de réunion de deux propositions * @param paramsMap * @return */ @InvokeParams({@InvokeParam(name="orParam1", type="Boolean"), @InvokeParam(name="orParam2", type="Boolean")}) public static Boolean or(Map<String, Object> paramsMap) { // Logger method trace debug logger.trace("ConnectorImpl.or(paramsMap)"); // Method parametter trace logger.trace("or(paramsMap) : pramaValue(paramsMap) = " + CommonToolsHelper.toString(paramsMap)); Boolean orParam1 = (Boolean) paramsMap.get("orParam1"); Boolean orParam2 = (Boolean) paramsMap.get("orParam2"); return ((orParam1 == null)? false : orParam1.booleanValue()) || ((orParam2 == null)? false : orParam2.booleanValue()); } /** * Unwrap Connecteurs de réunion de deux propositions * @param orParam1 * @param orParam2 * @return */ public static Boolean or(Boolean orParam1, Boolean orParam2) { Map<String, Object> paramsMap = new HashMap<String, Object>(); paramsMap.put("orParam1", orParam1); paramsMap.put("orParam2", orParam2 ); return or(paramsMap); } /** * Connecteur de conjonction de deux propositions * @param paramsMap * @return */ @InvokeParams({@InvokeParam(name="andParam1", type="Boolean"), @InvokeParam(name="andParam2", type="Boolean")}) public static Boolean and(Map<String, Object> paramsMap) { // Logger method trace debug logger.trace("ConnectorImpl.and(paramsMap)"); // Method parametter trace logger.trace("and(paramsMap) : pramaValue(paramsMap) = " + CommonToolsHelper.toString(paramsMap)); Boolean andParam1 = (Boolean) paramsMap.get("andParam1"); Boolean andParam2 = (Boolean) paramsMap.get("andParam2"); return ((andParam1 == null)? false : andParam1.booleanValue()) && ((andParam2 == null)? false : andParam2.booleanValue()); } /** * Unwrap Connecteur de conjonction de deux propositions * @param andParam1 * @param andParam2 * @return */ public static Boolean and(Boolean andParam1, Boolean andParam2) { Map<String, Object> paramsMap = new HashMap<String, Object>(); paramsMap.put("andParam1", andParam1); paramsMap.put("andParam2", andParam2 ); return and(paramsMap); } /** * Connecteur d'implication de deux propositions * @param paramsMap * @return */ @InvokeParams({@InvokeParam(name="impliesAssumption", type="Boolean"), @InvokeParam(name="impliesConclusion", type="Boolean")}) public static Boolean implies(Map<String, Object> paramsMap) { // Logger method trace debug logger.trace("ConnectorImpl.implies(paramsMap)"); // Method parametter trace logger.trace("implies(paramsMap) : pramaValue(paramsMap) = " + CommonToolsHelper.toString(paramsMap)); Boolean impliesAssumption = (Boolean) paramsMap.get("impliesAssumption"); Boolean impliesConclusion = (Boolean) paramsMap.get("impliesConclusion"); boolean assumption= (impliesAssumption == null)? false : impliesAssumption.booleanValue(); boolean conclusion= (impliesConclusion == null)? false : impliesConclusion.booleanValue(); return (assumption==true && conclusion==false)? false : true; } /** * Unwrap Connecteur d'implication de deux propositions * @param impliesAssumption * @param impliesConclusion * @return */ public static Boolean implies(Boolean impliesAssumption, Boolean impliesConclusion) { Map<String, Object> paramsMap = new HashMap<String, Object>(); paramsMap.put("impliesAssumption", impliesAssumption); paramsMap.put("impliesConclusion", impliesConclusion ); return implies(paramsMap); } } typefichier-validator/src/main/java/com/megatim/typefichier/validator/predicat/ConstantsPredicat.java
New file @@ -0,0 +1,16 @@ /* * 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.typefichier.validator.predicat; /** * * @author STEPHANIE */ public class ConstantsPredicat { public static int BEGIN_TIERCE = 0; public static int END_TIERCE = 59; public static int NB_POS_TIERCE = 2; } typefichier-validator/src/main/java/com/megatim/typefichier/validator/predicat/Data.java
New file @@ -0,0 +1,22 @@ /* * 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.typefichier.validator.predicat; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; /** * * @author mela */ @Getter @Setter @NoArgsConstructor @AllArgsConstructor public class Data { private String data; private String dataType; } typefichier-validator/src/main/java/com/megatim/typefichier/validator/predicat/PredicatResult.java
New file @@ -0,0 +1,25 @@ /* * 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.typefichier.validator.predicat; import java.util.List; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; /** * * @author mela */ @Getter @Setter @NoArgsConstructor @AllArgsConstructor public class PredicatResult <T> { List<T> errors; List<T> success; } typefichier-validator/src/main/java/com/megatim/typefichier/validator/predicat/PredicateImpl.java
New file @@ -0,0 +1,1954 @@ /** * */ package com.megatim.typefichier.validator.predicat; import com.megatim.typefichier.validator.model.enums.TypeDonnee; import com.megatim.typefichier.validator.utilities.Constantes; import com.mgt.moteur.predicat.validation.ifaces.InvokeParam; import com.mgt.moteur.predicat.validation.ifaces.InvokeParams; import com.mgt.moteur.predicat.validation.tools.CommonToolsHelper; import java.lang.reflect.Array; import java.math.BigDecimal; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import org.apache.commons.validator.GenericValidator; /** * @author @since 18 nov. 2012 18:50:25 * */ @SuppressWarnings({"rawtypes", "unchecked"}) public class PredicateImpl { // Declaration gestionaire des logs //private static Logger logger = Logger.getLogger(PredicateImpl.class); private static Class lockObject = PredicateImpl.class; @InvokeParams( { @InvokeParam(name = "fieldToCheck", type = "String"), @InvokeParam(name = "values", type = "String")}) public static Boolean inValues(Map<String, Object> paramsMap) { boolean result = false; try { String fieldToCheck = (String) paramsMap.get("fieldToCheck"); String values = (String) paramsMap.get("values"); String[] tab = values.split(","); for (String value : tab) { if (value.trim().equals(fieldToCheck.trim())) { result = true; break; } } } catch (Exception ex) { } return result; } @InvokeParams({ @InvokeParam(name = Constantes.LIBELLE_INDEX, type = "int"), @InvokeParam(name = Constantes.LIBELLE_TAILLE, type = "int"), @InvokeParam(name = Constantes.LIBELLE_TYPE_DONNEE, type = "String"), @InvokeParam(name = Constantes.LIBELLE_FORMAT_DATE, type = "String"), @InvokeParam(name = Constantes.LIBELLE_SEPARATEUR_DATE, type = "String"), @InvokeParam(name = Constantes.LIBELLE_TAILLE_PARTIE_DECIMALE, type = "int"), @InvokeParam(name = Constantes.LIBELLE_SEPARATEUR_DECIMAL, type = "String"), @InvokeParam(name = Constantes.LIBELLE_LIGNE, type = "String")}) public static Boolean ifTypeFichier(Map<String, Object> paramsMap) { boolean result = false; try { int indexValue = Integer.parseInt((String) paramsMap.get(Constantes.LIBELLE_INDEX)); int tailleValue = Integer.parseInt((String) paramsMap.get(Constantes.LIBELLE_TAILLE)); String ligneValue = (String) paramsMap.get(Constantes.LIBELLE_LIGNE); String typeDonneeValue = ((String) paramsMap.get(Constantes.LIBELLE_TYPE_DONNEE)).toUpperCase(); if (ligneValue != null && !ligneValue.isEmpty()) { String data = ligneValue.substring(indexValue, indexValue + tailleValue); if (typeDonneeValue.equalsIgnoreCase(TypeDonnee.DATE.getValue())) { //Si la date est une sucession de chaine vide, alors elle est bien formatée if (data.trim().isEmpty()) { result = true; } else { String separateurValue = (String) paramsMap.get(Constantes.LIBELLE_SEPARATEUR_DATE); String formatValue = (String) paramsMap.get(Constantes.LIBELLE_FORMAT_DATE); if (formatValue != null) { if (!formatValue.isEmpty()) { result = isDate(separateurValue == null ? "" : separateurValue, formatValue, data, tailleValue); } } } } else if (typeDonneeValue.equalsIgnoreCase(TypeDonnee.NUMERIQUE.getValue())) { result = isNumeric(data, tailleValue); } else if (typeDonneeValue.equalsIgnoreCase(TypeDonnee.ALPHANUMERIQUE.getValue())) { result = true; } else if (typeDonneeValue.equalsIgnoreCase(TypeDonnee.DECIMAL.getValue())) { int taillePartieDecimale = Integer.parseInt((String) paramsMap.get(Constantes.LIBELLE_TAILLE_PARTIE_DECIMALE)); String separateurDecimalValue = (String) paramsMap.get(Constantes.LIBELLE_SEPARATEUR_DECIMAL); String number = ligneValue.substring(indexValue, indexValue + tailleValue + taillePartieDecimale + separateurDecimalValue.length()).trim(); result = isDecimal(number, separateurDecimalValue, tailleValue, taillePartieDecimale); } } } catch (Exception ex) { Logger.getLogger(PredicateImpl.class.getName()).log(Level.SEVERE, ex.getMessage(), ex); } return result; } @InvokeParams({ @InvokeParam(name = Constantes.LIBELLE_POSITION, type = "int"), @InvokeParam(name = Constantes.LIBELLE_TYPE_DONNEE, type = "String"), @InvokeParam(name = Constantes.LIBELLE_FORMAT_DATE, type = "String"), @InvokeParam(name = Constantes.LIBELLE_SEPARATEUR_DATE, type = "String"), @InvokeParam(name = Constantes.LIBELLE_SEPARATEUR_DECIMAL, type = "String"), @InvokeParam(name = Constantes.LIBELLE_TAILLE_PARTIE_DECIMALE, type = "int"), @InvokeParam(name = Constantes.LIBELLE_TAILLE, type = "int"), @InvokeParam(name = Constantes.LIBELLE_LIGNE, type = "String")}) public static Boolean ifTypeFichierCsv(Map<String, Object> paramsMap) { boolean result = false; try { int position = Integer.parseInt((String) paramsMap.get(Constantes.LIBELLE_POSITION)); int taille = Integer.parseInt((String) paramsMap.get(Constantes.LIBELLE_TAILLE)); Map<Integer, String> colums = (HashMap) paramsMap.get(Constantes.LIBELLE_LIGNE); String typeDonneeValue = ((String) paramsMap.get(Constantes.LIBELLE_TYPE_DONNEE)).toUpperCase(); if (colums != null && !colums.isEmpty()) { String data = colums.get(position); if (typeDonneeValue.equalsIgnoreCase(TypeDonnee.DATE.getValue())) { //Si la date est une chaine vide, alors elle est bien formatée if (data.trim().isEmpty()) { result = true; } else { String separateurValue = (String) paramsMap.get(Constantes.LIBELLE_SEPARATEUR_DATE); String formatValue = (String) paramsMap.get(Constantes.LIBELLE_FORMAT_DATE); if (formatValue != null) { if (!formatValue.isEmpty()) { result = isDate(separateurValue == null ? "" : separateurValue, formatValue, data, taille); } } } } else if (typeDonneeValue.equalsIgnoreCase(TypeDonnee.NUMERIQUE.getValue())) { result = isNumeric(data, taille); } else if (typeDonneeValue.equalsIgnoreCase(TypeDonnee.ALPHANUMERIQUE.getValue())) { result = data.trim().length() <= taille; } else if (typeDonneeValue.equalsIgnoreCase(TypeDonnee.DECIMAL.getValue())) { String separateurDecimalValue = (String) paramsMap.get(Constantes.LIBELLE_SEPARATEUR_DECIMAL); int taillePartieDecimale = Integer.parseInt((String) paramsMap.get(Constantes.LIBELLE_TAILLE_PARTIE_DECIMALE)); result = isDecimal(data, separateurDecimalValue, taille, taillePartieDecimale); } } } catch (Exception ex) { Logger.getLogger(PredicateImpl.class.getName()).log(Level.SEVERE, ex.getMessage(), ex); } return result; } private static boolean isNumeric(String data, int taille) { data = data .trim() .replaceAll("\\s+", "") .replaceAll("\\u00A0", "")//nbsp .replaceAll(" ", "")//nbsp .replaceAll("\\p{Z}", "") .replaceAll("\t", "") .replaceAll("\r", "") .replaceAll("\n", ""); if (data.isEmpty()) { return true; } else { data = new BigDecimal(data.replace(',', '.')).toPlainString() + "";//Remplacer la virgule par le point return data.length() <= taille && data.matches("\\d+|[-]\\d+"); } } private static boolean isDecimal(String data, String separateurDecimalValue, int taille, int taillePartieDecimale) { data = data .trim() .replaceAll("\\s+", "") .replaceAll("\\u00A0", "")//nbsp .replaceAll(" ", "")//nbsp .replaceAll("\\p{Z}", "") .replaceAll("\t", "") .replaceAll("\r", "") .replaceAll("\n", ""); if (isNumeric(data, taille)) { return true; } else { try { data = new BigDecimal(data.replace(',', '.')).toPlainString();//Remplacer la virgule par le point } catch (Exception ex) { return false; } return data.length() <= taille + taillePartieDecimale + separateurDecimalValue.length(); } } private static boolean isDate(String separateurValue, String formatValue, String data, int taille) { data = data.trim() .replaceAll("\\s+", "") .replaceAll("\\u00A0", "")//nbsp .replaceAll(" ", ""); if (data.length() != taille) { return false; } //Retirer le séparateur avant validation if (separateurValue != null && !separateurValue.isEmpty()) { String[] dateArray = data.split(separateurValue); StringBuilder dateToValidate = new StringBuilder(0); for (String d : dateArray) { dateToValidate.append(d); } data = dateToValidate.toString(); } return formatValue != null && !formatValue.isEmpty() && GenericValidator.isDate(data, formatValue, true); } @InvokeParams({ @InvokeParam(name = Constantes.LIBELLE_FORMAT_DATE, type = "String"), @InvokeParam(name = "prefixe", type = "String"), @InvokeParam(name = "type_suffixe", type = "String"), @InvokeParam(name = "fileName", type = "String")}) public static Boolean ifTypeFichierFileName(Map<String, Object> paramsMap) { //Variables boolean result = false; try { // Lecture des paramettres d'entrée String formatValue = (String) paramsMap.get(Constantes.LIBELLE_FORMAT_DATE); String prefixeValue = (String) paramsMap.get("prefixe"); String type_suffixeValue = (String) paramsMap.get("type_suffixe"); String fileNameValue = (String) paramsMap.get("fileName"); if (fileNameValue != null && !fileNameValue.isEmpty()) { if (fileNameValue.startsWith(prefixeValue)) { if (type_suffixeValue.equalsIgnoreCase(TypeDonnee.DATE.getValue())) { String date = fileNameValue.substring(prefixeValue.length()); //date sans tierce if (date.length() == formatValue.length()) { result = GenericValidator.isDate(date, formatValue, true); } else { //Date avec tierce String str = date.substring(0, formatValue.length()); boolean result1 = GenericValidator.isDate(str, formatValue, true); String tierce = date.substring(formatValue.length()); if (tierce.length() == ConstantsPredicat.NB_POS_TIERCE) { if (GenericValidator.isInt(tierce)) { int tierceValue = Integer.parseInt(tierce); result = result1 && tierceValue >= ConstantsPredicat.BEGIN_TIERCE && tierceValue <= ConstantsPredicat.END_TIERCE; } } } } else if (type_suffixeValue.equalsIgnoreCase(TypeDonnee.NUMERIQUE.getValue())) { BigDecimal big = new BigDecimal(type_suffixeValue); result = true; } } } } catch (Exception ex) { //Logger.getLogger(PredicateImpl.class.getName()).log(Level.SEVERE, ex.getMessage(), ex); } return result; } @InvokeParams({ @InvokeParam(name = "version", type = "String"), @InvokeParam(name = "nbPosition", type = "int"), @InvokeParam(name = "typeCharactere", type = "String")}) public static Boolean ifVersion(Map<String, Object> paramsMap) { //Variables boolean result = true; try { // Lecture des paramettres d'entrée String versionValue = (String) paramsMap.get("version"); int nbPositionValue = Integer.parseInt((String) paramsMap.get("nbPosition")); String typeCharactereValue = (String) paramsMap.get("typeCharactere"); if (versionValue.length() == nbPositionValue) { if (typeCharactereValue.equalsIgnoreCase("digit")) { for (int i = 0; i < versionValue.length(); i++) { if (!Character.isDigit(versionValue.charAt(i))) { result = false; break; } } } } else { result = false; } } catch (Exception ex) { result = false; //Logger.getLogger(PredicateImpl.class.getName()).log(Level.SEVERE, ex.getMessage(), ex); } return result; } /** * @param paramsMap * @return */ @InvokeParams({ @InvokeParam(name = Constantes.LIBELLE_INDEX, type = "int"), @InvokeParam(name = "fileName", type = "fileName"), @InvokeParam(name = "format", type = "String")}) public static Boolean ifDate(Map<String, Object> paramsMap) { //Variables boolean result = false; try { // Lecture des paramettres d'entrée String formatValue = (String) paramsMap.get("format"); String fileName = (String) paramsMap.get("fileName"); int index = Integer.parseInt((String) paramsMap.get(Constantes.LIBELLE_INDEX)); String dateValue = fileName.substring(index, index + formatValue.length()); result = GenericValidator.isDate(dateValue, formatValue, true); } catch (Exception ex) { // Logger.getLogger(PredicateImpl.class.getName()).log(Level.SEVERE, ex.getMessage(), ex); } return result; } @InvokeParams({ @InvokeParam(name = Constantes.LIBELLE_INDEX, type = "int"), @InvokeParam(name = "maxValue", type = "int"), @InvokeParam(name = "minValue", type = "int"), @InvokeParam(name = "fileName", type = "String")}) public static Boolean ifTierce(Map<String, Object> paramsMap) { boolean result = false; try { int index = Integer.parseInt((String) paramsMap.get(Constantes.LIBELLE_INDEX)); int maxValue = Integer.parseInt((String) paramsMap.get("maxValue")); int minValue = Integer.parseInt((String) paramsMap.get("minValue")); String fileName = (String) paramsMap.get("fileName"); if (index < fileName.length()) { String tierce = fileName.substring(index); int tierceValue = Integer.parseInt(tierce); result = (tierceValue >= minValue) && (tierceValue <= maxValue); } else { result = true; } } catch (Exception ex) { Logger.getLogger(PredicateImpl.class.getName()).log(Level.SEVERE, ex.getMessage(), ex); } return result; } @InvokeParams({ @InvokeParam(name = Constantes.LIBELLE_INDEX, type = "int"), @InvokeParam(name = Constantes.LIBELLE_TAILLE, type = "int"), @InvokeParam(name = Constantes.LIBELLE_TYPE_DONNEE, type = "String"), @InvokeParam(name = Constantes.LIBELLE_LIGNE, type = "String"), @InvokeParam(name = Constantes.LIBELLE_TAILLE_PARTIE_DECIMALE, type = "int"), @InvokeParam(name = "separator", type = "char") }) public static Boolean ifDecimal(Map<String, Object> paramsMap) { boolean result; try { // Récupération des données dans la Map des paramètres String ligne = (String) paramsMap.get(Constantes.LIBELLE_LIGNE); String separator = (String) paramsMap.get("separator"); int taille = Integer.parseInt((String) paramsMap.get(Constantes.LIBELLE_TAILLE)); int index = Integer.parseInt((String) paramsMap.get(Constantes.LIBELLE_INDEX)); String number = ligne.substring(index, index + taille); String regex = "^[0-9]+" + separator + "{1}[0-9]+$"; result = (separator.equals(".") || separator.equals(",")) && GenericValidator.matchRegexp(number, regex); } catch (Exception ex) { result = false; Logger.getLogger(PredicateImpl.class.getName()).log(Level.SEVERE, ex.getMessage(), ex); } return result; } @InvokeParams({ @InvokeParam(name = Constantes.LIBELLE_INDEX, type = "int"), @InvokeParam(name = Constantes.LIBELLE_TAILLE, type = "int"), @InvokeParam(name = "code", type = "String"), @InvokeParam(name = "fileName", type = "String")}) public static Boolean ifCodeAgentOrCodeParticipant(Map<String, Object> paramsMap) { //Variables boolean result = false; try { int index = Integer.parseInt((String) paramsMap.get(Constantes.LIBELLE_INDEX)); int taille = Integer.parseInt((String) paramsMap.get(Constantes.LIBELLE_TAILLE)); String fileName = (String) paramsMap.get("fileName"); String codeAgent = (String) paramsMap.get("code"); result = fileName.substring(index, index + taille).equals(codeAgent); } catch (Exception ex) { Logger.getLogger(PredicateImpl.class.getName()).log(Level.SEVERE, ex.getMessage(), ex); } return result; } /** * * @param paramsMap * @return */ @InvokeParams({ @InvokeParam(name = "nbFiles", type = "String")}) public static Boolean ifNumber(Map<String, Object> paramsMap) { boolean result = false; try { String nbFilesValue = (String) paramsMap.get("nbFiles"); result = GenericValidator.isLong(nbFilesValue); } catch (Exception ex) { //Logger.getLogger(PredicateImpl.class.getName()).log(Level.SEVERE, ex.getMessage(), ex); } return result; } /** * Prédicat de vérification la 4ème partie de l'archive referentiel, en * l'occurence le code de la remise * * @param paramsMap * @return */ @InvokeParams({ @InvokeParam(name = "codeRemise", type = "String"), @InvokeParam(name = "nbPosition", type = "int"), @InvokeParam(name = "typeCharactere", type = "String")}) public static Boolean ifCodeRemise(Map<String, Object> paramsMap) { boolean result = true; try { // Lecture des paramettres d'entrée String codeRemiseValue = (String) paramsMap.get("codeRemise"); int nbPositionValue = Integer.parseInt((String) paramsMap.get("nbPosition")); String typeCharactereValue = (String) paramsMap.get("typeCharactere"); if (codeRemiseValue.length() == nbPositionValue) { if (typeCharactereValue.equalsIgnoreCase("digit")) { for (int i = 0; i < codeRemiseValue.length(); i++) { if (!Character.isDigit(codeRemiseValue.charAt(i))) { result = false; break; } } } } else { result = false; } } catch (Exception ex) { result = false; // Logger.getLogger(PredicateImpl.class.getName()).log(Level.SEVERE, ex.getMessage(), ex); } return result; } /** * Predicat d'égalité * * @param paramsMap * @return */ @InvokeParams({ @InvokeParam(name = "equalParam", type = "Object"), @InvokeParam(name = "equalValue", type = "Object")}) public static Boolean equal(Map<String, Object> paramsMap) { // Logger method trace debug //logger.trace("PredicateImpl.equal(paramsMap)"); Object equalParam = (Object) paramsMap.get("equalParam"); Object equalValue = (Object) paramsMap.get("equalValue"); // Variable temporaire de stockage Object tmpEqualParam = equalParam; Object tmpEqualValue = equalValue; // Test de nulité des paramettres if (equalParam == null || equalValue == null) { return false; } //Transformation des numériques stockés en chaine de caractère en BigDecimal tmpEqualParam = CommonToolsHelper.convertIfStringToBigDecimal(equalParam); tmpEqualValue = CommonToolsHelper.convertIfStringToBigDecimal(equalValue); // Traitement des nombres stockés ous formes de chaine de caractère if (tmpEqualParam instanceof BigDecimal && tmpEqualValue instanceof BigDecimal && ((BigDecimal) tmpEqualParam).compareTo((BigDecimal) tmpEqualValue) == 0) { return true; } // Traitement des types chaines de charactères if (equalParam instanceof String && equalValue instanceof String && ((String) equalParam).trim().equalsIgnoreCase(((String) equalValue).trim())) { return true; } // Test d'incohérence hiérachique if (!equalParam.getClass().isInstance(equalValue) && !equalValue.getClass().isInstance(equalParam)) { return false; } // Test de comparabilité par l'implémentation de l'interface comparable if ((equalParam instanceof Comparable) && ((Comparable) equalParam).compareTo(equalValue) == 0) { return true; } // Test de comparabilité par l'implémentation de l'interface comparable if ((equalValue instanceof Comparable) && ((Comparable) equalValue).compareTo(equalParam) == 0) { return true; } // Test de filiation par héritage if (equalParam.getClass().isInstance(equalValue)) { return equalParam.equals(equalValue); } // Test de filiation par héritage if (equalValue.getClass().isInstance(equalParam)) { return equalValue.equals(equalParam); } // Comparaison par défaut de la classe object return equalParam.equals(equalValue) || equalValue.equals(equalParam); } /** * UnWrapper Predicat d'égalité * * @param equalValue * @param equalParam * @return */ public static Boolean equal(Object equalValue, Object equalParam) { Map<String, Object> paramsMap = new HashMap<String, Object>(); paramsMap.put("equalValue", equalValue); paramsMap.put("equalParam", equalParam); return equal(paramsMap); } /** * Predicat de nullité d'un objet * * @param paramsMap * @return */ @InvokeParams({ @InvokeParam(name = "emptyParam", type = "Object")}) public static Boolean empty(Map<String, Object> paramsMap) { // Logger method trace debug //logger.trace("PredicateImpl.empty(paramsMap)"); Object emptyParam = (Object) paramsMap.get("emptyParam"); // Gestion de l'objet non reférencé if (emptyParam == null) { return true; } // Gestion du cas d'une chaine de caractère if (emptyParam instanceof String && ((String) emptyParam).trim().isEmpty()) { return true; } // Gestion du cas d'un tableau de données if (emptyParam.getClass().isArray() && Array.getLength(emptyParam) == 0) { return true; } // Gestion du cas d'une collection if (emptyParam instanceof Collection && ((Collection) emptyParam).isEmpty() == true) { return true; } // Gestion du cas d'une map if (emptyParam instanceof Map && ((Map) emptyParam).isEmpty() == true) { return true; } return false; } /** * Unwrap predicat de nullité d'un objet * * @param emptyParam * @return */ public static Boolean empty(Object emptyParam) { Map<String, Object> paramsMap = new HashMap<String, Object>(); paramsMap.put("emptyParam", emptyParam); return empty(paramsMap); } /** * Unwrap predicat de non nullité d'une collection de valeur * * @param notEmptyValuesParam collection des valeurs à verifier * @return */ public static Boolean notEmptyValues(Object notEmptyValuesParam) { Map<String, Object> paramsMap = new HashMap<String, Object>(); paramsMap.put("notEmptyValuesParam", notEmptyValuesParam); return notEmptyValues(paramsMap); } /** * Predicat de non nullité d'une collection d'oject, retourne la valeur vrai * si et seulement si toutes les valeurs de la collection sont non nulles * * @param paramsMap * @return */ @InvokeParams({ @InvokeParam(name = "notEmptyValuesParam", type = "Collection")}) public static Boolean notEmptyValues(Map<String, Object> paramsMap) { /** * Logger method trace debug */ //logger.trace("PredicateImpl.emptyList(paramsMap)"); Object notEmptyValuesParam = (Object) paramsMap.get("notEmptyValuesParam"); // Gestion de l'objet non reférencé if (notEmptyValuesParam == null) { return false; } // Gestion du cas d'une chaine de caractère if (notEmptyValuesParam instanceof String) { if (((String) notEmptyValuesParam).trim().isEmpty() == true) { return false; } } // Gestion du cas d'un tableau de données if (notEmptyValuesParam.getClass().isArray()) { for (int i = 0; i < Array.getLength(notEmptyValuesParam); i++) { if (empty(Array.get(notEmptyValuesParam, i))) { return false; } } } // Gestion du cas d'une collection if (notEmptyValuesParam instanceof Collection) { for (Object obj : (Collection) notEmptyValuesParam) { if (empty(obj)) { return false; } } } // Gestion du cas d'une map if (notEmptyValuesParam instanceof Map) { for (Object obj : ((Map) notEmptyValuesParam).entrySet()) { if (empty(obj)) { return false; } } } return true; } /** * Unwrap Prédicate de vérification de la nulité d'une collection de valeur * * @param emptyValuesParam collection de valeur à vérifier * @return */ public static Boolean emptyValues(Object emptyValuesParam) { Map<String, Object> paramsMap = new HashMap<String, Object>(); paramsMap.put("emptyValuesParam", emptyValuesParam); return emptyValues(paramsMap); } /** * Prédicate de vérification de la nulité d'une collection de valeur, * retourne vrai ssi toutes les valeurs sont nulles * * @param paramsMap * @return */ @InvokeParams({ @InvokeParam(name = "emptyValuesParam", type = "collection")}) public static Boolean emptyValues(Map<String, Object> paramsMap) { /** * Logger method trace debug */ //logger.trace("PredicateImpl.emptyValues(paramsMap)"); // Lecture des paramettres d'entrée Object emptyValuesParam = paramsMap.get("emptyValuesParam"); // Gestion de l'objet non reférencé if (emptyValuesParam == null) { return true; } // Gestion du cas d'une chaine de caractère if (emptyValuesParam instanceof String) { if (((String) emptyValuesParam).trim().isEmpty()) { return true; } } // Gestion du cas d'un tableau de données if (emptyValuesParam.getClass().isArray()) { for (int i = 0; i < Array.getLength(emptyValuesParam); i++) { if (!empty(Array.get(emptyValuesParam, i))) { return false; } } return true; } // Gestion du cas d'une collection if (emptyValuesParam instanceof Collection) { for (Object obj : (Collection) emptyValuesParam) { if (!empty(obj)) { return false; } } return true; } // Gestion du cas d'une map if (emptyValuesParam instanceof Map) { for (Object obj : ((Map) emptyValuesParam).entrySet()) { if (!empty(obj)) { return false; } } return true; } // Object non nulle return false; } /** * Prédicat de vérification de la conformité entre la date et le format * fournit * * @param paramsMap * @return */ @InvokeParams({ @InvokeParam(name = "dateValue", type = "String"), @InvokeParam(name = "dateFormat", type = "String")}) public static Boolean dateFormat(Map<String, Object> paramsMap) { // Logger method trace debug //logger.trace("PredicateImpl.dateFormat(paramsMap)"); String dateValue = (String) paramsMap.get("dateValue"); String dateFormat = (String) paramsMap.get("dateFormat"); /* * Declaration des variables locales */ SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormat); Date date = null; /* * Test de nullité */ if (dateValue == null || dateValue.trim().isEmpty() || dateFormat == null || dateFormat.trim().isEmpty()) { return false; } /* * Test de longueur */ if (dateValue.trim().length() != dateFormat.trim().length()) { return false; } try { // Test de format date = simpleDateFormat.parse(dateValue); // Test de reversibilité if (!simpleDateFormat.format(date).equalsIgnoreCase(dateValue)) { return false; } } catch (ParseException e) { return false; } return true; } /** * UnWrap Prédicat de vérification de la conformité entre la date et le * format fournit * * @param dateValue * @param dataFormat * @return */ public static Boolean dateFormat(String dateValue, String dateFormat) { Map<String, Object> paramsMap = new HashMap<String, Object>(); paramsMap.put("dateValue", dateValue); paramsMap.put("dateFormat", dateFormat); return dateFormat(paramsMap); } /** * prédicat de vérification d'appartenance d'une entrée à une liste * d'element csv * * @param paramsMap * @return */ @InvokeParams({ @InvokeParam(name = "entryValue", type = "String"), @InvokeParam(name = "csvValues", type = "Object")}) public static Boolean csvEntry(Map<String, Object> paramsMap) { // Logger method trace debug //logger.trace("PredicateImpl.csvEntry(paramsMap)"); String entryValue = (String) paramsMap.get("entryValue"); Object csvValues = paramsMap.get("csvValues"); /** * Traitment du cas ou aumoins l'un des paramettres d'entrés est null */ if (entryValue == null || csvValues == null) { return (entryValue == csvValues); } /** * Traitment du cas ou les valeurs sont, dans une chaine de caractère * et, séparés par des virgules */ if (csvValues instanceof String) { String stringCsvValues = (String) csvValues; String[] csvArray = null; // Traitement des valeurs vides if (entryValue.trim().isEmpty() || stringCsvValues.trim().isEmpty()) { return (entryValue.trim() == stringCsvValues.trim()); } csvArray = stringCsvValues.split(","); for (String cursor : csvArray) { if (equal(cursor.trim(), entryValue.trim())) { return true; } } return false; } /** * Traitment du cas ou les valeurs sont dans une collection */ if (csvValues instanceof Collection) { for (Object entryCsvValue : (Collection) csvValues) { if (equal(entryCsvValue, entryValue)) { return true; } } return false; } /** * Traitment du cas ou les valeurs sont dans une map */ if (csvValues instanceof Map) { for (Object keyCsvValue : ((Map) csvValues).keySet()) { if (equal(((Map) csvValues).get(keyCsvValue), entryValue)) { return true; } } return false; } /** * Traitement des type de données non prise en charge */ return false; } /** * Unwrap prédicat de vérification d'appartenance d'une entrée à une liste * d'element csv * * @param entryValue * @param csvValues * @return */ public static Boolean csvEntry(String entryValue, Object csvValues) { Map<String, Object> paramsMap = new HashMap<String, Object>(); paramsMap.put("entryValue", entryValue); paramsMap.put("csvValues", csvValues); return csvEntry(paramsMap); } /** * Predicate de vérification de l'unicité de valeur d'un property d'un sous * ensemble * * @param paramsMap * @return */ @InvokeParams({ @InvokeParam(name = "collectionEntries", type = "java.util.Collection"), @InvokeParam(name = "entryTypeName", type = "String"), @InvokeParam(name = "entryPropertyName", type = "String")}) public static Boolean singleton(Map<String, Object> paramsMap) { // Logger method trace debug //logger.trace("PredicateImpl.singleton(paramsMap)"); Collection<?> collectionEntries = (Collection<?>) paramsMap.get("collectionEntries"); String entryTypeName = (String) paramsMap.get("entryTypeName"); String entryPropertyName = (String) paramsMap.get("entryPropertyName"); // Valeur de l'property courant Object entryPropertyValue = null; // Valeur du singleton Object singletonValue = null; // Test de nullité des valeurs if (collectionEntries == null || collectionEntries.isEmpty() || entryTypeName == null || ((entryPropertyName == null || entryPropertyName.trim().isEmpty()))) { return true; } // Traitement des occurences de la collection et uniquement ceux du type correpondant à entryType for (Object cursorObject : collectionEntries) { if (CommonToolsHelper.isInstanceOf(cursorObject, entryTypeName)) { // Lecture de valeur de l'property entryPropertyName pour l'objet en cours entryPropertyValue = CommonToolsHelper.getValue(cursorObject, entryPropertyName); // Initialisation de la valeur du singleton à la première valeur singletonValue = (singletonValue == null) ? entryPropertyValue : singletonValue; // Vérification de l'unicité if (!PredicateImpl.equal(singletonValue, entryPropertyValue)) { return false; } } } return true; } /** * Unwrap Predicate de vérification de l'unicité de valeur d'un property * d'un sous ensemble d'une collection identifié par le type de la classe * * @param collectionEntries : collection de données servant de base à la * vérification * @param entryTypeName : Nom du type des elements à prendre en compte dans * la vérification * @param entryPropertyName : nom de l'property d'unicité * @return */ public static Boolean singleton(Collection<?> collectionEntries, String entryTypeName, String entryPropertyName) { Map<String, Object> paramsMap = new HashMap<String, Object>(); paramsMap.put("collectionEntries", collectionEntries); paramsMap.put("entryTypeName", entryTypeName); paramsMap.put("entryPropertyName", entryPropertyName); return singleton(paramsMap); } /** * Predicate de vérification de l'égalité d'une valeur d'un property d'un * sous ensemble avec une valeur fournie en paramettre * * @param paramsMap * @return */ @InvokeParams({ @InvokeParam(name = "collectionEntries", type = "java.util.Collection"), @InvokeParam(name = "entryTypeName", type = "String"), @InvokeParam(name = "entryPropertyName", type = "String"), @InvokeParam(name = "singletonValue", type = "Object")}) public static Boolean singletonValue(Map<String, Object> paramsMap) { // Logger method trace debug //logger.trace("PredicateImpl.singleton(paramsMap)"); Collection<?> collectionEntries = (Collection<?>) paramsMap.get("collectionEntries"); String entryTypeName = (String) paramsMap.get("entryTypeName"); String entryPropertyName = (String) paramsMap.get("entryPropertyName"); Object singletonValue = paramsMap.get("singletonValue"); // Valeur de l'property courant Object entryPropertyValue = null; // Test de nullité des valeurs if (collectionEntries == null || collectionEntries.isEmpty() || entryTypeName == null || ((entryPropertyName == null || entryPropertyName.trim().isEmpty()))) { return true; } // Traitement des occurences de la collection et uniquement ceux du type correpondant à entryType for (Object cursorObject : collectionEntries) { if (CommonToolsHelper.isInstanceOf(cursorObject, entryTypeName)) { // Lecture de valeur de l'property entryPropertyName pour l'objet en cours entryPropertyValue = CommonToolsHelper.getValue(cursorObject, entryPropertyName); // Vérification de l'unicité if (!PredicateImpl.equal(singletonValue, entryPropertyValue)) { return false; } } } return true; } /** * Unwrap Predicate de vérification de l'égalité de valeur d'un property * d'un sous ensemble avec une valeur fournie en paramettre d'une collection * identifié par le type de la classe * * @param collectionEntries : collection de données servant de base à la * vérification * @param entryTypeName : Nom du type des elements à prendre en compte dans * la vérification * @param entryPropertyName : nom de l'property d'unicité * @return */ public static Boolean singletonValue(Collection<?> collectionEntries, String entryTypeName, String entryPropertyName, Object singletonValue) { Map<String, Object> paramsMap = new HashMap<String, Object>(); paramsMap.put("collectionEntries", collectionEntries); paramsMap.put("entryTypeName", entryTypeName); paramsMap.put("entryPropertyName", entryPropertyName); paramsMap.put("singletonValue", singletonValue); return singletonValue(paramsMap); } /** * Predicate de vérification de l'existence d'une seule occurence d'une * valeur particulière parmis les properties des objects particuliers d'une * collection * * @param paramsMap * @return */ @InvokeParams({ @InvokeParam(name = "collectionEntries", type = "java.util.Collection"), @InvokeParam(name = "entryTypeName", type = "String"), @InvokeParam(name = "entryPropertyName", type = "String"), @InvokeParam(name = "occurenceValue", type = "Object")}) public static Boolean singleOccurenceValue(Map<String, Object> paramsMap) { /** * Logger method trace debug */ //logger.trace("PredicateImpl.singleOccurenceValue(paramsMap)"); Collection<?> collectionEntries = (Collection<?>) paramsMap.get("collectionEntries"); String entryTypeName = (String) paramsMap.get("entryTypeName"); String entryPropertyName = (String) paramsMap.get("entryPropertyName"); Object occurenceValue = paramsMap.get("occurenceValue"); /** * Valeur de l'property courant */ Object entryPropertyValue = null; /** * Nombre d'occurence de la valeur envisagée */ int occurenceCount = 0; /** * Test de nullité des valeurs */ if (collectionEntries == null || collectionEntries.isEmpty() || entryTypeName == null || ((entryPropertyName == null || entryPropertyName.trim().isEmpty()))) { return true; } /** * Traitement des occurences de la collection et uniquement ceux du type * correpondant à entryType */ for (Object cursorObject : collectionEntries) { if (CommonToolsHelper.isInstanceOf(cursorObject, entryTypeName)) { /** * Lecture de valeur de l'property entryPropertyName pour * l'objet en cours */ entryPropertyValue = CommonToolsHelper.getValue(cursorObject, entryPropertyName); /** * Vérification de l'apparution de l'occurence */ if (PredicateImpl.equal(occurenceValue, entryPropertyValue) && (++occurenceCount > 2)) { return false; } } } /** * Pas plus d'une occurence trouvée */ return true; } /** * Unwrap Predicate de vérification de l'existence d'une seule occurence * d'une valeur particulière parmis les properties des objects particuliers * d'une collection * * @param collectionEntries : collection de données servant de base à la * vérification * @param entryTypeName : Nom du type des elements à prendre en compte dans * la vérification * @param entryPropertyName : nom de l'property d'unicité * @param occurenceValue : occurence à verifier le nombre d'appuration * @return */ public static Boolean singleOccurenceValue(Collection<?> collectionEntries, String entryTypeName, String entryPropertyName, Object occurenceValue) { Map<String, Object> paramsMap = new HashMap<String, Object>(); paramsMap.put("collectionEntries", collectionEntries); paramsMap.put("entryTypeName", entryTypeName); paramsMap.put("entryPropertyName", entryPropertyName); paramsMap.put("occurenceValue", occurenceValue); return singleOccurenceValue(paramsMap); } /** * Predicate de vérification de l'existence d'une seule occurence d'une * valeur particulière sur un sous ensemble groupé d'un type précis des * eléments d'une collection * * @param paramsMap * @return */ @InvokeParams({ @InvokeParam(name = "collectionEntries", type = "java.util.Collection"), @InvokeParam(name = "entryTypeName", type = "String"), @InvokeParam(name = "entryPropertyName", type = "String"), @InvokeParam(name = "csvGroupPropertiesNames", type = "String"), @InvokeParam(name = "occurenceEntity", type = "Object"), @InvokeParam(name = "occurenceValue", type = "Object")}) public static Boolean singleOccurenceValueByGroup(Map<String, Object> paramsMap) { /** * Logger method trace debug */ //logger.trace("PredicateImpl.singleOccurenceValueByGroup(paramsMap)"); Collection<?> collectionEntries = (Collection<?>) paramsMap.get("collectionEntries"); String entryTypeName = (String) paramsMap.get("entryTypeName"); String entryPropertyName = (String) paramsMap.get("entryPropertyName"); String csvGroupPropertiesNames = (String) paramsMap.get("csvGroupPropertiesNames"); Object occurenceEntity = paramsMap.get("occurenceEntity"); Object occurenceValue = paramsMap.get("occurenceValue"); /** * Valeur de l'property courant */ Object entryPropertyValue = null; /** * Déclaration et initialisation du compteur des occurences rencontrées */ int occurenceCount = 0; /** * Test de nullité des valeurs */ if (collectionEntries == null || collectionEntries.isEmpty() || entryTypeName == null || ((entryPropertyName == null || entryPropertyName.trim().isEmpty())) || (csvGroupPropertiesNames == null || csvGroupPropertiesNames.trim().isEmpty()) || occurenceEntity == null || occurenceValue == null) { return true; } /** * Traitement des occurences de la collection et uniquement ceux du type * correpondant à entryType et appartenant au group d'unicité */ for (Object cursorObject : collectionEntries) { if (CommonToolsHelper.isInstanceOf(cursorObject, entryTypeName) && equalGroup(cursorObject, occurenceEntity, csvGroupPropertiesNames)) { /** * Lecture de valeur de la property entryPropertyName pour * l'objet en cours */ entryPropertyValue = CommonToolsHelper.getValue(cursorObject, entryPropertyName); /** * Vérification de l'apparution de l'occurence */ if (PredicateImpl.equal(occurenceValue, entryPropertyValue) && (++occurenceCount > 1)) { return false; } } } /** * Pas plus d'une occurence trouvée */ return true; } /** * Unwrap Predicate de vérification de l'existence d'une seule occurence * d'une valeur particulière parmis les properties des objects particuliers * d'une collection * * @param collectionEntries : collection de données servant de base à la * vérification * @param entryTypeName : Nom du type des elements à prendre en compte dans * la vérification * @param entryPropertyName : nom de l'property d'unicité * @param csvGroupPropertiesNames : properties de groupements sur lequel * l'occurence doit être unique * @param occurenceEntity : entité de l'occurence à vérifier * @param occurenceValue : occurence à verifier le nombre d'appuration * @return */ public static Boolean singleOccurenceValueByGroup(Collection<?> collectionEntries, String entryTypeName, String entryPropertyName, String csvGroupPropertiesNames, Object occurenceEntity, Object occurenceValue) { Map<String, Object> paramsMap = new HashMap<String, Object>(); paramsMap.put("collectionEntries", collectionEntries); paramsMap.put("entryTypeName", entryTypeName); paramsMap.put("entryPropertyName", entryPropertyName); paramsMap.put("csvGroupPropertiesNames", csvGroupPropertiesNames); paramsMap.put("occurenceEntity", occurenceEntity); paramsMap.put("occurenceValue", occurenceValue); return singleOccurenceValueByGroup(paramsMap); } /** * Prédicat de calcul de la somme des entrés d'un property d'un type de * données de la collection * * @param paramsMap * @return */ @InvokeParams({ @InvokeParam(name = "collectionEntries", type = "java.util.Collection"), @InvokeParam(name = "entryTypeName", type = "String"), @InvokeParam(name = "entryPropertyName", type = "String"), @InvokeParam(name = "sumValue", type = "java.math.BigDecimal")}) public static Boolean sum(Map<String, Object> paramsMap) { // Logger method trace debug //logger.trace("PredicateImpl.sum(paramsMap)"); Collection<?> collectionEntries = (Collection<?>) paramsMap.get("collectionEntries"); String entryTypeName = (String) paramsMap.get("entryTypeName"); String entryPropertyName = (String) paramsMap.get("entryPropertyName"); BigDecimal sumValue = new BigDecimal(paramsMap.get("sumValue").toString()); // Reférence de la variable qui cumulera le somme valeur BigDecimal cumulValue = BigDecimal.ZERO; // Valeur de l'property courant Object entryPropertyValue = null; // Test de nullité des paramettres if (collectionEntries == null || collectionEntries.isEmpty() || entryTypeName == null || ((entryPropertyName == null || entryPropertyName.trim().isEmpty())) || sumValue == null || sumValue.longValue() == 0l) { return false; } // Traitement des occurences de la collection et uniquement ceux du type correpondant à entryType for (Object cursorObject : collectionEntries) { if (CommonToolsHelper.isInstanceOf(cursorObject, entryTypeName)) { // Lecture de valeur de l'property entryPropertyName pour l'objet en cours entryPropertyValue = CommonToolsHelper.getValue(cursorObject, entryPropertyName); // Ajout de la valeur courante au cumul cumulValue = cumulValue.add(new BigDecimal(entryPropertyValue.toString())); } } // Comparaison des cumuls return (cumulValue.compareTo(sumValue) == 0) ? true : false; } /** * Unwrap Prédicat de calcul de la somme des entrés d'un property d'un type * de données de la collection * * @param collectionEntries : collection des entrées * @param entryType : type de entrées de la somme * @param entryPropertyName : l'property à sommer * @param sommeValue : Somme à comparer * @return */ public static Boolean sum(Collection<?> collectionEntries, String entryTypeName, String entryPropertyName, BigDecimal sumValue) { Map<String, Object> paramsMap = new HashMap<String, Object>(); paramsMap.put("collectionEntries", collectionEntries); paramsMap.put("entryTypeName", entryTypeName); paramsMap.put("entryPropertyName", entryPropertyName); paramsMap.put("sumValue", sumValue); return sum(paramsMap); } /** * Prédicat de calcul du nombre d'entré de la collection de type entryType * et verification l'équivalence avec la valeur fournie * * @param paramsMap * @return */ @InvokeParams({ @InvokeParam(name = "collectionEntries", type = "java.util.Collection"), @InvokeParam(name = "entryTypeName", type = "String"), @InvokeParam(name = "sizeValue", type = "java.math.BigDecimal")}) public static Boolean size(Map<String, Object> paramsMap) { // Logger method trace debug //logger.trace("PredicateImpl.size(paramsMap)"); Collection<?> collectionEntries = (Collection<?>) paramsMap.get("collectionEntries"); String entryTypeName = (String) paramsMap.get("entryTypeName"); BigDecimal sizeValue = new BigDecimal(paramsMap.get("sizeValue").toString()); // Reférence de la variable qui cumulera le somme valeur BigDecimal cumulsize = BigDecimal.ZERO; // Test de nullité des paramettres if (collectionEntries == null || collectionEntries.isEmpty() || entryTypeName == null || sizeValue == null || sizeValue.longValue() == 0l) { return false; } // Traitement des occurences de la collection et uniquement ceux du type correpondant à entryType for (Object cursorObject : collectionEntries) { if (CommonToolsHelper.isInstanceOf(cursorObject, entryTypeName)) // Cumul du nombre total d'entrée correspondate { cumulsize = cumulsize.add(BigDecimal.ONE); } } // Comparaison des cumuls return (cumulsize.compareTo(sizeValue) == 0) ? true : false; } /** * Prédicat de calcul du nombre d'entré de la collection de type entryType * et verification l'équivalence avec la valeur fournie * * @param collectionEntries * @param entryType * @param sizeValue * @return */ public static Boolean size(Collection<?> collectionEntries, String entryTypeName, BigDecimal sizeValue) { Map<String, Object> paramsMap = new HashMap<String, Object>(); paramsMap.put("collectionEntries", collectionEntries); paramsMap.put("entryTypeName", entryTypeName); paramsMap.put("sizeValue", sizeValue); return size(paramsMap); } /** * Prédicat de vérifiation de la supérirorité d'une valeur sur une autre * * @param paramsMap * @return */ @InvokeParams({ @InvokeParam(name = "greaterValue", type = "Object"), @InvokeParam(name = "greaterLimit", type = "Object")}) public static Boolean greater(Map<String, Object> paramsMap) { // Logger method trace debug //logger.trace("PredicateImpl.greater(paramsMap)"); Object greaterValue = (Object) paramsMap.get("greaterValue"); Object greaterLimit = (Object) paramsMap.get("greaterLimit"); // Variable temporaire de stockage Object tmpGreaterValue = greaterValue; Object tmpGreaterLimit = greaterLimit; // Test de nulité des paramettres if (greaterValue == null || greaterLimit == null) { return false; } //Transformation des numériques stockés en chaine de caractère en BigDecimal tmpGreaterValue = CommonToolsHelper.convertIfStringToBigDecimal(greaterValue); tmpGreaterLimit = CommonToolsHelper.convertIfStringToBigDecimal(greaterLimit); // Traitement des nombres if (tmpGreaterValue instanceof BigDecimal && tmpGreaterLimit instanceof BigDecimal && ((BigDecimal) tmpGreaterValue).compareTo((BigDecimal) tmpGreaterLimit) == 1) { return true; } // Test des incohérences hiérachiques if (!tmpGreaterValue.getClass().isInstance(tmpGreaterLimit) && !tmpGreaterLimit.getClass().isInstance(tmpGreaterValue)) { return false; } // Test de comparabilité par l'implémentation de l'interface comparable if ((tmpGreaterValue instanceof Comparable) && ((Comparable) tmpGreaterValue).compareTo(tmpGreaterLimit) == 1) { return true; } // Test de comparabilité par l'implémentation de l'interface comparable if ((tmpGreaterLimit instanceof Comparable) && ((Comparable) tmpGreaterLimit).compareTo(tmpGreaterValue) == -1) { return true; } // Valeur par défaut return false; } /** * Prédicat de vérifiation de la supérirorité d'une valeur sur une autre * * @param greaterValue * @param greaterLimit * @return */ public static Boolean greater(Object greaterValue, Object greaterLimit) { Map<String, Object> paramsMap = new HashMap<String, Object>(); paramsMap.put("greaterValue", greaterValue); paramsMap.put("greaterLimit", greaterLimit); return greater(paramsMap); } /** * Prédicat de vérifiation de l'infériorité d'une valeur sur une autre * * @param paramsMap * @return */ @InvokeParams({ @InvokeParam(name = "lowerValue", type = "Object"), @InvokeParam(name = "lowerLimit", type = "Object")}) public static Boolean lower(Map<String, Object> paramsMap) { // Logger method trace debug //logger.trace("PredicateImpl.lower(paramsMap)"); Object lowerValue = (Object) paramsMap.get("lowerValue"); Object lowerLimit = (Object) paramsMap.get("lowerLimit"); // Variable temporaire de stockage Object tmpLowerValue = lowerValue; Object tmpLowerLimit = lowerLimit; // Test de nulité des paramettres if (lowerValue == null || lowerLimit == null) { return false; } //Transformation des numériques stockés en chaine de caractère en BigDecimal tmpLowerValue = CommonToolsHelper.convertIfStringToBigDecimal(lowerValue); tmpLowerLimit = CommonToolsHelper.convertIfStringToBigDecimal(lowerLimit); // Traitement des nombres if (tmpLowerValue instanceof BigDecimal && tmpLowerLimit instanceof BigDecimal && ((BigDecimal) tmpLowerValue).compareTo((BigDecimal) tmpLowerLimit) == -1) { return true; } // Test des incohérences hiérachiques if (!tmpLowerValue.getClass().isInstance(tmpLowerLimit) && !tmpLowerLimit.getClass().isInstance(tmpLowerValue)) { return false; } // Test de comparabilité par l'implémentation de l'interface comparable if ((tmpLowerValue instanceof Comparable) && ((Comparable) tmpLowerValue).compareTo(tmpLowerLimit) == -1) { return true; } // Test de comparabilité par l'implémentation de l'interface comparable if ((tmpLowerLimit instanceof Comparable) && ((Comparable) tmpLowerLimit).compareTo(tmpLowerValue) == 1) { return true; } // Valeur par défaut return false; } /** * Unwrap Prédicat de vérifiation de l'infériorité d'une valeur sur une * autre * * @param lowerValue * @param lowerLimit * @return */ public static Boolean lower(Object lowerValue, Object lowerLimit) { Map<String, Object> paramsMap = new HashMap<String, Object>(); paramsMap.put("lowerValue", lowerValue); paramsMap.put("lowerLimit", lowerLimit); return lower(paramsMap); } /** * Prédicat de vérification de la cohérence du Rib, vérifié la longueur du * RIB, * * @param paramsMap * @return */ @InvokeParams({ @InvokeParam(name = "ribValue", type = "String")}) public static Boolean ribChecker(Map<String, Object> paramsMap) { // Logger method trace debug //logger.trace("PredicateImpl.ribChecker(paramsMap)"); String ribValue = (String) paramsMap.get("ribValue"); // Variables locales BigDecimal accountNumber = null; BigDecimal keyNumber = null; BigDecimal moduloValue = new BigDecimal(0); BigDecimal bigDecimal97 = new BigDecimal(97); BigDecimal bigDecimal100 = new BigDecimal(100); // Test de nullité des parametres if (ribValue == null || ribValue.trim().isEmpty()) { return false; } // Test de longueur des caractères if (ribValue.trim().length() != 23) { return false; } // Test de présence exclusive des chiffres dans le code RIB try { accountNumber = new BigDecimal(ribValue.trim().substring(0, 21)); keyNumber = new BigDecimal(ribValue.trim().substring(21, 23)); } catch (NumberFormatException e) { e.printStackTrace(); return false; } /* * Test du modulo 97 */ //Calcul du modulo moduloValue = accountNumber; moduloValue = moduloValue.multiply(bigDecimal100); moduloValue = moduloValue.remainder(bigDecimal97); moduloValue = bigDecimal97.subtract(moduloValue); // Test du modulo if (!moduloValue.equals(keyNumber)) { return false; } // En cas de succès de l'ensemble des vérifications return true; } /** * Unwrap Prédicat de vérification de la cohérence du Rib, vérifié la * longueur du RIB, la présence exclusive des nombres dans la chaine et le * calcul du modulo * * @param ribValue * @return */ public static Boolean ribChecker(String ribValue) { Map<String, Object> paramsMap = new HashMap<String, Object>(); paramsMap.put("ribValue", ribValue); return ribChecker(paramsMap); } /** * Prédicat de vérification s'il s'agit d'un message sygma MT103-001 * * @param paramsMap * @return */ @InvokeParams({ @InvokeParam(name = "codeTypeMessage", type = "String"), @InvokeParam(name = "codeTypeTransaction", type = "String") }) public static Boolean ifMt103001Message(Map<String, Object> paramsMap) { //Variables boolean bool = false; //Logger method trace debug //logger.trace("PredicateImpl.ifMt103001Message(paramsMap)"); // Lecture des paramettres d'entrée String codeTypeMessage = (String) paramsMap.get("codeTypeMessage"); String codeTypeTransaction = (String) paramsMap.get("codeTypeTransaction"); //Si null if (codeTypeMessage == null || codeTypeTransaction == null) { bool = false; } else { //Si correct if (codeTypeMessage.equalsIgnoreCase("103") && codeTypeTransaction.equalsIgnoreCase("001")) { bool = true; } else { bool = false; } } return bool; } /** * Prédicat de s'il s'agit d'un administrateur * * @param paramsMap * @return */ @InvokeParams({ @InvokeParam(name = "loginValue", type = "String"), @InvokeParam(name = "passwordValue", type = "String") }) public static Boolean ifAdmin(Map<String, Object> paramsMap) { //Variables boolean bool = false; // Lecture des paramettres d'entrée String loginValue = (String) paramsMap.get("loginValue"); String passwordValue = (String) paramsMap.get("passwordValue"); //Si null if (loginValue == null || passwordValue == null) { bool = false; } else { //Si correct if (loginValue.equalsIgnoreCase("admin") && passwordValue.equalsIgnoreCase("admin")) { bool = true; } else { bool = false; } } return bool; } /** * ************************************************************** * Utility ************************************************************** */ /** * Vérifie si deux object sont égaux sur un groupe d'property * * @param cursorObject * @param occurenceEntity * @param csvGroupPropertiesNames * @return */ private static boolean equalGroup(Object cursorObject, Object occurenceEntity, String csvGroupPropertiesNames) { /** * Groupe des properties du périmètre d'égalité */ String[] groupPropertiesNamesArray = csvGroupPropertiesNames.split(","); /** * Vérificaition de l'égalité */ for (String groupPropertyName : groupPropertiesNamesArray) { if (!equal(CommonToolsHelper.getValue(occurenceEntity, groupPropertyName), CommonToolsHelper.getValue(cursorObject, groupPropertyName))) { return false; } } return true; } /** * Verificztion de la necessite du controle de l'unicite processus systac * non authorise Les processus suivant ne doivent pas faire l'objet de ce * controle Code_Valeur Code_Enregistrement 10 23 13 23 20 23 23 23 30 23 33 * 23 40 23 43 23 50 23 53 23 */ private static boolean isSinglePresentationAuthorize(String code_valeur, String code_enreg) { //Verifie que le code_valeur n'est pas null if (code_valeur == null || code_valeur.trim().isEmpty()) { return false; } //Cas ou le code enregistrement est null if (code_enreg == null || code_enreg.trim().isEmpty()) { return false; } int code_val = Integer.parseInt(code_valeur.trim()); int code_enregistrement = Integer.parseInt(code_enreg.trim()); //Traitement switch (code_val) { case 10: if (code_enregistrement == 23) { return true; } break; case 13: if (code_enregistrement == 23) { return true; } break; case 20: if (code_enregistrement == 23) { return true; } break; case 23: if (code_enregistrement == 23) { return true; } break; case 30: if (code_enregistrement == 23) { return true; } break; case 33: if (code_enregistrement == 23) { return true; } break; case 40: if (code_enregistrement == 23) { return true; } break; case 43: if (code_enregistrement == 23) { return true; } break; case 50: if (code_enregistrement == 23) { return true; } break; case 53: if (code_enregistrement == 23) { return true; } break; } return false; } } typefichier-validator/src/main/java/com/megatim/typefichier/validator/predicat/TypeFichierValidatorEngine.java
New file @@ -0,0 +1,385 @@ /* * 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.typefichier.validator.predicat; import com.megatim.dynamicjsonparser.pojo.ValidationResult; import com.megatim.typefichier.validator.model.ConfigStreamValidator; import com.megatim.typefichier.validator.model.ValidatorDescriptor; import com.megatim.typefichier.validator.model.ExcelFileLine; import com.megatim.typefichier.validator.model.FileLine; import com.megatim.typefichier.validator.model.GenericTypeFichier; import com.megatim.typefichier.validator.utilities.Constantes; import com.megatim.typefichier.validator.utilities.ParserUtils; import com.megatim.typefichier.validator.utilities.Utilities; import static com.megatim.typefichier.validator.utilities.Utilities.getCharset; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.StandardOpenOption; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.logging.Level; import java.util.logging.Logger; import org.apache.commons.csv.CSVFormat; import org.apache.commons.csv.CSVParser; import org.apache.commons.csv.CSVRecord; import org.apache.commons.text.StringEscapeUtils; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.xssf.usermodel.XSSFWorkbook; /** * * @author mela */ public class TypeFichierValidatorEngine { private static TypeFichierValidatorEngine typeFichierEngine; private static final int TRESHOLD = 100_000; public static TypeFichierValidatorEngine getInstance() { if (typeFichierEngine == null) { typeFichierEngine = new TypeFichierValidatorEngine(); } return typeFichierEngine; } //valide un type de fichier et indique si la validation a été un succès ou un échec public boolean validateTypeFichier(final ConfigStreamValidator config, File errorFile, int nbThreads) { boolean valid = true; try { if (config.getFileToValidate() != null && config.getFileToValidate().isFile()) { ValidatorDescriptor desc = Utilities.validatorDescriptor(config.getValidator()); ValidationResult vr = null; if (desc.getExtension() == null) { if (desc.getLineDelimiter() != null && desc.getColumnDelimiter() != null) { vr = validateCsvFileLines(config, errorFile, desc, nbThreads); } else { vr = validateTxtFileLines(config, errorFile, nbThreads); } } else { switch (desc.getExtension()) { case CSV: vr = validateCsvFileLines(config, errorFile, desc, nbThreads); break; case TXT: vr = validateTxtFileLines(config, errorFile, nbThreads); break; case XLS: vr = parseXlsFile(config, errorFile, desc, nbThreads); break; case XLSX: vr = parseXlsxFile(config, errorFile, desc, nbThreads); break; default: throw new UnsupportedOperationException("Cette valeur de l'extension nous est inconnu"); } } //On valide le nom du fichier valid = validateFileName(config, errorFile, vr.getNbLines()) && vr.isValid(); } else { valid = false; //La validation du fichier a échouéa } } catch (Exception ex) { valid = false; Logger.getLogger(TypeFichierValidatorEngine.class.getName()).log(Level.SEVERE, ex.getMessage(), ex); } return valid; } //valide un type de fichier et indique si la validation a été un succès ou un échec (utilisé par fdx-server public boolean validateTypeFichier(final ConfigStreamValidator config, int nbThreads) { int numero = 0; try { if (config.getFileToValidate() != null && config.getFileToValidate().isFile()) { Charset charset = getCharset(config.getFileToValidate()); //On valide les lignes du fichier try ( FileInputStream fis = new FileInputStream(config.getFileToValidate()); InputStreamReader isr = new InputStreamReader(fis, charset); BufferedReader reader = new BufferedReader(isr)) { String line; List<FileLine> fileLines = new ArrayList<>(TRESHOLD); while ((line = reader.readLine()) != null) { FileLine fileLine = new FileLine(line, line.length(), ++numero, config.getFileToValidate().getName()); fileLines.add(fileLine); if (numero % TRESHOLD == 0) { //Si la validation a des erreurs, on écrit ces erreurs dans le fichier d'erreur boolean valid = validateFileLines(config, fileLines, nbThreads); if (!valid) { return false; } fileLines.clear(); } } return validateFileLines(config, fileLines, nbThreads); } } //GenericTypeFichier représente la structure que le validateur exploite pour la validation du nom du fichier GenericTypeFichier typeFichier = new GenericTypeFichier(config.getFileToValidate(), numero); //On valide la nomenclature du fichier PredicatResult<GenericTypeFichier> predicatResult = CalculPredicat.validateElement(config.getPredicate(), config.getValidator(), typeFichier, 1); //Si la validation a des erreurs, on écrit ces erreurs dans le fichier d'erreur if (!predicatResult.getErrors().isEmpty()) { return false; } } catch (Exception ex) { Logger.getLogger(TypeFichierValidatorEngine.class.getName()).log(Level.SEVERE, ex.getMessage(), ex); } return false; } private boolean writeErrorsIfAny(final ConfigStreamValidator config, List<FileLine> fileLines, int nbThreads, File errorFile, boolean valid) throws Exception, IOException { PredicatResult<FileLine> predicatResults; //Validation de toutes les lignes du fichier predicatResults = CalculPredicat.validateElements(config.getPredicate(), config.getValidator(), fileLines, nbThreads); List<FileLine> errors = predicatResults.getErrors(); if (errors != null && !errors.isEmpty()) { valid = false; if (!errorFile.exists()) { errorFile.createNewFile(); } //Si la validation a des erreurs, on écrit ces erreurs dans le fichier d'erreur try ( FileWriter ffw = new FileWriter(errorFile)) { //On écrit l'erreur de nomenclature dans le fichier for (FileLine e : errors) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder = stringBuilder.append(e.getCodeErreur()).append(" : ligne ").append(e.getNumero()).append(" ;\n"); if (stringBuilder.length() > 0) { ffw.write(stringBuilder.toString()); } } } } return valid; } private boolean writeCsvErrorsIfAny(final ConfigStreamValidator config, List<ExcelFileLine> fileLines, int nbThreads, File errorFile, boolean valid) throws Exception, IOException { PredicatResult<ExcelFileLine> predicatResults; //Validation de toutes les lignes du fichier predicatResults = CalculPredicat.validateElements(config.getPredicate(), config.getValidator(), fileLines, nbThreads); List<ExcelFileLine> errors = predicatResults.getErrors(); if (errors != null && !errors.isEmpty()) { valid = false; //Si la validation a des erreurs, on écrit ces erreurs dans le fichier d'erreur try ( BufferedWriter bufferWriter = Files.newBufferedWriter(errorFile.toPath(), StandardCharsets.UTF_8, StandardOpenOption.APPEND, StandardOpenOption.CREATE);) { //On écrit l'erreur de nomenclature dans le fichier for (ExcelFileLine e : errors) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder = stringBuilder.append(e.getCodeErreur()).append(" : ligne ").append(e.getLineNumber()).append(" ;\n"); if (stringBuilder.length() > 0) { bufferWriter.write(stringBuilder.toString()); } } } } return valid; } private boolean validateFileLines(final ConfigStreamValidator config, List<FileLine> fileLines, int nbThreads) throws Exception, IOException { PredicatResult<FileLine> predicatResults = CalculPredicat.validateElements(config.getPredicate(), config.getValidator(), fileLines, nbThreads); List<FileLine> errors = predicatResults.getErrors(); return errors != null && errors.isEmpty(); } private boolean validateFileName(final ConfigStreamValidator config, File errorFile, int nbLines) throws IOException, Exception { //GenericTypeFichier représente la structure que le validateur exploite pour la validation des colonnes de fichier GenericTypeFichier typeFichier = new GenericTypeFichier(config.getFileToValidate(), nbLines); PredicatResult<GenericTypeFichier> predicatResult = CalculPredicat.validateElement(config.getPredicate(), config.getValidator(), typeFichier, 1); //Si la validation a des erreurs, on écrit ces erreurs dans le fichier d'erreur if (!predicatResult.getErrors().isEmpty()) { List<GenericTypeFichier> errors = predicatResult.getErrors(); errorFile.createNewFile(); try ( BufferedWriter bufferWriter = Files.newBufferedWriter(errorFile.toPath(), StandardCharsets.UTF_8, StandardOpenOption.APPEND, StandardOpenOption.CREATE);) { if (errors != null && !errors.isEmpty()) { for (GenericTypeFichier e : errors) { //On écrit l'erreur de nomenclature dans le fichier StringBuilder stringBuilder = new StringBuilder(); stringBuilder = stringBuilder.append(e.getCodeErreur()).append(";").append("\n"); if (stringBuilder.length() > 0) { bufferWriter.write(stringBuilder.toString()); } } } return false; //La validation du fichier a échouée } } return true; } private ValidationResult validateCsvFileLines(ConfigStreamValidator config, File errorFile, ValidatorDescriptor desc, int nbThreads) throws IOException, Exception { Charset charset = getCharset(config.getFileToValidate()); AtomicBoolean withHeader = new AtomicBoolean(desc.isHeaderPresent()); AtomicInteger numeroLigne = withHeader.get() ? new AtomicInteger(1) : new AtomicInteger(0); List<ExcelFileLine> fileLines = new ArrayList<>(); int count = 1; boolean valid = true; try ( FileInputStream fis = new FileInputStream(config.getFileToValidate()); InputStreamReader isr = new InputStreamReader(fis, charset); BufferedReader reader = new BufferedReader(isr)) { CSVParser parser = new CSVParser(reader, CSVFormat.DEFAULT.builder() .setSkipHeaderRecord(false) .setIgnoreSurroundingSpaces(true) .setTrim(true) .setDelimiter(StringEscapeUtils.unescapeJava(desc.getColumnDelimiter())) .setRecordSeparator(StringEscapeUtils.unescapeJava(desc.getLineDelimiter())) .build()); for (CSVRecord record : parser) { if (!withHeader.get()) { Map<Integer, String> columns = new HashMap<>(); AtomicInteger position = new AtomicInteger(0); record.forEach(column -> columns.put(position.incrementAndGet(), column)); fileLines.add(new ExcelFileLine(columns, numeroLigne.incrementAndGet(), position.get())); if (count % TRESHOLD == 0) { boolean test = writeCsvErrorsIfAny(config, fileLines, nbThreads, errorFile, valid); valid = valid & test; fileLines.clear(); } } else { withHeader.set(false); } count++; } if (!fileLines.isEmpty()) { boolean test = writeCsvErrorsIfAny(config, fileLines, nbThreads, errorFile, valid); valid = valid & test; fileLines.clear(); } } return new ValidationResult(numeroLigne.get(), valid); } private ValidationResult validateTxtFileLines(final ConfigStreamValidator config, File errorFile, int nbThreads) throws FileNotFoundException, IOException, Exception { boolean valid = true; int numero = 0; try ( FileInputStream fis = new FileInputStream(config.getFileToValidate()); InputStreamReader isr = new InputStreamReader(fis, getCharset(config.getFileToValidate())); BufferedReader reader = new BufferedReader(isr)) { String line; List<FileLine> fileLines = new ArrayList<>(TRESHOLD); while ((line = reader.readLine()) != null) { FileLine fileLine = new FileLine(line, line.length(), ++numero, config.getFileToValidate().getName()); fileLines.add(fileLine); if (numero % TRESHOLD == 0) { //Si la validation a des erreurs, on écrit ces erreurs dans le fichier d'erreur boolean test = writeErrorsIfAny(config, fileLines, nbThreads, errorFile, valid); valid = valid & test; fileLines.clear(); } } boolean test = writeErrorsIfAny(config, fileLines, nbThreads, errorFile, valid); valid = valid & test; } return new ValidationResult(numero, valid); } private ValidationResult parseXlsxFile(ConfigStreamValidator config, File errorFile, ValidatorDescriptor desc, int nbThreads) throws Exception { try ( InputStream is = new FileInputStream(config.getFileToValidate()); Workbook wb = new XSSFWorkbook(is)) { return parseExcelFile(config, errorFile, desc, wb, nbThreads); } } private ValidationResult parseXlsFile(ConfigStreamValidator config, File errorFile, ValidatorDescriptor desc, int nbThreads) throws Exception { try ( InputStream is = new FileInputStream(config.getFileToValidate()); Workbook wb = new HSSFWorkbook(is)) { return parseExcelFile(config, errorFile, desc, wb, nbThreads); } } private ValidationResult parseExcelFile(ConfigStreamValidator config, File errorFile, ValidatorDescriptor desc, Workbook wb, int nbThreads) throws IOException, Exception { Map<Integer, Map> mapParams = ParserUtils.getValidateurElements(config.getValidator()); List<ExcelFileLine> fileLines = new ArrayList<>(); AtomicBoolean withHeader = new AtomicBoolean(desc.isHeaderPresent()); AtomicInteger numeroLigne = withHeader.get() ? new AtomicInteger(1) : new AtomicInteger(0); int count = 1; boolean valid = true; for (int i = 0; i < wb.getNumberOfSheets(); i++) { Sheet sheet = wb.getSheetAt(i); final Integer numberOfColumns = Collections.max(mapParams.keySet()); for (org.apache.poi.ss.usermodel.Row r : sheet) { if (!withHeader.get()) { //Représente les colonnes extraites de chaque ligne du fichier Map<Integer, String> columns = new HashMap<>(); AtomicInteger index = new AtomicInteger(0); for (int cn = 0; cn < r.getLastCellNum(); cn++) { if (cn < numberOfColumns) { Map<String, String> map = mapParams.get(index.get() + 1); //Prendre aussi les cellules vides en considération org.apache.poi.ss.usermodel.Cell c = r.getCell(cn, org.apache.poi.ss.usermodel.Row.MissingCellPolicy.CREATE_NULL_AS_BLANK); String value = ParserUtils.getXlxsCellValue(c, wb, map.get(Constantes.LIBELLE_TYPE_DONNEE), map.get(Constantes.LIBELLE_FORMAT_DATE), map.get(Constantes.LIBELLE_SEPARATEUR_DATE), map.get(Constantes.ERROR_CODE)); columns.put(index.incrementAndGet(), value); fileLines.add(new ExcelFileLine(columns, numeroLigne.incrementAndGet(), r.getLastCellNum() + 1)); if (count % TRESHOLD == 0) { boolean test = writeCsvErrorsIfAny(config, fileLines, nbThreads, errorFile, valid); valid = valid & test; fileLines.clear(); } } else { break; } } } else { withHeader.set(false); } } if (!fileLines.isEmpty()) { boolean test = writeCsvErrorsIfAny(config, fileLines, nbThreads, errorFile, valid); valid = valid & test; fileLines.clear(); } } return new ValidationResult(numeroLigne.get(), valid); } } typefichier-validator/src/main/java/com/megatim/typefichier/validator/utilities/Constantes.java
New file @@ -0,0 +1,33 @@ /* * 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.typefichier.validator.utilities; /** * * @author ASUS */ public class Constantes { public final static String LIBELLE_POSITION = "position"; public final static String LIBELLE_TAILLE = "taille"; public final static String LIBELLE_SEPARATEUR_DATE = "separateurDate"; public final static String LIBELLE_INDEX = "index"; public final static String LIBELLE_TYPE_DONNEE = "typeDonnee"; public final static String LIBELLE_TAILLE_PARTIE_DECIMALE = "taillePartieDecimale"; public final static String LIBELLE_SEPARATEUR_DECIMAL = "separateurDecimal"; public final static String LIBELLE_LIGNE = "ligne"; public final static String LIBELLE_FORMAT_DATE = "formatDate"; public final static String LIBELLE_DECIMAL = "DECIMAL"; public final static String LIBELLE_DATE = "DATE"; public final static String LIBELLE_NUMERIQUE = "NUMERIQUE"; public final static String LIBELLE_ALPHANUMERIQUE = "ALPHANUMERIQUE"; public static final String ERROR_CODE = "error-code"; public static final String FIELD_NAME = "field-name"; public static final String EQUAL_PARAM = "equalParam"; public static final String HEADER_PRESENT = "header-present"; public static final String LINE_DELIMITER = "line-delimiter"; public static final String COLUMN_DELIMITER = "column-delimiter"; public final static String EXTENSION = "extension"; } typefichier-validator/src/main/java/com/megatim/typefichier/validator/utilities/ParserUtils.java
New file @@ -0,0 +1,420 @@ /* * 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.typefichier.validator.utilities; import com.megatim.typefichier.validator.model.enums.TypeDonnee; 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 <entity> dans le validateur XML private static final int ENTITY_LIST_SIZE = 2; private ParserUtils() { } public static Map<Integer, Map> getValidateurElements(File file) throws Exception { byte[] bytes = Files.readAllBytes(file.toPath()); return getValidateurElements(bytes); } public static Map<Integer, Map> getValidateurElements(byte[] bytes) throws Exception { Document doc = intialize(bytes); NodeList entityList = doc.getElementsByTagName("entity"); //Liste des noeud <entity> //Map qui stocke le champ à une position, ainsi que les caractéristiques de champ(typeDonnee, taille, index de debut d'extraction) Map<Integer, Map> mapParams = new HashMap<>(); int position = 0; if (entityList.getLength() == ENTITY_LIST_SIZE) { //Liste des noeud de type <validation> du deuximème Noeud <entity> NodeList entityFileLineChildren = entityList.item(1).getChildNodes(); //parcours de la balise <entity> 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 <validation> Node validation = entityFileLineChildren.item(i); if (validation != null) { position++; //Liste des assertions de la balise <validation> NodeList assertions = validation.getChildNodes(); for (int r = 0; r < assertions.getLength(); r++) { Node assertion = assertions.item(r); Map<String, String> mapAttributes = new HashMap<>(); if (assertion != null && assertion.getAttributes() != null) { //Les attributs de la balise <assertion> 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 <param-value> de la balise <assertion> 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 <param-value> 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.LIBELLE_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, String separateurDate, String columnName) { if (cell != null) { String formatString = cell.getCellStyle().getDataFormatString(); System.out.println("----------typeDonnee = " + typeDonnee); switch (cell.getCellTypeEnum()) { case STRING: if (typeDonnee.equalsIgnoreCase(TypeDonnee.DATE.getValue())) { Date date = DateUtil.getJavaDate(Double.parseDouble(cell.getStringCellValue())); return formatDate(date, formatDate, separateurDate, columnName); } 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, separateurDate, columnName); } else if (DateUtil.isCellDateFormatted(cell)) { return convertToDate(cell, formatDate, separateurDate, columnName); } 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, String separateurDate, String columnName) { Date date = cell.getDateCellValue(); return formatDate(date, formatDate, separateurDate, columnName); } private static String formatDate(Date date, String formatDate, String separateurDate, String columnName) { SimpleDateFormat sdf = new SimpleDateFormat(formatDate != null && !formatDate.isEmpty() && separateurDate != null ? Utilities.addSeparateurToDateFormat(formatDate, separateurDate, columnName) : "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()); } } } typefichier-validator/src/main/java/com/megatim/typefichier/validator/utilities/TypeFichierJsonConverter.java
New file @@ -0,0 +1,83 @@ /* * 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.typefichier.validator.utilities; import com.megatim.dynamicjsonparser.enums.TypeDonnee; import static com.megatim.dynamicjsonparser.enums.TypeDonnee.ALPHANUMERIQUE; import static com.megatim.dynamicjsonparser.enums.TypeDonnee.DATE; import static com.megatim.dynamicjsonparser.enums.TypeDonnee.DECIMAL; import static com.megatim.dynamicjsonparser.enums.TypeDonnee.NUMERIQUE; import com.megatim.dynamicjsonparser.pojo.JsonField; import com.megatim.dynamicjsonparser.pojo.JsonStructure; import com.megatim.dynamicjsonparser.pojo.TypeFichierJson; import java.math.BigDecimal; import java.time.LocalDate; import java.util.ArrayList; import java.util.List; /** * * @author ASUS */ public class TypeFichierJsonConverter { private final TypeFichierJson typeFichierJson; public TypeFichierJsonConverter(TypeFichierJson typeFichierJson) { this.typeFichierJson = typeFichierJson; } public List<JsonField> convert() { return convert(typeFichierJson.getJsonStructure().getFields()); } private List<JsonField> convert(List<JsonStructure> jsonStructs) { List<JsonField> fields = new ArrayList<>(); jsonStructs.forEach(j -> { if (j.getTypeDonnee() != null) { if (j.getTypeDonnee().equals(TypeDonnee.OBJET)) { if (j.getFields() != null && !j.getFields().isEmpty()) { fields.add(new JsonField(j.getName(), convert(j.getFields()), j.getName(),j.getLengthh(), j.isRequired(), j.isCollection())); } } else { fields.add(convert(j, j.getParent().getName())); } } }); return fields; } private JsonField convert(JsonStructure js, String className) { Class<?> clazz; switch (js.getTypeDonnee()) { case ALPHANUMERIQUE: clazz = String.class; break; case NUMERIQUE: clazz = Long.class; break; case DATE: clazz = LocalDate.class; break; case DECIMAL: clazz = BigDecimal.class; break; default: clazz = String.class; } JsonField dynamicField = new JsonField(clazz, js.getName(), className, js.getLengthh(), js.isRequired(), js.isCollection()); dynamicField.setFormatDate(js.getFormatDate()); dynamicField.setSeparateurDate(js.getCodeDelimiteurDate()); return dynamicField; } } typefichier-validator/src/main/java/com/megatim/typefichier/validator/utilities/TypeFichierJsonUnMarshaller.java
New file @@ -0,0 +1,38 @@ /* * 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.typefichier.validator.utilities; import com.megatim.dynamicjsonparser.pojo.JsonField; import com.megatim.dynamicjsonparser.pojo.JsonStructure; import com.megatim.dynamicjsonparser.pojo.TypeFichierJson; import java.io.File; import java.util.List; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Unmarshaller; /** * * @author ASUS */ public class TypeFichierJsonUnMarshaller { public static List<JsonField> unMarshallOne(String filePath) throws JAXBException { JAXBContext context = JAXBContext.newInstance(TypeFichierJson.class); Unmarshaller unmarshaller = context.createUnmarshaller(); TypeFichierJson typeFichierJson = (TypeFichierJson) unmarshaller.unmarshal(new File(filePath)); setParent(typeFichierJson.getJsonStructure()); return new TypeFichierJsonConverter(typeFichierJson).convert(); } private static void setParent(JsonStructure jsonStruct) { jsonStruct.getFields().forEach(f -> { f.setParent(jsonStruct); setParent(f); }); } } typefichier-validator/src/main/java/com/megatim/typefichier/validator/utilities/Utilities.java
New file @@ -0,0 +1,145 @@ /* * 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.typefichier.validator.utilities; import com.megatim.dynamicjsonparser.pojo.exceptions.ValidatorException; import com.megatim.typefichier.validator.model.ValidatorDescriptor; import com.megatim.typefichier.validator.model.enums.FileExtension; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; /** * * @author ASUS */ public class Utilities { /** * Méthode qui ajoute le séparateur renseigné dans le validateur au format * * @param formatDate * @param separateurDate * @param columnName * @return */ public static String addSeparateurToDateFormat(String formatDate, String separateurDate, String columnName) throws ValidatorException { StringBuilder dateValue = new StringBuilder(); switch (formatDate) { case "ddMMyyyy": dateValue.append("dd").append(separateurDate).append("MM").append(separateurDate).append("yyyy"); break; case "ddyyyyMM": dateValue.append("dd").append(separateurDate).append("yyyy").append(separateurDate).append("MM"); break; case "MMddyyyy": dateValue.append("MM").append(separateurDate).append("dd").append(separateurDate).append("yyyy"); break; case "MMyyyydd": dateValue.append("MM").append(separateurDate).append("yyyy").append(separateurDate).append("dd"); break; case "yyyyddMM": dateValue.append("yyyy").append(separateurDate).append("dd").append(separateurDate).append("MM"); break; case "yyyyMMdd": dateValue.append("yyyy").append(separateurDate).append("MM").append(separateurDate).append("dd"); break; case "yyyy": dateValue.append("yyyy"); break; case "yyyyMM": dateValue.append("yyyy").append(separateurDate).append("MM"); case "MMyyyy": dateValue.append("MM").append(separateurDate).append("yyyy"); break; default: throw new ValidatorException("Le format date " + formatDate + " du champ" + columnName + " n'est pas acceptable "); } return dateValue.toString(); } /** * Méthode qui récupère l'encodage d'un fichier * * @param file : Fichier dont on veut connaître l'encodage * @return : retourne l'encodage le plus probable * @throws FileNotFoundException * @throws IOException */ public static Charset getCharset(File file) throws FileNotFoundException, IOException { return StandardCharsets.UTF_8; } public static ValidatorDescriptor validatorDescriptor(byte[] validator) throws Exception { ValidatorDescriptor desc = new ValidatorDescriptor(); Document doc = intialize(validator); 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) { //Liste des noeud de type <validation> du deuxième Noeud <entity> Node entityNode = entityList.item(1); NamedNodeMap attributes = entityNode.getAttributes(); for (int q = 0; q < attributes.getLength(); q++) { String attributeName = attributes.item(q).getNodeName(); if (attributeName.equalsIgnoreCase(Constantes.EXTENSION)) { desc.setExtension(FileExtension.fromValeur(attributes.item(q).getNodeValue().toUpperCase())); } if (attributeName.equalsIgnoreCase(Constantes.LINE_DELIMITER)) { desc.setLineDelimiter(attributes.item(q).getNodeValue()); } if (attributeName.equalsIgnoreCase(Constantes.HEADER_PRESENT)) { desc.setHeaderPresent(Boolean.parseBoolean(attributes.item(q).getNodeValue())); } if (attributeName.equalsIgnoreCase(Constantes.COLUMN_DELIMITER)) { desc.setColumnDelimiter(attributes.item(q).getNodeValue()); } } } return desc; } /** * Méthode utilitaire pour extraire les données dans un fichier xml * * @param array * @return * @throws Exception */ private static Document intialize(byte[] validator) throws Exception { /** * Défini un factory qui aide à obtenir un parseur qui produit un arbre * d'objets DOM à partir d'un document 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(validator)); doc.getDocumentElement().normalize(); return doc; } } typefichier-validator/target/classes/.netbeans_automatic_build
typefichier-validator/target/maven-archiver/pom.properties
New file @@ -0,0 +1,5 @@ #Generated by Maven #Mon Jun 08 14:55:53 WAT 2026 version=1.0 groupId=com.megatim.typefichier.validator artifactId=typefichier-validator typefichier-validator/target/maven-status/maven-compiler-plugin/compile/default-compile/createdFiles.lst
New file @@ -0,0 +1,34 @@ com\megatim\typefichier\validator\model\FileValidator.class com\megatim\typefichier\validator\model\GenericTypeFichier.class com\megatim\typefichier\validator\utilities\ParserUtils$1.class com\megatim\typefichier\validator\predicat\PredicateImpl.class com\megatim\typefichier\validator\model\enums\FileExtension.class com\megatim\typefichier\validator\utilities\ParserUtils.class com\megatim\dynamicjsonparser\pojo\JsonStructure.class com\megatim\typefichier\validator\predicat\ConstantsPredicat.class com\megatim\dynamicjsonparser\pojo\Indexe.class com\megatim\typefichier\validator\predicat\TypeFichierValidatorEngine$1.class com\megatim\typefichier\validator\predicat\PredicatResult.class com\megatim\dynamicjsonparser\pojo\exceptions\ValidatorException.class com\megatim\typefichier\validator\utilities\TypeFichierJsonConverter$1.class com\megatim\typefichier\validator\model\TypeFichierValidator.class com\megatim\typefichier\validator\utilities\Constantes.class com\megatim\typefichier\validator\utilities\Utilities.class com\megatim\typefichier\validator\predicat\CalculPredicat.class com\megatim\typefichier\validator\Validator.class com\megatim\typefichier\validator\predicat\Data.class com\megatim\typefichier\validator\utilities\TypeFichierJsonUnMarshaller.class com\megatim\typefichier\validator\App.class com\megatim\dynamicjsonparser\pojo\ValidationResult.class com\megatim\typefichier\validator\model\CsvFileLine.class com\megatim\typefichier\validator\model\ValidatorDescriptor.class com\megatim\dynamicjsonparser\pojo\TypeFichierJson.class com\megatim\typefichier\validator\model\ConfigJsonValidator.class com\megatim\typefichier\validator\model\enums\TypeDonnee.class com\megatim\typefichier\validator\model\ConfigStreamValidator.class com\megatim\typefichier\validator\utilities\TypeFichierJsonConverter.class com\megatim\typefichier\validator\predicat\ConnectorImpl.class com\megatim\typefichier\validator\model\ConfigValidator.class com\megatim\typefichier\validator\model\ResultValidation.class com\megatim\typefichier\validator\predicat\TypeFichierValidatorEngine.class com\megatim\typefichier\validator\model\FileLine.class typefichier-validator/target/maven-status/maven-compiler-plugin/compile/default-compile/inputFiles.lst
New file @@ -0,0 +1,31 @@ C:\Users\ASUS\Documents\NetBeansProjects\share_sources\typefichier-validator\src\main\java\com\megatim\typefichier\validator\model\ResultValidation.java C:\Users\ASUS\Documents\NetBeansProjects\share_sources\typefichier-validator\src\main\java\com\megatim\dynamicjsonparser\pojo\ValidationResult.java C:\Users\ASUS\Documents\NetBeansProjects\share_sources\typefichier-validator\src\main\java\com\megatim\dynamicjsonparser\pojo\Indexe.java C:\Users\ASUS\Documents\NetBeansProjects\share_sources\typefichier-validator\src\main\java\com\megatim\typefichier\validator\predicat\PredicateImpl.java C:\Users\ASUS\Documents\NetBeansProjects\share_sources\typefichier-validator\src\main\java\com\megatim\dynamicjsonparser\pojo\TypeFichierJson.java C:\Users\ASUS\Documents\NetBeansProjects\share_sources\typefichier-validator\src\main\java\com\megatim\typefichier\validator\predicat\TypeFichierValidatorEngine.java C:\Users\ASUS\Documents\NetBeansProjects\share_sources\typefichier-validator\src\main\java\com\megatim\typefichier\validator\utilities\ParserUtils.java C:\Users\ASUS\Documents\NetBeansProjects\share_sources\typefichier-validator\src\main\java\com\megatim\typefichier\validator\model\TypeFichierValidator.java C:\Users\ASUS\Documents\NetBeansProjects\share_sources\typefichier-validator\src\main\java\com\megatim\typefichier\validator\predicat\CalculPredicat.java C:\Users\ASUS\Documents\NetBeansProjects\share_sources\typefichier-validator\src\main\java\com\megatim\typefichier\validator\utilities\TypeFichierJsonConverter.java C:\Users\ASUS\Documents\NetBeansProjects\share_sources\typefichier-validator\src\main\java\com\megatim\typefichier\validator\model\enums\FileExtension.java C:\Users\ASUS\Documents\NetBeansProjects\share_sources\typefichier-validator\src\main\java\com\megatim\typefichier\validator\model\enums\TypeDonnee.java C:\Users\ASUS\Documents\NetBeansProjects\share_sources\typefichier-validator\src\main\java\com\megatim\typefichier\validator\utilities\Constantes.java C:\Users\ASUS\Documents\NetBeansProjects\share_sources\typefichier-validator\src\main\java\com\megatim\dynamicjsonparser\pojo\exceptions\ValidatorException.java C:\Users\ASUS\Documents\NetBeansProjects\share_sources\typefichier-validator\src\main\java\com\megatim\dynamicjsonparser\pojo\JsonStructure.java C:\Users\ASUS\Documents\NetBeansProjects\share_sources\typefichier-validator\src\main\java\com\megatim\typefichier\validator\App.java C:\Users\ASUS\Documents\NetBeansProjects\share_sources\typefichier-validator\src\main\java\com\megatim\typefichier\validator\Validator.java C:\Users\ASUS\Documents\NetBeansProjects\share_sources\typefichier-validator\src\main\java\com\megatim\typefichier\validator\utilities\Utilities.java C:\Users\ASUS\Documents\NetBeansProjects\share_sources\typefichier-validator\src\main\java\com\megatim\typefichier\validator\predicat\ConstantsPredicat.java C:\Users\ASUS\Documents\NetBeansProjects\share_sources\typefichier-validator\src\main\java\com\megatim\typefichier\validator\model\GenericTypeFichier.java C:\Users\ASUS\Documents\NetBeansProjects\share_sources\typefichier-validator\src\main\java\com\megatim\typefichier\validator\predicat\Data.java C:\Users\ASUS\Documents\NetBeansProjects\share_sources\typefichier-validator\src\main\java\com\megatim\typefichier\validator\model\ConfigStreamValidator.java C:\Users\ASUS\Documents\NetBeansProjects\share_sources\typefichier-validator\src\main\java\com\megatim\typefichier\validator\utilities\TypeFichierJsonUnMarshaller.java C:\Users\ASUS\Documents\NetBeansProjects\share_sources\typefichier-validator\src\main\java\com\megatim\typefichier\validator\model\CsvFileLine.java C:\Users\ASUS\Documents\NetBeansProjects\share_sources\typefichier-validator\src\main\java\com\megatim\typefichier\validator\predicat\PredicatResult.java C:\Users\ASUS\Documents\NetBeansProjects\share_sources\typefichier-validator\src\main\java\com\megatim\typefichier\validator\model\FileValidator.java C:\Users\ASUS\Documents\NetBeansProjects\share_sources\typefichier-validator\src\main\java\com\megatim\typefichier\validator\model\ConfigJsonValidator.java C:\Users\ASUS\Documents\NetBeansProjects\share_sources\typefichier-validator\src\main\java\com\megatim\typefichier\validator\model\ValidatorDescriptor.java C:\Users\ASUS\Documents\NetBeansProjects\share_sources\typefichier-validator\src\main\java\com\megatim\typefichier\validator\model\ConfigValidator.java C:\Users\ASUS\Documents\NetBeansProjects\share_sources\typefichier-validator\src\main\java\com\megatim\typefichier\validator\model\FileLine.java C:\Users\ASUS\Documents\NetBeansProjects\share_sources\typefichier-validator\src\main\java\com\megatim\typefichier\validator\predicat\ConnectorImpl.java typefichier-validator/target/maven-status/maven-compiler-plugin/testCompile/default-testCompile/inputFiles.lst
typefichier-validator/target/test-classes/.netbeans_automatic_build