package com.megatim.fdxconsultation.tools; import com.megatim.export.excel.Export; import io.github.classgraph.ClassGraph; import io.github.classgraph.ClassInfoList; import io.github.classgraph.ScanResult; import java.io.File; import java.io.FileInputStream; import java.math.BigInteger; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.security.spec.InvalidKeySpecException; import java.util.ArrayList; import java.util.List; import java.util.Properties; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.PBEKeySpec; import java.lang.annotation.Annotation; import com.megatim.fdxconsultation.tools.context.AppCommonContext; import java.text.SimpleDateFormat; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.Arrays; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.core.Context; import javax.ws.rs.core.HttpHeaders; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * * @author ABEGA */ public class CommonTools { /** * Permet de generer des nomre aleatorement * * @return */ public static synchronized String genererChaineAleatoire() { SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss"); String nombre = format.format(new Date()) + String.valueOf((int) (Math.random() * 1000000000)); return nombre; } /** * Permet d'exporter en excel dans repertoire donn� * * @param datas * @param repertoireGeneration * @return */ public static File exporterEnExcel(List datas, File fichier) { try { //On effectue l'export Export.exportExcel(datas, fichier.getAbsolutePath()); } catch (Exception ex) { //On affiche l'erreur ex.printStackTrace(); } return fichier; } /** * Methode permettant de * @param headers * @param request * @return */ public static Map recupererInfosRequete(HttpHeaders headers, @Context HttpServletRequest request) { //Variables Map map = new HashMap(); // Adresse IP du client String clientIp = request.getRemoteAddr(); // En-tête User-Agent String userAgent = headers.getHeaderString("User-Agent"); // Methode String methode = request.getMethod(); // Path String path = request.getRequestURI(); //On ajoute les informations dans la map map.put(AppCommonContext.REQUETE_HTTP_ADRESSE_IP, clientIp); map.put(AppCommonContext.REQUETE_HTTP_CLIENT, userAgent); map.put(AppCommonContext.REQUETE_HTTP_METHODE, methode); map.put(AppCommonContext.REQUETE_HTTP_PATH, path.toLowerCase().replaceAll(AppCommonContext.PATH_BASE_MODULE_CONSULTATION.toLowerCase(), "")); //On retourne la map return map; } /** * Permet d'ajouter des jours à une date donnée * @param date * @param nbreJour * @return */ public static Date addDay(Date date, int nbreJour){ //Varaibles Calendar cal = Calendar.getInstance(); //On ajoute la date cal.setTime(date); //On ajoute la date cal.add(Calendar.DATE, nbreJour); // convert calendar to date Date modifiedDate = cal.getTime(); return modifiedDate; } /** * Permet de formater les chiffres avec un zero devant * @return */ public static String formaterChiffreAvecZeroDevant(long chiffre) { //Si nombre if(chiffre >= 10){ return String.valueOf(chiffre); }else{ return "0"+String.valueOf(chiffre); } } /** * Renvoie les champs de la liste qui n'appartiennent pas à l'entité * * @param classe * @param fieldsToCheck * @return */ public static List checkIfEntityField(Class classe, List fieldsToCheck) { List fieldsNotFound = new ArrayList<>(); Set fieldsSet = Arrays.asList(classe.getDeclaredFields()).stream().map(f ->f.getName()).collect(Collectors.toSet()); fieldsToCheck.stream().forEach(s -> { System.out.println("field to check "+s); if (!fieldsSet.contains(s)) { fieldsNotFound.add(s); } }); return fieldsNotFound; } /** * Permet de hacher le mot de passe * * @param password * @return */ public static String encryptPassword(String password) { try { int iterations = 1000; char[] chars = password.toCharArray(); byte[] salt = getSalt(); PBEKeySpec spec = new PBEKeySpec(chars, salt, iterations, 64 * 8); SecretKeyFactory skf = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1"); byte[] hash = skf.generateSecret(spec).getEncoded(); return iterations + ":" + toHex(salt) + ":" + toHex(hash); } catch (Exception ex) { //On affiche le message d'errreur ex.printStackTrace(); } return null; } /** * Permet de charger des classes qui ont une annotation pr�cise * * @param pkgName * @param annotation * @return */ public static List getAnnotations(final String pkgName, String annotation) { //Variables List> classRefs = new ArrayList<>(); List annotations = new ArrayList<>(); try ( ScanResult scanResult = new ClassGraph().acceptPackages(pkgName).enableAllInfo().scan()) { //On recup�re les classes annot�es ClassInfoList liste = scanResult.getClassesWithAnnotation(annotation); //On charge les classes classRefs = liste.loadClasses(); //On parcourt les classes for (Class classe : classRefs) { //On parcourt les annotations for (Annotation annotationDeclaree : classe.getDeclaredAnnotations()) { //On ajoute l'annotation annotations.add(annotationDeclaree); } } } catch (Exception e) { //On affiche les traces e.printStackTrace(); } return annotations; } /** * Permet de charger des classes qui ont une annotation pr�cise * * @param pkgName * @param annotation * @return */ public static List> getAnnotatedClasses(final String pkgName, String annotation) { //Variables List> classRefs = new ArrayList<>(); try ( ScanResult scanResult = new ClassGraph().acceptPackages(pkgName).enableAllInfo().scan()) { //On recup�re les classes annot�es ClassInfoList liste = scanResult.getClassesWithAnnotation(annotation); //On charge les classes classRefs = liste.loadClasses(); } catch (Exception e) { //On affiche les traces e.printStackTrace(); } return classRefs; } /** * Permet de valider le mot de passe * * @param originalPassword * @param storedPassword * @return * @throws NoSuchAlgorithmException * @throws InvalidKeySpecException */ public static boolean validerMotDePasse(String originalPassword, String storedPassword) throws NoSuchAlgorithmException, InvalidKeySpecException { String[] parts = storedPassword.split(":"); int iterations = Integer.parseInt(parts[0]); byte[] salt = fromHex(parts[1]); byte[] hash = fromHex(parts[2]); PBEKeySpec spec = new PBEKeySpec(originalPassword.toCharArray(), salt, iterations, hash.length * 8); SecretKeyFactory skf = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1"); byte[] testHash = skf.generateSecret(spec).getEncoded(); int diff = hash.length ^ testHash.length; for (int i = 0; i < hash.length && i < testHash.length; i++) { diff |= hash[i] ^ testHash[i]; } return diff == 0; } /** * Retourne le chemin du serveur * * @return */ public static String getCurrentDirectoryOfServer() { //On recup�re le chemin du repertoire AppCommonContext.REPERTOIRE_SERVEUR = getCurrentDirectory().getParent() + File.separator + "standalone" + File.separator + "data" + File.separator + "donnees"; return AppCommonContext.REPERTOIRE_SERVEUR; } /** * Retourne le chemin du serveur * * @return */ public static String getCurrentTempDirectoryOfServer() { //On recup�re le chemin du repertoire AppCommonContext.REPERTOIRE_SERVEUR = getCurrentDirectory().getParent() + File.separator + "standalone" + File.separator + "tmp"; return AppCommonContext.REPERTOIRE_SERVEUR; } /** * Retourn le chemin courant * * @return */ public static File getCurrentDirectory() { String fileName = (String) System.getProperties().get("user.dir"); return new File(fileName); } public static Properties loadProperties(String filename) { Properties properties = new Properties(); try { //On charge le fichier de config properties.load(new FileInputStream(filename)); } catch (Exception ex) { //On affiche l'erreur ex.printStackTrace(); } return properties; } /** * Permet de convertir un hexadeicmal en tableau de byte * * @param hex * @return * @throws NoSuchAlgorithmException */ public static byte[] fromHex(String hex) throws NoSuchAlgorithmException { byte[] bytes = new byte[hex.length() / 2]; for (int i = 0; i < bytes.length; i++) { bytes[i] = (byte) Integer.parseInt(hex.substring(2 * i, 2 * i + 2), 16); } return bytes; } /** * * @param array * @return * @throws NoSuchAlgorithmException */ public static String toHex(byte[] array) throws NoSuchAlgorithmException { BigInteger bi = new BigInteger(1, array); String hex = bi.toString(16); int paddingLength = (array.length * 2) - hex.length(); if (paddingLength > 0) { return String.format("%0" + paddingLength + "d", 0) + hex; } else { return hex; } } /** * * @return @throws NoSuchAlgorithmException */ public static byte[] getSalt() throws NoSuchAlgorithmException { SecureRandom sr = SecureRandom.getInstance("SHA1PRNG"); byte[] salt = new byte[16]; sr.nextBytes(salt); return salt; } }