/*
|
* 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.fdxgenerator.utilities;
|
|
import java.beans.IntrospectionException;
|
import java.beans.PropertyDescriptor;
|
import java.io.FileNotFoundException;
|
import java.io.FileReader;
|
import java.io.IOException;
|
import java.io.LineNumberReader;
|
import java.lang.reflect.Field;
|
import java.lang.reflect.InvocationTargetException;
|
import java.lang.reflect.Method;
|
import java.util.ArrayList;
|
import java.util.HashMap;
|
import java.util.List;
|
import java.util.Map;
|
import java.util.logging.Level;
|
import java.util.logging.Logger;
|
|
/**
|
*
|
* @author mela
|
*/
|
public class ImportData {
|
|
/**
|
* Méthode qui parse le fichier csv et en extrait les données
|
*
|
* @param datIm
|
* @return
|
*/
|
public static <T> List<T> importDataFromCsvFile(DataToImport<T> datIm) throws AttributeFormatException {
|
FileReader reader = null;
|
List<String[]> datas = new ArrayList<>();
|
List<T> listeToReturn = new ArrayList<>();
|
|
if (datIm != null) {
|
try {
|
reader = new FileReader(datIm.getFile() + "");
|
LineNumberReader lineReader = new LineNumberReader(reader);
|
String line = "";
|
|
while ((line = lineReader.readLine()) != null) {
|
String[] row = line.split(datIm.getRowDelimiter());
|
for (String r : row) {
|
String[] values = new String[datIm.getFields().size()];
|
String[] columns = r.split(datIm.getColumnDelimiter());
|
|
int ss = 0;
|
while (ss < datIm.getFields().size() && ss < columns.length) {
|
values[ss] = columns[ss];
|
ss++;
|
}
|
datas.add(values);
|
}
|
|
}
|
} catch (FileNotFoundException ex) {
|
Logger.getLogger(ImportData.class.getName()).log(Level.SEVERE, ex.getMessage(), ex);
|
} catch (IOException ex) {
|
Logger.getLogger(ImportData.class.getName()).log(Level.SEVERE, ex.getMessage(), ex);
|
} finally {
|
try {
|
reader.close();
|
} catch (IOException | NullPointerException ex) {
|
Logger.getLogger(ImportData.class.getName()).log(Level.SEVERE, ex.getMessage(), ex);
|
}
|
}
|
|
if (!datas.isEmpty()) {
|
|
//tous les champs du type paramétré
|
Field[] fields = datIm.getType().getDeclaredFields();
|
|
// mettre les champs du type paramétré dans une map afin de faciliter leur accès
|
Map<String, Field> fieldsToMap = fieldsToMap(fields);
|
datas.forEach(d -> {
|
try {
|
T obj = datIm.getType().newInstance();
|
Map<String, String> map = tabToMap(datIm.getFields(), d);
|
for (Field field : fields) {
|
String fieldName = field.getName();
|
if (map.containsKey(fieldName) && fieldsToMap.containsKey(fieldName)) {
|
try {
|
Object converted = convertToPrimitive(field, map.get(fieldName));
|
Method method = new PropertyDescriptor(fieldName, datIm.getType()).getWriteMethod();
|
method.invoke(obj, converted);
|
} catch (IntrospectionException | IllegalAccessException | InvocationTargetException ex) {
|
Logger.getLogger(ImportData.class.getName()).log(Level.SEVERE, ex.getMessage(), ex);
|
} catch (IllegalArgumentException | ClassCastException ex) {
|
throw new AttributeFormatException("Erreur de type sur le champ " + fieldName);
|
}
|
}
|
}
|
listeToReturn.add(obj);
|
} catch (InstantiationException | IllegalAccessException ex) {
|
Logger.getLogger(ImportData.class.getName()).log(Level.SEVERE, ex.getMessage(), ex);
|
}
|
|
});
|
}
|
}
|
return listeToReturn;
|
}
|
|
/**
|
* Méthode qui met les libellés des colonnes et leurs valeurs
|
* correspondantes dans une map
|
*
|
* @param titles : ensemble des noms de colonnes
|
* @param values : ensemble des données
|
* @return : rentourne une map (clé,valeur) = (nom_de_la_colonne,
|
* valeur_colonne)
|
*/
|
private static Map<String, String> tabToMap(List<String> titles, String[] values) {
|
Map<String, String> map = new HashMap<>();
|
for (int i = 0; i < titles.size(); i++) {
|
map.put(titles.get(i), values[i]);
|
}
|
|
return map;
|
}
|
|
/**
|
* Méthode qui met un tableau de Field dans une
|
* map<nom_du_champ,objet représentant_le_champ>
|
* afin de faciliter leur accès
|
*
|
* @param fields
|
* @return
|
*/
|
private static Map<String, Field> fieldsToMap(Field[] fields) {
|
Map<String, Field> map = new HashMap<>();
|
for (Field f : fields) {
|
map.put(f.getName(), f);
|
}
|
|
return map;
|
}
|
|
/**
|
* Méthode qui fait la conversion de la donnée extraite vers un type
|
* primitif
|
*
|
* @param field : objet contenant les informations sur le type auquel
|
* appartient le champ de la donnée extraite
|
* @param value : donnée à convertir
|
* @return : retourne un String si le type du champ ne figure pas dans la
|
* liste ci-dessus
|
*/
|
private static Object convertToPrimitive(Field field, String value) {
|
Object obj = value;
|
|
if (field.getType().isAssignableFrom(Integer.class)
|
|| field.getType().isAssignableFrom(int.class)) {
|
obj = Integer.parseInt(value);
|
} else if (field.getType().isAssignableFrom(Double.class)
|
|| field.getType().isAssignableFrom(double.class)) {
|
obj = Double.parseDouble(value);
|
} else if (field.getType().isAssignableFrom(java.math.BigDecimal.class)) {
|
obj = new java.math.BigDecimal(value);
|
} else if (field.getType().isAssignableFrom(Float.class)
|
|| field.getType().isAssignableFrom(float.class)) {
|
obj = Float.valueOf(value);
|
} else if (field.getType().isAssignableFrom(Long.class)
|
|| field.getType().isAssignableFrom(long.class)) {
|
obj = Long.parseLong(value);
|
} else if (field.getType().isAssignableFrom(Boolean.class)
|
|| field.getType().isAssignableFrom(boolean.class)) {
|
Boolean.parseBoolean(value);
|
}
|
|
return obj;
|
}
|
}
|