New file |
0,0 → 1,636 |
package org.tela_botanica.client.util; |
|
import java.text.NumberFormat; |
import java.text.ParsePosition; |
import java.util.ArrayList; |
import java.util.Collections; |
import java.util.Comparator; |
import java.util.HashMap; |
import java.util.Iterator; |
import java.util.List; |
import java.util.Map; |
import java.util.Vector; |
|
import org.tela_botanica.client.i18n.Msg; |
import org.tela_botanica.client.modeles.objets.ChampEtendu; |
import org.tela_botanica.client.modeles.objets.Configuration; |
import org.tela_botanica.client.modeles.objets.Observation; |
import org.tela_botanica.client.modeles.objets.ReferentielLocalite; |
import org.tela_botanica.client.modeles.objets.ReferentielNom; |
|
import com.google.gwt.core.client.Callback; |
import com.google.gwt.http.client.Request; |
import com.google.gwt.http.client.RequestCallback; |
import com.google.gwt.http.client.RequestException; |
import com.google.gwt.http.client.Response; |
import com.google.gwt.json.client.JSONArray; |
import com.google.gwt.json.client.JSONObject; |
import com.google.gwt.json.client.JSONParser; |
import com.google.gwt.json.client.JSONString; |
import com.google.gwt.json.client.JSONValue; |
import com.google.gwt.user.client.ui.RootPanel; |
|
public class Util { |
|
public Util() { |
} |
|
public static String getValeurJsonOuVide(JSONObject jo, String index) { |
return jsonNonNull(jo, index) ? ((JSONString)jo.get(index)).stringValue() : ""; |
} |
|
public static Map<String, ChampEtendu> getMapValeursOuVide(JSONObject jo, String index) { |
Map<String, ChampEtendu> mapValeurs = new HashMap<String, ChampEtendu>(); |
if(jo.get(index) != null && jo.get(index).isArray() != null) { |
JSONArray tabJo = jo.get(index).isArray(); |
for (int i = 0; i < tabJo.size(); i++) { |
JSONObject champJson = tabJo.get(i).isObject(); |
String cle = champJson.get("cle").isString().stringValue(); |
String label = cle; |
String valeur = champJson.get("valeur").isString().stringValue(); |
ChampEtendu champ = new ChampEtendu(cle, label, valeur); |
mapValeurs.put(cle, champ); |
} |
|
} |
return mapValeurs; |
} |
|
public static String convertirChampsEtendusEnChaineRequete(Map<String, ChampEtendu> map) { |
String json = ""; |
if (map != null && !map.isEmpty()) { |
JSONArray jsonArr = new JSONArray(); |
int i = 0; |
for (Map.Entry<String, ChampEtendu> entry: map.entrySet()) { |
jsonArr.set(i, convertirChampEtenduEnJson(entry.getValue())); |
i++; |
} |
json = jsonArr.toString(); |
} |
return json; |
} |
|
public static JSONObject convertirChampEtenduEnJson(ChampEtendu champEtendu) { |
JSONObject jsonObj = new JSONObject(); |
jsonObj.put("cle", new JSONString(champEtendu.getCle())); |
jsonObj.put("label", new JSONString(champEtendu.getLabel())); |
jsonObj.put("valeur", new JSONString(champEtendu.getValeur())); |
return jsonObj; |
} |
|
public static boolean jsonNonNull(JSONObject jo, String index) { |
return (jo != null && |
jo.get(index) != null && |
jo.get(index).isNull() == null |
); |
} |
|
public static String formaterLieu(Observation obs, String modeleLieu) { |
|
String lieuModele = modeleLieu; |
|
String localite = obs.getLocalite(); |
String lieuDit = obs.getLieudit(); |
String station = obs.getStation(); |
|
String lieulocaliteFormate = ""; |
String lieuDitFormate = ""; |
String stationFormatee = ""; |
|
if(localite != null && !localite.contains("000null") && !localite.trim().equals("")) { |
String idLoc =obs.getIdentifiantLocalite().replaceAll(" ","/"); |
if(idLoc != null && !idLoc.contains("000null") && !idLoc.trim().equals("")) { |
|
idLoc = idLoc.replaceAll("%",""); |
idLoc = idLoc.replaceAll("\"",""); |
idLoc = idLoc.replace('\\',' '); |
idLoc = idLoc.trim(); |
if(idLoc.length() > 2) { |
idLoc = idLoc.substring(0,2); |
} |
lieulocaliteFormate += idLoc+" - "; |
} |
lieulocaliteFormate += localite; |
lieuModele = lieuModele.replaceAll("IDLOCLOCALITE", lieulocaliteFormate); |
} else { |
|
lieuModele = lieuModele.replaceAll("IDLOCLOCALITE,", lieulocaliteFormate); |
} |
|
if(lieuDit != null && !lieuDit.contains("000null") && !lieuDit.trim().equals("")) { |
lieuDitFormate += lieuDit; |
lieuModele = lieuModele.replaceAll("LIEUDIT", lieuDitFormate); |
} else { |
lieuModele = lieuModele.replaceAll("LIEUDIT,", lieuDitFormate); |
} |
|
if(station != null && !station.contains("000null") && !station.trim().equals("")) { |
stationFormatee += station; |
lieuModele = lieuModele.replaceAll("STATION", stationFormatee); |
} else { |
lieuModele = lieuModele.replaceAll("STATION", stationFormatee); |
} |
|
lieuModele = lieuModele.trim(); |
lieuModele = lieuModele.replaceAll(",$",""); |
lieuModele = lieuModele.replaceAll(",^$",", "); |
|
return lieuModele; |
} |
|
public static String obtenirIdLocAPartirChaineLocalite(String localite) { |
|
String idLoc = ""; |
String[] depCom = localite.split(" "); |
if(depCom.length > 1) { |
idLoc = depCom[1].replace('(', ' '); |
} else { |
idLoc = ""; |
} |
|
idLoc = idLoc.replace(')', ' '); |
idLoc = idLoc.trim(); |
idLoc = idLoc.replace('\\',' '); |
idLoc = idLoc.trim(); |
|
return idLoc; |
} |
|
public static String formaterDepartement(String depAFormater) { |
String dep = ""; |
try |
{ |
int nDep = Integer.parseInt(depAFormater); |
if(nDep > 0 && nDep < 110) { |
dep = depAFormater ; |
} |
|
if(depAFormater.length() == 4) { |
dep = "0"+depAFormater; |
} |
|
dep = depAFormater.substring(0,2); |
} |
catch(NumberFormatException e) |
{ |
// rien à faire |
} |
|
return dep; |
} |
|
public static String supprimerChaineIdLocalite(String chaineLocaliteComplete) { |
return chaineLocaliteComplete.replaceAll(" \\([a-zA-Z0-9]*\\)", "").trim(); |
} |
|
public static String convertirChaineZoneGeoVersDepartement(String chaineZoneGeo) { |
return (!chaineZoneGeo.equals("000null") && !chaineZoneGeo.equals("") && chaineZoneGeo.replaceAll("INSEE-C:", "").length() >= 2) ? |
chaineZoneGeo.replaceAll("INSEE-C:", "").substring(0, 2) : |
chaineZoneGeo; |
} |
|
public static String convertirChaineZoneGeoVersCodeInsee(String chaineZoneGeo) { |
return (!chaineZoneGeo.equals("000null") && !chaineZoneGeo.equals("")) ? chaineZoneGeo.replaceAll("INSEE-C:", ""): chaineZoneGeo; |
} |
|
/*** |
* Fusionne les éléments d'un tableau en une chaîne |
* @param delim : la chaîne de séparation |
* @param args : la tableau |
* @return la chaîne fusionnée |
*/ |
public static String implode(String delim, String[] args){ |
StringBuffer sb = new StringBuffer(); |
|
int lgArgs = args.length; |
|
for(int i = 0; i < lgArgs; i++){ |
if (i > 0) { |
sb.append(delim); |
} |
|
sb.append(args[i]); |
} |
|
return sb.toString(); |
} |
|
public static boolean filtreValide(String[] filtre) { |
|
return (filtre.length == 2 && |
filtre[0] != null && |
!filtre[0].equals("") && |
filtre[1] != null && |
!filtre[1].equals("")); |
} |
|
public static String renvoyerMois(int numMois) { |
|
if(numMois >= 1 && numMois <= 12) { |
return Msg.get("mois-"+numMois); |
} else { |
return Msg.get("mois-inconnu") ; |
} |
} |
|
public static String remplacerSautsDeligneMalEncodes(String chaineAvecSautsDeLignesMalEncodes) { |
|
String chaineAvecSautsDeLignesBienEncodes = chaineAvecSautsDeLignesMalEncodes.replace('\\','%'); |
chaineAvecSautsDeLignesBienEncodes = chaineAvecSautsDeLignesBienEncodes.replaceAll("%n","%"); |
chaineAvecSautsDeLignesBienEncodes = chaineAvecSautsDeLignesBienEncodes.replace('%','\n'); |
|
return chaineAvecSautsDeLignesBienEncodes; |
} |
|
public static boolean verifierDateFormatCel(String dateAVerifier) { |
|
String dateRemplacee = remplacerSeparateursDateFormatCel(dateAVerifier); |
String[] tabDate = dateRemplacee.split("/"); |
|
boolean retour = false; |
|
if(tabDate.length == 3) { |
//TODO: faire un parsing de date qui fonctionne mieux car |
// on peut saisir un 31 novembre par exemple |
// mais l'api date de java est mal gérée par gwt |
try { |
int jour = Integer.parseInt(tabDate[0]); |
int mois = Integer.parseInt(tabDate[1]); |
int annee = Integer.parseInt(tabDate[2]); |
|
if(jour <= 31 && mois <= 12 && tabDate[2].length() == 4) { |
retour = true; |
} |
} catch (Exception e) { |
|
} |
} |
|
return retour; |
} |
|
public static String remplacerSeparateursDateFormatCel(String date) { |
|
String dateRemplacee = date.replaceAll("-", "/"); |
|
return dateRemplacee; |
} |
|
public static boolean estZero(String s) { |
boolean estZero = false; |
try { |
Double dou = Double.parseDouble(s); |
estZero = (dou == 0); |
} catch(NumberFormatException e) { |
|
} |
return estZero; |
} |
|
public static boolean estUnNombre(String s) { |
//http://stackoverflow.com/questions/1102891/how-to-check-if-a-string-is-a-numeric-type-in-java |
try { |
double d = Double.parseDouble(s); |
} catch(NumberFormatException nfe) { |
return false; |
} |
return true; |
} |
|
public static boolean estLaCorse(String s) { |
// Les générations futures d'informaticiens me jugeront |
// (et éventuellement géreront mieux le cas de la Corse que je ne l'ai fait) |
return s.toUpperCase().equals("2A") || s.toUpperCase().equals("2B"); |
} |
|
public static boolean estUnDepartement(String s) { |
return estUnNombre(s) || estLaCorse(s); |
} |
|
public static String formaterNombre(String s) { |
s = s.indexOf(".") < 0 ? s : s.replaceAll("0*$", "").replaceAll("\\.$", ""); |
return s; |
} |
|
// Prend un nombre décimal avec le spéparateur spécifié et le tronque à n décimales |
public static String tronquerNombrePourAffichage(String nombre, int decimales, char separateur) { |
String retour = nombre; |
int posSep = nombre.indexOf(separateur); |
if (posSep >= 0) { |
int taille = posSep + decimales + 1; |
if (nombre.length() < taille) { |
taille = nombre.length(); |
} |
retour = nombre.substring(0, taille); |
} |
return retour; |
} |
|
public static String tronquerNombrePourAffichage(String nombre, int decimales) { |
return tronquerNombrePourAffichage(nombre, decimales, '.'); |
} |
|
// Adapté de http://www.programcreek.com/2011/03/java-method-for-spliting-a-camelcase-string/ |
public static String formaterCleChampsEtenduPourAffichage(String s) { |
char[] cArray = s.toCharArray(); |
|
Vector<Integer> al = new Vector<Integer>(); |
al.add(0); |
|
// get all upper case letter index positions |
for (int i = 1; i < cArray.length; i++) { |
char c = cArray[i]; |
//add more interested index beyond upper case letter |
if (c >= 65 && c <= 90) { |
al.add(i); |
} |
} |
|
Vector<String> strl = new Vector<String>(); |
|
// this handles the all lower letter case |
if (al.size() == 1) { |
strl.add(s); |
return depilerChaineListee(strl, " "); |
} |
|
|
int prev = 0; |
int curr = 0; |
int begin = 0; |
for (int k = 1; k < al.size(); k++) { |
|
curr = al.get(k); |
|
if(curr == s.length() - 1){ |
|
} |
|
if (curr == prev + 1 && curr != s.length() - 1) { |
prev = curr; |
} else if(curr == prev + 1 && curr == s.length() - 1){ |
strl.add(s.substring(begin, curr+1)); |
}else { |
|
strl.add(s.substring(prev, curr)); |
prev = curr; |
begin = curr; |
if (k == al.size() - 1) { |
strl.add(s.substring(curr, s.length())); |
} |
} |
} |
|
return depilerChaineListee(strl, " "); |
} |
|
private static String depilerChaineListee(Vector<String> strl, String separateur) { |
String s = ""; |
for(int i = 0; i < strl.size(); i++) { |
s += strl.get(i); |
if(i != strl.size() - 1) { |
s += separateur; |
} |
} |
return s; |
} |
|
public static Map<String, ChampEtendu> trierListeChampsEtendus(Map<String, ChampEtendu> listeChampsEtendus) { |
List<String> tmp = new ArrayList<String>(listeChampsEtendus.keySet()); |
Collections.sort(tmp, new Comparator<String>() { |
|
@Override |
public int compare(String arg0, String arg1) { |
return arg0.compareTo(arg1); |
} |
|
}); |
return listeChampsEtendus; |
} |
|
/** |
* Solution issue de stackoverflow : |
* http://stackoverflow.com/questions/1143951/what-is-the-simplest-way-to-convert-a-java-string-from-all-caps-words-separated |
*/ |
public static String convertirEnChaMot(String s) { |
s = s.replaceAll("_", " "); |
s = s.replaceAll("-", " "); |
String[] parties = s.split(" "); |
String chaineChaMot = ""; |
for (String partie : parties){ |
chaineChaMot = chaineChaMot + convertirMotEnChaMot(partie); |
} |
return chaineChaMot; |
} |
|
protected static String convertirMotEnChaMot(String s) { |
// MiaOu |
return s.substring(0, 1).toUpperCase() + |
s.substring(1).toLowerCase(); |
} |
|
public static void curseurAttente() { |
RootPanel.getBodyElement().getStyle().setProperty("cursor", "wait"); |
} |
|
public static void curseurParDefaut() { |
RootPanel.getBodyElement().getStyle().setProperty("cursor", "default"); |
} |
|
public static Map<String, String> parserRetourReferentielPerso(Response response) { |
final Map<String, String> referentielData = new HashMap<String, String>(); |
final JSONValue responseValue = JSONParser.parse(response.getText()); |
|
JSONArray reponse = null; |
|
// si c'est un tableau |
if ((reponse = responseValue.isArray()) != null) { |
|
JSONString elementsRef; |
final int taillemax = reponse.size(); |
|
for (int i = 0; i < taillemax; i++) { |
if ((elementsRef = reponse.get(i).isString()) != null) { |
|
String valeur = elementsRef.stringValue(); |
referentielData.put(i+"", valeur); |
|
} |
} |
} |
return referentielData; |
} |
|
public static Map<String, ReferentielNom> parserRetourReferentielNomIndexeParNom(Response response) { |
|
final Map<String, ReferentielNom> referentielNomData ; |
final JSONValue responseValue = JSONParser.parse(response.getText()); |
JSONArray reponse=null; |
|
// si c'est un tableau |
if ((reponse=responseValue.isArray()) != null) { |
|
JSONArray noms; |
final int taillemax = reponse.size(); |
|
referentielNomData = new HashMap<String, ReferentielNom>(taillemax); |
for (int i = 0; i < taillemax; i++) { |
if ((noms=reponse.get(i).isArray()) != null) { |
String nom = ((JSONString) noms.get(0)).stringValue(); |
String numeroNom = ((JSONString) noms.get(1)).stringValue(); |
String statut= ((JSONString) noms.get(2)).stringValue(); |
ReferentielNom nomScientifique = new ReferentielNom(nom, numeroNom, statut); |
// FIXME : et si le numero de nom n'est pas unique ? (cas de multirefrentiel....) |
referentielNomData.put(nomScientifique.getNom(),nomScientifique); |
} |
} |
} else { |
referentielNomData = new HashMap<String, ReferentielNom>(0); |
} |
return referentielNomData; |
} |
|
public static Map<String, String> convertirListeReferentielNomVersMap(Map<String, ReferentielNom> referentielNom) { |
Map<String, String> nomMap = new HashMap<String, String>(); |
for (Iterator<String> it = referentielNom.keySet().iterator(); it.hasNext();) { |
String cle = it.next(); |
nomMap.put(cle, referentielNom.get(cle).getNom()); |
} |
return nomMap; |
} |
|
public static Map<String, ReferentielLocalite> parserRetourReferentielLocaliteIndexeParNom(Response response) { |
|
final Map<String, ReferentielLocalite> referentielLocaliteData; |
final JSONValue responseValue = JSONParser.parse(response.getText()); |
JSONArray reponse = null; |
|
// si c'est un tableau |
if ((reponse = responseValue.isArray()) != null) { |
|
JSONArray localites; |
final int taillemax = reponse.size(); |
|
referentielLocaliteData = new HashMap<String, ReferentielLocalite>(taillemax); |
|
for (int i = 0; i < taillemax; i++) { |
if ((localites = reponse.get(i).isArray()) != null) { |
String localite = ((JSONString) localites.get(0)).stringValue(); |
String codeLocalite = ((JSONString) localites.get(1)).stringValue(); |
ReferentielLocalite com = new ReferentielLocalite(localite, codeLocalite); |
referentielLocaliteData.put(com.getLocalite(), com); |
} |
} |
} else { |
referentielLocaliteData = new HashMap<String, ReferentielLocalite>(0); |
} |
return referentielLocaliteData; |
} |
|
public static Map<String, String> convertirListeReferentielLocaliteVersMap(Map<String, ReferentielLocalite> referentielLocalite) { |
Map<String, String> locMap = new HashMap<String, String>(); |
for (Iterator<String> it = referentielLocalite.keySet().iterator(); it.hasNext();) { |
String cle = it.next(); |
locMap.put(cle, referentielLocalite.get(cle).getLocalite()); |
} |
return locMap; |
} |
|
public static Map<String, String> parserRetourImportObs(String json) { |
final JSONValue responseValue = JSONParser.parse(json); |
JSONObject reponse = null; |
|
Map<String, String> retourImport = new HashMap<String,String>(); |
// si c'est un objet |
if ((reponse = responseValue.isObject()) != null) { |
Iterator<String> it = reponse.keySet().iterator(); |
|
while(it.hasNext()) { |
String cle = it.next(); |
String valeur = reponse.get(cle).isString().stringValue(); |
retourImport.put(cle, valeur); |
} |
} |
|
return retourImport; |
} |
|
public static void envoyerRequeteStatsUpload(final Callback<String, String> cb) { |
RequestBuilderWithCredentials rb = new RequestBuilderWithCredentials(RequestBuilderWithCredentials.GET,Configuration.getServiceBaseUrl() |
+"/ImportXLS") ; |
try { |
rb.sendRequest(null, new RequestCallback() { |
|
@Override |
public void onError(Request request, Throwable exception) { |
// TODO Auto-generated method stub |
} |
|
@Override |
public void onResponseReceived(Request request, |
Response response) { |
cb.onSuccess(response.getText()); |
} |
}) ; |
|
} catch (RequestException e) { |
// TODO Auto-generated catch block |
e.printStackTrace(); |
} |
} |
|
public static native void LogVersFirebug(Object o) /*-{ |
if (!!($wnd.console && $wnd.console.log)) { |
console.log(o); |
} |
}-*/; |
|
public static String buildStackTrace(Throwable t, String log) { |
if (t != null) { |
log += t.getClass().toString(); |
log += t.getMessage(); |
// |
StackTraceElement[] stackTrace = t.getStackTrace(); |
if (stackTrace != null) { |
StringBuffer trace = new StringBuffer(); |
|
for (int i = 0; i < stackTrace.length; i++) { |
trace.append(stackTrace[i].getClassName() + "." + stackTrace[i].getMethodName() + "(" |
+ stackTrace[i].getFileName() + ":" + stackTrace[i].getLineNumber()); |
} |
|
log += trace.toString(); |
} |
// |
Throwable cause = t.getCause(); |
if (cause != null && cause != t) { |
log += buildStackTrace(cause, "CausedBy:\n"); |
} |
} |
return log; |
} |
|
public static String obtenirCodeLangueSysteme() { |
String langueSystemeBrute = obtenirLangueSysteme(); |
// le navigateur peut éventuellement renvoyer une chaine de la forme |
// en-us ou fr-fr par exemple |
String[] lngTab = langueSystemeBrute.split("-"); |
return (lngTab.length > 0) ? lngTab[0] : null; |
} |
|
public static native String obtenirLangueSysteme() /*-{ |
lang = ""; |
if (!!($wnd.navigator && $wnd.navigator.language)) { |
lang = window.navigator.language; |
} |
return lang; |
}-*/; |
|
public static native String utf8ToB64(String str) /*-{ |
return window.btoa(unescape(encodeURIComponent( str ))); |
}-*/; |
|
public static native String b64ToUtf8(String str) /*-{ |
return decodeURIComponent(escape(window.atob( str ))); |
}-*/; |
} |