package com.megatim.apifdxweb.tools;
|
|
import com.lowagie.text.Document;
|
import com.lowagie.text.pdf.PdfContentByte;
|
import com.lowagie.text.pdf.PdfImportedPage;
|
import com.lowagie.text.pdf.PdfReader;
|
import com.lowagie.text.pdf.PdfWriter;
|
import com.opencsv.CSVReader;
|
import com.opencsv.CSVReaderBuilder;
|
import io.github.classgraph.ClassGraph;
|
import io.github.classgraph.ClassInfoList;
|
import io.github.classgraph.ScanResult;
|
import java.io.BufferedReader;
|
import java.io.File;
|
import java.io.FileInputStream;
|
import java.io.FileOutputStream;
|
import java.io.IOException;
|
import java.io.InputStreamReader;
|
import java.io.OutputStream;
|
import java.io.Reader;
|
import java.math.BigDecimal;
|
import java.math.BigInteger;
|
import java.security.NoSuchAlgorithmException;
|
import java.security.SecureRandom;
|
import java.security.spec.InvalidKeySpecException;
|
import java.text.ParseException;
|
import java.text.SimpleDateFormat;
|
import java.util.ArrayList;
|
import java.util.Date;
|
import java.util.List;
|
import java.util.Map;
|
import java.util.Properties;
|
import javax.crypto.SecretKeyFactory;
|
import javax.crypto.spec.PBEKeySpec;
|
import java.lang.annotation.Annotation;
|
import java.text.NumberFormat;
|
import java.util.Calendar;
|
import java.util.Iterator;
|
import net.sf.jasperreports.engine.JasperExportManager;
|
import net.sf.jasperreports.engine.JasperFillManager;
|
import net.sf.jasperreports.engine.JasperPrint;
|
import net.sf.jasperreports.engine.JasperReport;
|
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
|
import net.sf.jasperreports.engine.util.JRLoader;
|
import org.apache.poi.ss.usermodel.Sheet;
|
import org.apache.poi.ss.usermodel.Workbook;
|
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
|
import org.apache.poi.xwpf.usermodel.XWPFDocument;
|
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
|
import org.apache.poi.xwpf.usermodel.XWPFRun;
|
import com.megatim.export.excel.Export;
|
import java.io.InputStream;
|
import java.time.LocalDate;
|
import java.time.ZoneId;
|
import java.time.format.DateTimeFormatter;
|
import java.time.format.FormatStyle;
|
import java.util.Locale;
|
import java.util.stream.IntStream;
|
import org.apache.poi.ss.usermodel.Cell;
|
import org.apache.poi.ss.usermodel.Row;
|
import javax.ws.rs.core.MultivaluedMap;
|
|
/*
|
* 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 CommonsTools {
|
|
/**
|
* Methode permettant de fusionner plusieur pdf
|
*
|
* @param inputPdfList
|
* @param outputStream
|
* @throws Exception
|
*/
|
public static void mergePdfFiles(List<InputStream> inputPdfList, OutputStream outputStream) throws Exception {
|
//Create document and pdfReader objects.
|
Document document = new Document();
|
List<PdfReader> readers
|
= new ArrayList<>();
|
int totalPages = 0;
|
|
//Create pdf Iterator object using inputPdfList.
|
Iterator<InputStream> pdfIterator
|
= inputPdfList.iterator();
|
|
// Create reader list for the input pdf files.
|
while (pdfIterator.hasNext()) {
|
InputStream pdf = pdfIterator.next();
|
PdfReader pdfReader = new PdfReader(pdf);
|
readers.add(pdfReader);
|
totalPages = totalPages + pdfReader.getNumberOfPages();
|
}
|
|
// Create writer for the outputStream
|
PdfWriter writer = PdfWriter.getInstance(document, outputStream);
|
|
//Open document.
|
document.open();
|
|
//Contain the pdf data.
|
PdfContentByte pageContentByte = writer.getDirectContent();
|
|
PdfImportedPage pdfImportedPage;
|
int currentPdfReaderPage = 1;
|
Iterator<PdfReader> iteratorPDFReader = readers.iterator();
|
|
// Iterate and process the reader list.
|
while (iteratorPDFReader.hasNext()) {
|
PdfReader pdfReader = iteratorPDFReader.next();
|
//Create page and add content.
|
while (currentPdfReaderPage <= pdfReader.getNumberOfPages()) {
|
document.newPage();
|
pdfImportedPage = writer.getImportedPage(
|
pdfReader, currentPdfReaderPage);
|
pageContentByte.addTemplate(pdfImportedPage, 0, 0);
|
currentPdfReaderPage++;
|
}
|
currentPdfReaderPage = 1;
|
}
|
|
//Close document and outputStream.
|
outputStream.flush();
|
document.close();
|
outputStream.close();
|
|
}
|
|
/**
|
* Permet de convertir un tableau de bytes en un fichier
|
*
|
* @param nomFichier
|
* @param content
|
* @return
|
*/
|
public static File convertBytesArrayToFile(String nomFichier, byte[] content) {
|
|
//Variables
|
FileOutputStream fileOuputStream = null;
|
File fichier = null;
|
|
try {
|
|
//Variables
|
fileOuputStream = new FileOutputStream(nomFichier);
|
|
//On lit le fichier
|
fileOuputStream.write(content);
|
|
//On ferme le fichier
|
fileOuputStream.close();
|
|
} catch (Exception ex) {
|
|
//On affiche l'erreur
|
ex.printStackTrace();
|
|
}
|
|
return new File(nomFichier);
|
}
|
|
/**
|
* Permet de convertir un fichier en tableau de bytes
|
*
|
* @param fichier
|
* @return
|
*/
|
public static byte[] convertFileToBytesArray(File fichier) {
|
|
//Variables
|
byte[] byteArray = new byte[(int) fichier.length()];
|
|
try {
|
|
//Variables
|
FileInputStream inputStream = new FileInputStream(fichier);
|
|
//On lit le fichier
|
inputStream.read(byteArray);
|
|
//On ferme le fichier
|
inputStream.close();
|
|
} catch (Exception ex) {
|
|
//On affiche l'erreur
|
ex.printStackTrace();
|
|
}
|
|
return byteArray;
|
}
|
|
/**
|
* 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;
|
}
|
|
/**
|
* Permet de verifier si une liste de valeurs est contenu dans une chaine
|
*
|
* @param chaine
|
* @param tab
|
* @return
|
*/
|
public static boolean contains(String chaine, List<String> tab) {
|
|
//Variables
|
boolean bool = false;
|
|
//Si non vide
|
if (tab != null && !tab.isEmpty()) {
|
|
//On parcourt la liste des valeurs
|
for (String valeur : tab) {
|
|
//Si la chaine est contenu dans la chaine
|
if (chaine.contains(valeur)) {
|
|
//On set la valeur
|
bool = true;
|
|
//On sort
|
break;
|
|
}
|
|
}
|
|
}
|
|
return bool;
|
}
|
|
/**
|
* Cette methode permet les donnees depuis un fichier excel
|
*
|
* @param file
|
* @return
|
*/
|
public static List<Cell> readExcelFile(File file) {
|
|
//On definit de variables de reference
|
FileInputStream inputStream = null;
|
Workbook workbook = null;
|
Sheet firstSheet = null;
|
Iterator<Row> iterator = null;
|
|
//Declaration
|
List<Cell> cellules = new ArrayList<Cell>();
|
|
try {
|
|
//Affectation
|
inputStream = new FileInputStream(file);
|
workbook = new XSSFWorkbook(inputStream);
|
firstSheet = workbook.getSheetAt(0);
|
//iterator = firstSheet.iterator();
|
|
for (int rowNumber = firstSheet.getFirstRowNum(); rowNumber <= firstSheet.getLastRowNum(); rowNumber++) {
|
Row row = firstSheet.getRow(rowNumber);
|
if (row == null) {
|
// This row is completely empty
|
} else {
|
// The row has data
|
for (int cellNumber = row.getFirstCellNum(); cellNumber <= row.getLastCellNum(); cellNumber++) {
|
Cell cell = row.getCell(cellNumber, Row.MissingCellPolicy.RETURN_BLANK_AS_NULL);
|
|
// if (cell == null || cell.getCellType() == Cell.CELL_TYPE_BLANK) {
|
//
|
// //On ajoute la cellule
|
// cellules.add(cell);
|
//
|
// } else {
|
//
|
//
|
//
|
// }
|
//On ajoute la cellule
|
cellules.add(cell);
|
// if(cell != null){
|
// System.out.println(">>>>>>>>>>>>>"+cell.getCellValue());
|
// }else{
|
// System.out.println("Cell NULLL>>>>>>>>>>>>>");
|
// }
|
|
}
|
}
|
}
|
|
//On parcour la feuille
|
// while (iterator.hasNext()) {
|
// Row nextRow = iterator.next();
|
// Iterator<Cell> cellIterator = nextRow.cellIterator();
|
//
|
// //On parcour les cellules
|
// while (cellIterator.hasNext()) {
|
//
|
// //On ajoute les cellules
|
// cellules.add(cellIterator.next());
|
// }
|
// }
|
//
|
//On ferme le classeur
|
workbook.close();
|
|
//On ferme le stream
|
inputStream.close();
|
|
} catch (Exception ex) {
|
|
//On affiche l'erreur
|
ex.printStackTrace();
|
|
} finally {
|
try {
|
inputStream.close();
|
} catch (IOException ex) {
|
|
//On affiche l'erreur
|
ex.printStackTrace();
|
|
}
|
}
|
|
return cellules;
|
}
|
|
/**
|
* Permet de lire un fichier csv
|
*
|
* @param file
|
* @return
|
* @throws Exception
|
*/
|
public static List<String[]> readCsvFile(File file) throws Exception {
|
|
//Variables
|
List<String[]> allData = null;
|
InputStreamReader inputStreamReader = new InputStreamReader(new FileInputStream(file), "UTF-8");
|
CSVReader csvReader = null;
|
|
try {
|
|
// create csvReader object and skip first Line
|
try {
|
|
//On lit le fichier
|
csvReader = new CSVReaderBuilder(inputStreamReader)
|
.withSkipLines(1)
|
.build();
|
|
//On recup�re les donn�es
|
allData = csvReader.readAll();
|
|
} catch (Exception ex) {
|
|
//On affiche l'erreur
|
ex.printStackTrace();
|
|
} finally {
|
|
//On ferme le reader
|
csvReader.close();
|
}
|
|
} finally {
|
|
//On ferme le fichier
|
inputStreamReader.close();
|
}
|
|
return allData;
|
}
|
|
/**
|
* Permet de mettre de mettre l'heure � minuit
|
*
|
* @param date
|
* @return
|
*/
|
public static Date passerHeureAMinuit(Date date) {
|
Calendar calendar = Calendar.getInstance();
|
calendar.setTime(date);
|
calendar.set(Calendar.HOUR_OF_DAY, 0);
|
calendar.set(Calendar.MINUTE, 0);
|
calendar.set(Calendar.SECOND, 0);
|
calendar.set(Calendar.MILLISECOND, 0);
|
|
return calendar.getTime();
|
}
|
|
/**
|
* Permet de retourner la liste des codes valeurs ch�que
|
*
|
* @return
|
*/
|
public static List<String> getCodeValeursCheque() {
|
|
//Variables
|
List<String> liste = new ArrayList<String>();
|
|
//On charge
|
liste.add("30");
|
liste.add("33");
|
|
return liste;
|
}
|
|
/**
|
* Permet de retourner la liste des codes valeurs virement
|
*
|
* @return
|
*/
|
public static List<String> getCodeValeursVirement() {
|
|
//Variables
|
List<String> liste = new ArrayList<String>();
|
|
//On charge
|
liste.add("10");
|
liste.add("13");
|
|
return liste;
|
}
|
|
/**
|
* permet de g��nrer en pdf
|
*
|
* @param datas
|
* @param pdfFile
|
* @param reportFilePath
|
* @param params
|
* @return
|
* @throws Exception
|
*/
|
public static File genererFichierPdf(List<?> datas, String pdfFile, String reportFilePath, Map params) throws Exception {
|
|
// Creation d'un File sur le fichier
|
File reportFile = new File(reportFilePath);
|
File fichierGenerer = new File(pdfFile);
|
|
//On cree le fichier s'ile n'existe pas
|
if (!fichierGenerer.exists()) {
|
|
//On cree le fichier
|
fichierGenerer.createNewFile();
|
|
}
|
|
// Chargement du Rapport
|
JasperReport report = null;
|
|
// Etat rempli
|
JasperPrint jasperPrint = null;
|
|
// Chargement du report
|
report = (JasperReport) JRLoader.loadObject(reportFile);
|
jasperPrint = JasperFillManager.fillReport(report, params, new JRBeanCollectionDataSource(datas, false));
|
|
OutputStream output = new FileOutputStream(fichierGenerer);
|
JasperExportManager.exportReportToPdfStream(jasperPrint, output);
|
output.close();
|
|
return fichierGenerer;
|
}
|
|
/**
|
* Permet de modifier un document word
|
*
|
* @param map
|
* @param pathFile
|
* @param repertoireDestination
|
* @return
|
* @throws Exception
|
*/
|
public static String updateWordFileToOtherFile(Map<String, Object> map, String pathFile, String fileName, String repertoireDestination) throws Exception {
|
|
try {
|
// System.out.println("---------------------------updateWordFileToOtherFile----------1111111111111--------------------------------------"+pathFile);
|
//Variables
|
FileInputStream fis = new FileInputStream(pathFile);
|
XWPFDocument doc = new XWPFDocument(fis);
|
FileOutputStream out = null;
|
//String fileName = genererValeurAleatoire() + ".docx";
|
String filePathDestination = repertoireDestination + File.separator + fileName + ".docx";
|
|
//On parcourt le document
|
for (Map.Entry<String, Object> entry : map.entrySet()) {
|
for (XWPFParagraph p : doc.getParagraphs()) {
|
List<XWPFRun> runs = p.getRuns();
|
if (runs != null) {
|
for (XWPFRun r : runs) {
|
String text = r.getText(0);
|
|
//On verifie s'il elle contient la cle
|
if (text != null && text.contains(entry.getKey())) {
|
|
//Si la valeur est non vide
|
if (entry.getValue() != null) {
|
|
//On dermine le type
|
if (entry.getValue() instanceof String) {
|
text = text.replace(entry.getKey(), (String) entry.getValue());
|
r.setText(text, 0);
|
} else {
|
text = text.replace(entry.getKey(), entry.getValue().toString());
|
r.setText(text, 0);
|
}
|
|
} else {
|
r.setText("", 0);
|
}
|
}
|
}
|
}
|
}
|
}
|
|
//On ecrit dans le fichier
|
out = new FileOutputStream(new File(filePathDestination));
|
doc.write(out);
|
out.close();
|
doc.close();
|
|
return filePathDestination;
|
|
} catch (Exception ex) {
|
ex.printStackTrace();
|
}
|
|
return null;
|
}
|
|
/**
|
* Permet de generer des nomre aleatorement
|
*
|
* @return
|
*/
|
public static String genererValeurAleatoire() {
|
SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
|
String nombre = format.format(new Date()) + String.valueOf((int) (Math.random() * 1000000000));
|
return nombre;
|
}
|
|
/**
|
* Permet de charger des classes qui ont une annotation pr�cise
|
*
|
* @param pkgName
|
* @param annotation
|
* @return
|
*/
|
public static List<Annotation> getAnnotations(final String pkgName, String annotation) {
|
|
//Variables
|
List<Class<?>> classRefs = new ArrayList<>();
|
|
List<Annotation> 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<Class<?>> getAnnotatedClasses(final String pkgName, String annotation) {
|
|
//Variables
|
List<Class<?>> 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 verifier si une chaine est contenu un tableau de chaine
|
*
|
* @param value
|
* @param tab
|
* @return
|
* @throws Exception
|
*/
|
public static boolean in(String value, String tab[]) {
|
|
//Variables
|
boolean bool = false;
|
|
//Si non null
|
if (tab != null && value != null) {
|
|
//On parcourt la chaine
|
for (String obj : tab) {
|
|
//Si trouv�
|
if (obj.equalsIgnoreCase(value)) {
|
|
//On marque comme trouv�
|
bool = true;
|
|
//On sort
|
break;
|
|
}
|
|
}
|
|
}
|
|
return bool;
|
|
}
|
|
/**
|
* Permet verifier si une chaine est contenu un tableau de chaine
|
*
|
* @param value
|
* @param tab
|
* @return
|
* @throws Exception
|
*/
|
public static boolean contains(String value, String tab[]) {
|
|
//Variables
|
boolean bool = false;
|
|
//Si non null
|
if (tab != null && value != null) {
|
|
//On parcourt la chaine
|
for (String obj : tab) {
|
|
//Si trouv�
|
if (value.contains(obj)) {
|
|
//On marque comme trouv�
|
bool = true;
|
|
//On sort
|
break;
|
|
}
|
|
}
|
|
}
|
|
return bool;
|
|
}
|
|
/**
|
* Permet de charger le fichier
|
*
|
* @param contenuDuFichier
|
* @return
|
* @throws Exception
|
*/
|
public static List<String> lireFichier(File fichier) throws Exception {
|
|
//Variables
|
List<String> lignes = null;
|
|
//On charge le fichier
|
lignes = chargerLesDonnees(new FileInputStream(fichier));
|
|
return lignes;
|
}
|
|
/**
|
* Permet de charger le fichier
|
*
|
* @param contenuDuFichier
|
* @return
|
* @throws Exception
|
*/
|
public static List<String> chargerLesDonnees(Object contenuDuFichier) throws Exception {
|
|
//Variables
|
FileInputStream fichier = (FileInputStream) contenuDuFichier;
|
InputStreamReader inputStreamReader = new InputStreamReader(fichier);
|
BufferedReader entree;
|
List<String> contenuFichier;
|
String ligne = null;
|
|
//Affectation
|
entree = new BufferedReader((Reader) inputStreamReader);
|
contenuFichier = new ArrayList<String>();
|
|
//On parcourt ligne par ligne le fichier
|
while (true) {
|
|
//On lie une ligne dans le fichier
|
ligne = entree.readLine();
|
|
//Traitement si la ligne est non null
|
if (ligne != null) {
|
|
//On recupere la ligne
|
contenuFichier.add(ligne);
|
} else {
|
|
//On sort de la boucle
|
break;
|
|
}
|
}
|
|
//On close
|
entree.close();
|
|
return contenuFichier;
|
|
}
|
|
/**
|
* Permet de decouper le traitement en plusieurs processus
|
*
|
* @param <T>
|
* @param list
|
* @param subListNumber
|
* @return
|
*/
|
public static <T> List<List<T>> splitList(List<T> list, int subListNumber) {
|
|
//Liste a retourner
|
List<List<T>> splitted = new ArrayList<List<T>>();
|
|
//Si la liste est vide
|
if (list == null || list.size() == 0) {
|
return splitted;
|
}
|
|
//CAs sp?cifique du nombre de sous liste inf?rieur ? 1
|
if (subListNumber <= 1) {
|
|
//Ajout de la liste courante ? la liste des sous liste
|
splitted.add(list);
|
|
//retour de la liste des sous liste
|
return splitted;
|
}
|
|
//Taille de la liste
|
int listSize = list.size();
|
|
//taille de la sous liste
|
int subListSize = Math.max(listSize / (subListNumber - 1), 1);
|
|
//parcours de la liste a splitter
|
for (int i = 0; i < listSize; i += subListSize) {
|
|
//Ajout de la sous-liste
|
splitted.add(new ArrayList<T>(list.subList(i, Math.min(listSize, i + subListSize))));
|
}
|
|
//On retourne la liste des sous-liste
|
return splitted;
|
|
}
|
|
/**
|
* 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 d'ecrire le fichier sur el disque
|
*
|
* @param content
|
* @param filename
|
* @throws IOException
|
*/
|
public static void ecrireFichier(byte[] content, String filename) throws IOException {
|
File file = new File(filename);
|
if (!file.exists()) {
|
file.createNewFile();
|
}
|
FileOutputStream fop = new FileOutputStream(file);
|
fop.write(content);
|
fop.flush();
|
fop.close();
|
}
|
|
/**
|
* Permet de recup�erer le nom du fichier
|
*
|
* @param headers
|
* @return
|
*/
|
public static String getNomFichier(MultivaluedMap<String, String> headers) {
|
String[] contentDisposition = headers.getFirst("Content-Disposition").split(";");
|
for (String filename : contentDisposition) {
|
if ((filename.trim().startsWith("filename"))) {
|
String[] name = filename.split("=");
|
String finalFileName = name[1].trim().replaceAll("\"", "");
|
return finalFileName;
|
}
|
}
|
return "";
|
}
|
//
|
// /**
|
// * Permet de convertir un object java en json
|
// *
|
// * @param objects
|
// * @return
|
// */
|
// public static String convertirJavaToJson(List<Object> objects) {
|
//
|
// //Variables
|
// ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
|
// StringBuilder json = new StringBuilder();
|
//
|
// try {
|
//
|
// //Si non null
|
// if (objects != null && !objects.isEmpty()) {
|
//
|
// //On parcourt la liste
|
// for (Object obj : objects) {
|
//
|
// //On parse en json
|
// json.append(convertirJavaToJson(obj));
|
//
|
// }
|
//
|
// }
|
//
|
// } catch (Exception ex) {
|
//
|
// //On affiche l'erreur
|
// ex.printStackTrace();
|
//
|
// }
|
//
|
// return json.toString();
|
//
|
// }
|
|
/**
|
* Permet de convertir un object java en json
|
*
|
* @param object
|
* @return
|
*/
|
// public static String convertirJavaToJson(Object object) {
|
//
|
// //Variables
|
// ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
|
// String json = null;
|
//
|
// try {
|
//
|
// //On convertit en json
|
// json = ow.writeValueAsString(object);
|
//
|
// } catch (Exception ex) {
|
//
|
// //On affiche l'erreur
|
// ex.printStackTrace();
|
//
|
// }
|
//
|
// return json;
|
//
|
// }
|
/**
|
* Permet de hacher le mot de passe
|
*
|
* @param password
|
* @return
|
* @throws NoSuchAlgorithmException
|
* @throws InvalidKeySpecException
|
*/
|
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;
|
}
|
|
/**
|
*
|
* @return @throws NoSuchAlgorithmException
|
*/
|
public static byte[] getSalt() throws NoSuchAlgorithmException {
|
SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
|
byte[] salt = new byte[16];
|
sr.nextBytes(salt);
|
return salt;
|
}
|
|
/**
|
*
|
* @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;
|
}
|
}
|
|
/**
|
* 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;
|
}
|
|
/**
|
* 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;
|
}
|
|
/**
|
* Permet de convertir une chaine en date
|
*
|
* @param formatSource
|
* @param date
|
* @return
|
*/
|
public static Date getStringToDate(String formatSource, String date) {
|
|
//Variables
|
SimpleDateFormat valeur = new SimpleDateFormat(formatSource);
|
|
try {
|
|
return valeur.parse(date);
|
|
} catch (Exception ex) {
|
|
//On affiche l'erreur
|
ex.printStackTrace();
|
|
return null;
|
|
}
|
}
|
|
/**
|
* 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;
|
}
|
|
/**
|
* Echapper des caractere pour une requete sql
|
*
|
* @param chaine
|
* @return
|
*/
|
public static String echapperCaractereRequete(String chaine) {
|
|
//Si non null
|
if (chaine != null) {
|
|
//on echappe
|
chaine = chaine.replaceAll("'", "''");
|
|
//On retourne
|
return chaine;
|
|
} else {
|
return "";
|
}
|
|
}
|
|
/**
|
* Permet de determiner le nombre d'occurences de cheques
|
*
|
* @param ncheque
|
* @return
|
*/
|
public static int getNombreChequesTrouve(Map<String, Object> nbreOccurencesCheques, String numeroCheque) {
|
|
//Variables
|
int nbre = 0;
|
|
//On teste si la liste est non vide
|
if (nbreOccurencesCheques != null && nbreOccurencesCheques.get(numeroCheque.trim()) != null) {
|
|
//On recupere le nombre
|
nbre = ((BigDecimal) nbreOccurencesCheques.get(numeroCheque.trim())).intValue();
|
|
}
|
|
return nbre;
|
|
}
|
|
/**
|
* Permet de mettre la premi�re lettre en majuscule uniquement
|
*
|
* @param chaine
|
* @return
|
*/
|
public static String mettreLesPremieresLettresChaineEnMajuscule(String chaine) {
|
|
//Vairiables
|
String resultat = "";
|
String tab[] = null;
|
|
//On splitte sur la base des espaces
|
tab = chaine.split(" ");
|
|
if (tab != null) {
|
|
//On parcourt la chaine
|
for (int i = 0; i < tab.length; i++) {
|
|
//Si nous ne sommes pas encore arriv� � la fin de la chaine
|
if (i < (tab.length - 1)) {
|
resultat = resultat + mettrePremiereLettreEnMajuscule(tab[i]) + " ";
|
} else {
|
resultat = resultat + mettrePremiereLettreEnMajuscule(tab[i]);
|
}
|
|
}
|
|
}
|
|
return resultat;
|
}
|
|
/**
|
* Permet de mettre la premi�re lettre en majuscule uniquement
|
*
|
* @param chaine
|
* @return
|
*/
|
public static String mettrePremiereLettreEnMajuscule(String chaine) {
|
|
//Variables
|
String resultat = "";
|
|
if (chaine != null && !chaine.isEmpty()) {
|
|
//On met toute la chaine en minuscule
|
resultat = chaine.toLowerCase();
|
|
//On met la premiere lettre en majucule
|
char premiereLettre = resultat.charAt(0);
|
|
// convert it to an UpperCase letter
|
char premiereLettreMajuscule = Character.toUpperCase(premiereLettre);
|
|
//On ajoute remplace la premiere lettre
|
resultat = resultat.replaceFirst(Character.toString(resultat.charAt(0)), Character.toString(premiereLettreMajuscule));
|
|
}
|
|
return resultat;
|
}
|
|
/**
|
* Permet de convertir la date en toutes lettres
|
*
|
* @param date
|
* @param langue
|
* @param format
|
* @return
|
*/
|
public static String convertirDateEnToutesLettres(Date date, Locale langue, FormatStyle format) {
|
|
//Variables
|
LocalDate dateConvertie = null;
|
String resultat = "";
|
|
//Si non null
|
if (date != null) {
|
|
//On convertit la date en type LocalDate
|
dateConvertie = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
|
|
//On convertit en toutes lettres
|
resultat = dateConvertie.format(DateTimeFormatter.ofLocalizedDate(format).withLocale(langue));
|
|
}
|
|
return resultat;
|
|
}
|
|
/**
|
* Permet de formatter une date
|
*
|
* @return the datePresentation
|
*/
|
public static String formaterDate(String format, Date date) {
|
|
if (date != null) {
|
return new SimpleDateFormat(format).format(date);
|
} else {
|
return "";
|
}
|
}
|
|
/**
|
* Permet de formatter une date recu yyyyMMdd en ce format dd/MM/yy
|
*
|
* @return the datePresentation
|
*/
|
public static String formatetterDate3(String dateAformatee) {
|
|
//On formate la date jj/MM/yyyy
|
String dateFormatee = null;
|
|
if (dateAformatee != null) {
|
|
String annee = dateAformatee.substring(0, 2);
|
String mois = dateAformatee.substring(2, 4);
|
String jour = dateAformatee.substring(4, 6);
|
dateFormatee = jour + "/" + mois + "/" + annee;
|
|
return dateFormatee;
|
|
} else {
|
|
return dateAformatee;
|
|
}
|
}
|
|
/**
|
* Prend une date au format yyyyMMdd et la transforme au format dd/MM/yyyy
|
*
|
* @param date
|
*/
|
public static String formaterDateddMMyyyy(String date) {
|
|
//On formate la date jj/MM/yyyy
|
String dateFormatee = null;
|
|
if (date != null) {
|
|
String annee = date.substring(0, 4);
|
String mois = date.substring(4, 6);
|
String jour = date.substring(6, 8);
|
dateFormatee = jour + "/" + mois + "/" + annee;
|
|
return dateFormatee;
|
} else {
|
return date;
|
}
|
|
}
|
|
/**
|
* Prend une date au format yyyyMMddHHmmss et la transforme au format
|
* dd/MM/yyyy � HH:mm:ss
|
*
|
* @param date
|
*/
|
public static String formaterDateddMMyyyyHHmmss(String date) {
|
|
//On formate la date jj/MM/yyyy
|
String dateFormatee = null;
|
String heureFormatee = null;
|
|
if (date != null) {
|
|
String annee = date.substring(0, 4);
|
String mois = date.substring(4, 6);
|
String jour = date.substring(6, 8);
|
String heure = date.substring(8, 10);
|
String minute = date.substring(10, 12);
|
String seconde = date.substring(12, 14);
|
|
dateFormatee = jour + "/" + mois + "/" + annee;
|
heureFormatee = heure + ":" + minute + ":" + seconde;
|
|
return dateFormatee + " � " + heureFormatee;
|
} else {
|
return date;
|
}
|
|
}
|
|
/**
|
* Prend une date au format yyMMdd et la transforme au format dd/MM/yy
|
*
|
* @param date
|
*/
|
public static String formaterDateyyMMdd(String date) {
|
|
//On formate la date jj/MM/yyyy
|
String dateFormatee = null;
|
|
if (date != null) {
|
|
String annee = date.substring(0, 2);
|
String mois = date.substring(2, 4);
|
String jour = date.substring(4, 6);
|
dateFormatee = jour + "/" + mois + "/" + annee;
|
|
return dateFormatee;
|
} else {
|
return date;
|
}
|
|
}
|
|
/**
|
* On affiche l'etat du virement
|
*
|
* @param item
|
* @return
|
*/
|
public static String getCodeAgenceToRIB(String rib) {
|
|
//On test si le rib respecte la taille
|
if (rib != null && rib.length() >= 10) {
|
return rib.substring(5, 10);
|
} else {
|
return rib;
|
}
|
|
}
|
|
/**
|
* Permet de formatter une date recu yyyyMMdd en ce format dd/MM/yyyy
|
*
|
* @return the datePresentation
|
*/
|
public static String formaterDateAuFormat(String format, String date) {
|
|
//Variables
|
Date valeur = null;
|
String dateFinale = "";
|
SimpleDateFormat formatDest = new SimpleDateFormat("dd/MM/yyyy");
|
|
//On recup�re la date
|
if (date != null && !date.trim().isEmpty()) {
|
|
try {
|
|
//Onr recupere la date
|
valeur = new SimpleDateFormat(format).parse(date);
|
|
//On formate au bon format
|
dateFinale = formatDest.format(valeur);
|
|
} catch (ParseException ex) {
|
|
//On affiche l'erreur
|
ex.printStackTrace();
|
|
}
|
}
|
|
return dateFinale;
|
|
}
|
|
/**
|
* Fonction permettant d'appliquer le s�parateur de millier sur les montants
|
*
|
* @param montant
|
* @return
|
*/
|
public static String separateurMillier(BigDecimal montant) {
|
NumberFormat numberFormat = NumberFormat.getInstance(java.util.Locale.FRENCH);
|
return (numberFormat.format(montant));
|
}
|
|
/**
|
* Permet de formatter une date
|
*
|
* @param formatSource
|
* @param date
|
* @param formatDestinataire
|
* @return
|
*/
|
public static String formaterDateAuFormat(String formatSource, String date, String formatDestinataire) {
|
|
//Variables
|
Date valeur = null;
|
String dateFinale = "";
|
SimpleDateFormat format = new SimpleDateFormat(formatDestinataire);
|
|
//On recup�re la date
|
if (date != null && !date.trim().isEmpty()) {
|
|
try {
|
|
//Onr recupere la date
|
valeur = new SimpleDateFormat(formatSource).parse(date);
|
|
//On formate au bon format
|
dateFinale = format.format(valeur);
|
|
} catch (ParseException ex) {
|
|
//On affiche l'erreur
|
ex.printStackTrace();
|
|
}
|
}
|
|
return dateFinale;
|
|
}
|
|
/**
|
* Permet determiner confirmation Sygma
|
*
|
* @param taille
|
* @param chaine
|
* @return
|
*/
|
public static String determinerConfirmation(String dateReglement) {
|
|
//On teste si la chaine est non vide
|
if (dateReglement != null && !dateReglement.isEmpty()) {
|
return "Confirm�";
|
} else {
|
return "Non Confirm�";
|
}
|
|
}
|
|
public static String getFileExtension(String fileName) {
|
String extension = "";
|
|
try {
|
extension = fileName.substring(fileName.lastIndexOf("."));
|
} catch (Exception e) {
|
extension = "";
|
}
|
|
return extension;
|
|
}
|
|
/**
|
* Permet de retourer la taille en Kilo d'un fichier
|
*
|
* @param file
|
* @return
|
*/
|
public static double getFileSizeKiloOctects(double octets) {
|
return (double) octets / 1024;
|
}
|
|
/**
|
* Permet de convertir un type en long en type Date
|
*
|
* @param file
|
* @return
|
*/
|
public static Date convertLongTODate(Long time) {
|
|
//Variables
|
Calendar c = Calendar.getInstance();
|
Date date = null;
|
|
//Si non null
|
if (time != null) {
|
|
//On set la valeur
|
c.setTimeInMillis(time);
|
|
//On recup�re la date
|
date = c.getTime();
|
|
}
|
|
return date;
|
}
|
|
public static String buildErrorMessage(List<String> errors) {
|
StringBuilder stringBuilder = new StringBuilder("");
|
int size = errors.size();
|
IntStream.range(0, size).forEach(index -> {
|
String message = errors.get(index);
|
if ((index + 1) < size) {
|
stringBuilder.append(message).append("\n");
|
} else {
|
stringBuilder.append(message);
|
}
|
});
|
return stringBuilder.toString();
|
}
|
|
}
|