Subversion Repositories eFlore/Applications.cel

Rev

Rev 2626 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
734 aurelien 1
package org.tela_botanica.client.util;
2 aperonnet 2
 
2558 aurelien 3
import java.text.NumberFormat;
4
import java.text.ParsePosition;
2392 aurelien 5
import java.util.ArrayList;
6
import java.util.Collections;
7
import java.util.Comparator;
1542 aurelien 8
import java.util.HashMap;
2606 aurelien 9
import java.util.Iterator;
2392 aurelien 10
import java.util.List;
1542 aurelien 11
import java.util.Map;
2392 aurelien 12
import java.util.Vector;
1542 aurelien 13
 
2626 aurelien 14
import org.tela_botanica.client.i18n.Msg;
1572 aurelien 15
import org.tela_botanica.client.modeles.objets.ChampEtendu;
989 aurelien 16
import org.tela_botanica.client.modeles.objets.Observation;
2606 aurelien 17
import org.tela_botanica.client.modeles.objets.ReferentielLocalite;
18
import org.tela_botanica.client.modeles.objets.ReferentielNom;
642 aurelien 19
 
2553 mathias 20
import com.google.gwt.dom.client.Element;
2602 aurelien 21
import com.google.gwt.http.client.Response;
1572 aurelien 22
import com.google.gwt.json.client.JSONArray;
1282 aurelien 23
import com.google.gwt.json.client.JSONObject;
2602 aurelien 24
import com.google.gwt.json.client.JSONParser;
1282 aurelien 25
import com.google.gwt.json.client.JSONString;
2602 aurelien 26
import com.google.gwt.json.client.JSONValue;
2553 mathias 27
import com.google.gwt.user.client.DOM;
28
import com.google.gwt.user.client.ui.RootPanel;
1282 aurelien 29
 
2 aperonnet 30
public class Util {
31
 
32
	public Util() {
33
	}
642 aurelien 34
 
1282 aurelien 35
	public static String getValeurJsonOuVide(JSONObject jo, String index) {
36
		return jsonNonNull(jo, index) ? ((JSONString)jo.get(index)).stringValue() : "";
37
	}
38
 
1572 aurelien 39
	public static Map<String, ChampEtendu> getMapValeursOuVide(JSONObject jo, String index) {
40
		Map<String, ChampEtendu> mapValeurs = new HashMap<String, ChampEtendu>();
41
		if(jo.get(index) != null && jo.get(index).isArray() != null) {
42
			JSONArray tabJo = jo.get(index).isArray();
43
			for (int i = 0; i < tabJo.size(); i++) {
44
				JSONObject champJson = tabJo.get(i).isObject();
45
				String cle = champJson.get("cle").isString().stringValue();
2392 aurelien 46
				String label = cle;
1572 aurelien 47
				String valeur = champJson.get("valeur").isString().stringValue();
48
				ChampEtendu champ = new ChampEtendu(cle, label, valeur);
49
				mapValeurs.put(cle, champ);
1542 aurelien 50
			}
1572 aurelien 51
 
1542 aurelien 52
		}
53
		return mapValeurs;
54
	}
55
 
1572 aurelien 56
	public static String convertirChampsEtendusEnChaineRequete(Map<String, ChampEtendu> map) {
57
		String json = "";
58
	    if (map != null && !map.isEmpty()) {
59
	    	JSONArray jsonArr = new JSONArray();
60
	    	int i = 0;
61
	        for (Map.Entry<String, ChampEtendu> entry: map.entrySet()) {
62
	        	jsonArr.set(i, convertirChampEtenduEnJson(entry.getValue()));
63
	        	i++;
64
	        }
65
	        json = jsonArr.toString();
66
	    }
67
	    return json;
1549 aurelien 68
	}
69
 
1572 aurelien 70
	public static JSONObject convertirChampEtenduEnJson(ChampEtendu champEtendu) {
71
		JSONObject jsonObj = new JSONObject();
72
		jsonObj.put("cle", new JSONString(champEtendu.getCle()));
73
		jsonObj.put("label", new JSONString(champEtendu.getLabel()));
74
		jsonObj.put("valeur", new JSONString(champEtendu.getValeur()));
75
        return jsonObj;
76
	}
77
 
1282 aurelien 78
	public static boolean jsonNonNull(JSONObject jo, String index) {
79
		return (jo != null &&
80
				jo.get(index) != null &&
81
				jo.get(index).isNull() == null
82
			   );
83
	}
84
 
642 aurelien 85
	public static String formaterLieu(Observation obs, String modeleLieu) {
86
 
87
		String lieuModele = modeleLieu;
88
 
2568 aurelien 89
		String localite = obs.getLocalite();
642 aurelien 90
		String lieuDit = obs.getLieudit();
91
		String station = obs.getStation();
92
 
2568 aurelien 93
		String lieulocaliteFormate = "";
642 aurelien 94
		String lieuDitFormate = "";
95
		String stationFormatee = "";
96
 
2568 aurelien 97
		if(localite != null && !localite.contains("000null") && !localite.trim().equals("")) {
642 aurelien 98
			String	idLoc =obs.getIdentifiantLocalite().replaceAll(" ","/");
99
			if(idLoc != null && !idLoc.contains("000null") && !idLoc.trim().equals("")) {
100
 
101
				idLoc = idLoc.replaceAll("%","");
102
				idLoc = idLoc.replaceAll("\"","");
103
				idLoc = idLoc.replace('\\',' ');
104
				idLoc = idLoc.trim();
1332 aurelien 105
				if(idLoc.length() > 2) {
106
					idLoc = idLoc.substring(0,2);
107
				}
2568 aurelien 108
				lieulocaliteFormate += idLoc+" - ";
642 aurelien 109
			}
2568 aurelien 110
			lieulocaliteFormate += localite;
111
			lieuModele = lieuModele.replaceAll("IDLOCLOCALITE", lieulocaliteFormate);
642 aurelien 112
		} else {
113
 
2568 aurelien 114
			lieuModele = lieuModele.replaceAll("IDLOCLOCALITE,", lieulocaliteFormate);
642 aurelien 115
		}
116
 
117
		if(lieuDit != null && !lieuDit.contains("000null") && !lieuDit.trim().equals("")) {
118
			lieuDitFormate += lieuDit;
119
			lieuModele = lieuModele.replaceAll("LIEUDIT", lieuDitFormate);
120
		} else {
121
			lieuModele = lieuModele.replaceAll("LIEUDIT,", lieuDitFormate);
122
		}
123
 
124
		if(station != null && !station.contains("000null") && !station.trim().equals("")) {
125
			stationFormatee += station;
126
			lieuModele = lieuModele.replaceAll("STATION", stationFormatee);
127
		} else {
128
			lieuModele = lieuModele.replaceAll("STATION", stationFormatee);
129
		}
130
 
131
		lieuModele = lieuModele.trim();
132
		lieuModele = lieuModele.replaceAll(",$","");
133
		lieuModele = lieuModele.replaceAll(",^$",", ");
134
 
135
		return lieuModele;
136
	}
137
 
2568 aurelien 138
	public static String obtenirIdLocAPartirChaineLocalite(String localite) {
1542 aurelien 139
 
2558 aurelien 140
		String idLoc = "";
2568 aurelien 141
		String[] depCom = localite.split(" ");
2558 aurelien 142
		if(depCom.length > 1) {
143
			idLoc = depCom[1].replace('(', ' ');
1542 aurelien 144
		} else {
2558 aurelien 145
			idLoc = "";
1542 aurelien 146
		}
147
 
2558 aurelien 148
		idLoc = idLoc.replace(')', ' ');
149
		idLoc = idLoc.trim();
150
		idLoc = idLoc.replace('\\',' ');
151
		idLoc = idLoc.trim();
1542 aurelien 152
 
2558 aurelien 153
		return idLoc;
154
	}
155
 
156
	public static String formaterDepartement(String depAFormater) {
157
		String dep = "";
1542 aurelien 158
		try
159
		{
2558 aurelien 160
			int nDep = Integer.parseInt(depAFormater);
1542 aurelien 161
			if(nDep > 0 && nDep < 110) {
2558 aurelien 162
				dep = depAFormater ;
1542 aurelien 163
			}
164
 
2558 aurelien 165
			if(depAFormater.length() == 4) {
166
				dep = "0"+depAFormater;
1542 aurelien 167
			}
168
 
2558 aurelien 169
			dep = depAFormater.substring(0,2);
1542 aurelien 170
		}
171
		catch(NumberFormatException e)
172
		{
2558 aurelien 173
			// rien à faire
1542 aurelien 174
		}
175
 
2558 aurelien 176
		return dep;
1542 aurelien 177
	}
178
 
2558 aurelien 179
	public static String supprimerChaineIdLocalite(String chaineLocaliteComplete) {
180
		return chaineLocaliteComplete.replaceAll(" \\([a-zA-Z0-9]*\\)", "");
642 aurelien 181
	}
673 aurelien 182
 
962 aurelien 183
	public static String convertirChaineZoneGeoVersDepartement(String chaineZoneGeo) {
1672 aurelien 184
		return (!chaineZoneGeo.equals("000null") && !chaineZoneGeo.equals("") && chaineZoneGeo.replaceAll("INSEE-C:", "").length() >= 2) ?
185
						chaineZoneGeo.replaceAll("INSEE-C:", "").substring(0, 2) :
186
						chaineZoneGeo;
962 aurelien 187
	}
188
 
189
	public static String convertirChaineZoneGeoVersCodeInsee(String chaineZoneGeo) {
190
		return (!chaineZoneGeo.equals("000null") && !chaineZoneGeo.equals("")) ? chaineZoneGeo.replaceAll("INSEE-C:", ""): chaineZoneGeo;
191
	}
192
 
673 aurelien 193
	/***
194
	 * Fusionne les éléments d'un tableau en une chaîne
195
	 * @param delim : la chaîne de séparation
196
	 * @param args : la tableau
197
	 * @return la chaîne fusionnée
198
	 */
199
	public static String implode(String delim, String[] args){
200
		StringBuffer sb = new StringBuffer();
201
 
202
		int lgArgs = args.length;
203
 
204
		for(int i = 0; i < lgArgs; i++){
205
			if (i > 0) {
206
				sb.append(delim);
207
			}
208
 
209
			sb.append(args[i]);
210
		}
211
 
212
		return sb.toString();
213
	}
214
 
215
	public static boolean filtreValide(String[] filtre) {
216
 
217
		return (filtre.length == 2 &&
218
		filtre[0] != null &&
219
		!filtre[0].equals("") &&
220
		filtre[1] != null &&
221
		!filtre[1].equals(""));
222
	}
223
 
224
	public static String renvoyerMois(int numMois) {
225
 
2626 aurelien 226
		if(numMois >= 1 && numMois <= 12) {
227
			return Msg.get("mois-"+numMois);
228
		} else {
229
			return Msg.get("mois-inconnu") ;
673 aurelien 230
		}
231
	}
232
 
233
	public static String remplacerSautsDeligneMalEncodes(String chaineAvecSautsDeLignesMalEncodes) {
234
 
235
		String chaineAvecSautsDeLignesBienEncodes = chaineAvecSautsDeLignesMalEncodes.replace('\\','%');
236
		chaineAvecSautsDeLignesBienEncodes = chaineAvecSautsDeLignesBienEncodes.replaceAll("%n","%");
237
		chaineAvecSautsDeLignesBienEncodes = chaineAvecSautsDeLignesBienEncodes.replace('%','\n');
238
 
239
		return chaineAvecSautsDeLignesBienEncodes;
240
	}
241
 
242
	public static boolean verifierDateFormatCel(String dateAVerifier) {
243
 
244
		String dateRemplacee = remplacerSeparateursDateFormatCel(dateAVerifier);
245
		String[] tabDate = dateRemplacee.split("/");
246
 
247
		boolean retour = false;
248
 
249
		if(tabDate.length == 3) {
1282 aurelien 250
			//TODO: faire un parsing de date qui fonctionne mieux car
251
			// on peut saisir un 31 novembre par exemple
252
			// mais l'api date de java est mal gérée par gwt
673 aurelien 253
			try {
254
				int jour = Integer.parseInt(tabDate[0]);
255
				int mois = Integer.parseInt(tabDate[1]);
256
				int annee = Integer.parseInt(tabDate[2]);
257
 
1010 aurelien 258
				if(jour <= 31 && mois <= 12 && tabDate[2].length() == 4) {
673 aurelien 259
					retour = true;
260
				}
261
			} catch (Exception e) {
262
 
263
			}
264
		}
265
 
266
		return retour;
267
	}
268
 
269
	public static String remplacerSeparateursDateFormatCel(String date) {
270
 
271
		String dateRemplacee = date.replaceAll("-", "/");
272
 
273
	    return dateRemplacee;
274
	}
1572 aurelien 275
 
276
	public static boolean estZero(String s) {
277
		boolean estZero = false;
278
	    try {
279
	    	Double dou = Double.parseDouble(s);
280
	    	estZero = (dou == 0);
281
	    } catch(NumberFormatException e) {
282
 
283
	    }
284
	    return estZero;
285
	}
286
 
2558 aurelien 287
	public static boolean estUnNombre(String s) {
288
		//http://stackoverflow.com/questions/1102891/how-to-check-if-a-string-is-a-numeric-type-in-java
289
		try {
290
			double d = Double.parseDouble(s);
291
		} catch(NumberFormatException nfe) {
292
			return false;
293
		}
294
		return true;
295
	}
296
 
1572 aurelien 297
	public static String formaterNombre(String s) {
298
		s = s.indexOf(".") < 0 ? s : s.replaceAll("0*$", "").replaceAll("\\.$", "");
299
		return s;
300
	}
2276 mathias 301
 
302
	// Prend un nombre décimal avec le spéparateur spécifié et le tronque à n décimales
303
	public static String tronquerNombrePourAffichage(String nombre, int decimales, char separateur) {
304
		String retour = nombre;
305
		int posSep = nombre.indexOf(separateur);
306
		if (posSep >= 0) {
307
			int taille = posSep + decimales + 1;
308
			if (nombre.length() < taille) {
309
				taille = nombre.length();
310
			}
311
			retour = nombre.substring(0, taille);
312
		}
313
		return retour;
314
	}
315
 
316
	public static String tronquerNombrePourAffichage(String nombre, int decimales) {
317
		return tronquerNombrePourAffichage(nombre, decimales, '.');
318
	}
2392 aurelien 319
 
320
	// Adapté de http://www.programcreek.com/2011/03/java-method-for-spliting-a-camelcase-string/
321
	public static String formaterCleChampsEtenduPourAffichage(String s) {
322
		char[] cArray = s.toCharArray();
323
 
324
		Vector<Integer> al = new Vector<Integer>();
325
		al.add(0);
326
 
327
		// get all upper case letter index positions
328
		for (int i = 1; i < cArray.length; i++) {
329
			char c = cArray[i];
330
			//add more interested index beyond upper case letter
331
			if (c >= 65 && c <= 90) {
332
				al.add(i);
333
			}
334
		}
335
 
336
		Vector<String> strl = new Vector<String>();
337
 
338
		// this handles the all lower letter case
339
		if (al.size() == 1) {
340
			strl.add(s);
341
			return depilerChaineListee(strl, " ");
342
		}
343
 
344
 
345
		int prev = 0;
346
		int curr = 0;
347
		int begin = 0;
348
		for (int k = 1; k < al.size(); k++) {
349
 
350
			curr = al.get(k);
351
 
352
			if(curr == s.length() - 1){
353
 
354
			}
355
 
356
			if (curr == prev + 1 && curr != s.length() - 1) {
357
				prev = curr;
358
			} else if(curr == prev + 1 &&  curr == s.length() - 1){
359
				strl.add(s.substring(begin, curr+1));
360
			}else {
361
 
362
				strl.add(s.substring(prev, curr));
363
				prev = curr;
364
				begin = curr;
365
				if (k == al.size() - 1) {
366
					strl.add(s.substring(curr, s.length()));
367
				}
368
			}
369
		}
370
 
371
		return depilerChaineListee(strl, " ");
372
	}
373
 
374
	private static String depilerChaineListee(Vector<String> strl, String separateur) {
375
		String s = "";
376
		for(int i = 0; i < strl.size(); i++) {
377
			s += strl.get(i);
378
			if(i != strl.size() - 1) {
379
				s += separateur;
380
			}
381
		}
382
		return s;
383
	}
384
 
385
	public static Map<String, ChampEtendu> trierListeChampsEtendus(Map<String, ChampEtendu> listeChampsEtendus) {
386
		List<String> tmp = new ArrayList<String>(listeChampsEtendus.keySet());
387
		Collections.sort(tmp, new Comparator<String>() {
388
 
389
		    @Override
390
		    public int compare(String arg0, String arg1) {
391
		        return arg0.compareTo(arg1);
392
		    }
393
 
394
		});
395
		return listeChampsEtendus;
396
	}
2401 aurelien 397
 
398
	/**
399
	 * Solution issue de stackoverflow :
400
	 * http://stackoverflow.com/questions/1143951/what-is-the-simplest-way-to-convert-a-java-string-from-all-caps-words-separated
401
	 */
402
	public static String convertirEnChaMot(String s) {
403
		s = s.replaceAll("_", " ");
404
		s = s.replaceAll("-", " ");
405
		String[] parties = s.split(" ");
406
		String chaineChaMot = "";
407
		for (String partie : parties){
408
			chaineChaMot = chaineChaMot + convertirMotEnChaMot(partie);
409
		}
410
		return chaineChaMot;
411
	}
412
 
413
	protected static String convertirMotEnChaMot(String s) {
414
		return s.substring(0, 1).toUpperCase() +
415
	               s.substring(1).toLowerCase();
416
	}
2553 mathias 417
 
418
	public static void curseurAttente() {
419
	    RootPanel.getBodyElement().getStyle().setProperty("cursor", "wait");
420
	}
421
 
422
	public static void curseurParDefaut() {
423
		RootPanel.getBodyElement().getStyle().setProperty("cursor", "default");
424
	}
2602 aurelien 425
 
426
	public static Map<String, String> parserRetourReferentielPerso(Response response) {
427
		final Map<String, String> referentielData = new HashMap<String, String>();
428
		final JSONValue responseValue = JSONParser.parse(response.getText());
429
 
430
		JSONArray reponse = null;
431
 
432
		// si c'est un tableau
433
		if ((reponse = responseValue.isArray()) != null) {
434
 
435
			JSONString elementsRef;
436
			final int taillemax = reponse.size();
437
 
438
			for (int i = 0; i < taillemax; i++) {
439
				if ((elementsRef = reponse.get(i).isString()) != null) {
440
 
441
					String valeur = elementsRef.stringValue();
442
					referentielData.put(i+"", valeur);
443
 
444
				}
445
			}
446
		}
447
		return referentielData;
448
	}
2606 aurelien 449
 
450
	public static Map<String, ReferentielNom> parserRetourReferentielNomIndexeParNom(Response response) {
451
 
452
		final Map<String, ReferentielNom> referentielNomData ;
453
		final JSONValue responseValue = JSONParser.parse(response.getText());
454
		JSONArray reponse=null;
455
 
456
		// si c'est un tableau
457
		if ((reponse=responseValue.isArray()) != null) {
458
 
459
			JSONArray noms;
460
			final int taillemax = reponse.size();
461
 
462
			referentielNomData = new HashMap<String, ReferentielNom>(taillemax);
463
			for (int i = 0; i < taillemax; i++) {
464
				if ((noms=reponse.get(i).isArray()) != null) {
465
					String nom = ((JSONString) noms.get(0)).stringValue();
466
					String numeroNom = ((JSONString) noms.get(1)).stringValue();
467
					String statut= ((JSONString) noms.get(2)).stringValue();
468
					ReferentielNom nomScientifique = new ReferentielNom(nom, numeroNom, statut);
469
					// FIXME : et si le numero de nom n'est pas unique ? (cas de multirefrentiel....)
470
					referentielNomData.put(nomScientifique.getNom(),nomScientifique);
471
				}
472
			}
473
		} else {
474
			referentielNomData = new HashMap<String, ReferentielNom>(0);
475
		}
476
		return referentielNomData;
477
	}
478
 
479
	public static Map<String, String> convertirListeReferentielNomVersMap(Map<String, ReferentielNom> referentielNom) {
480
		Map<String, String> nomMap = new HashMap<String, String>();
481
		for (Iterator<String> it  = referentielNom.keySet().iterator(); it.hasNext();) {
482
			String cle = it.next();
483
			nomMap.put(cle, referentielNom.get(cle).getNom());
484
		}
485
		return nomMap;
486
	}
487
 
488
	public static Map<String, ReferentielLocalite> parserRetourReferentielLocaliteIndexeParNom(Response response) {
489
 
490
		final Map<String, ReferentielLocalite> referentielLocaliteData;
491
		final JSONValue responseValue = JSONParser.parse(response.getText());
492
		JSONArray reponse = null;
493
 
494
		// si c'est un tableau
495
		if ((reponse = responseValue.isArray()) != null) {
496
 
497
			JSONArray localites;
498
			final int taillemax = reponse.size();
499
 
500
			referentielLocaliteData = new HashMap<String, ReferentielLocalite>(taillemax);
501
 
502
			for (int i = 0; i < taillemax; i++) {
503
				if ((localites = reponse.get(i).isArray()) != null) {
504
					String localite = ((JSONString) localites.get(0)).stringValue();
505
					String codeLocalite  = ((JSONString) localites.get(1)).stringValue();
506
					ReferentielLocalite com = new ReferentielLocalite(localite, codeLocalite);
507
					referentielLocaliteData.put(com.getLocalite() + com.getCodeLocalite(), com);
508
				}
509
			}
510
		} else {
511
			referentielLocaliteData = new HashMap<String, ReferentielLocalite>(0);
512
		}
513
		return referentielLocaliteData;
514
	}
515
 
516
	public static Map<String, String> convertirListeReferentielLocaliteVersMap(Map<String, ReferentielLocalite> referentielLocalite) {
517
		Map<String, String> locMap = new HashMap<String, String>();
518
		for (Iterator<String> it  = referentielLocalite.keySet().iterator(); it.hasNext();) {
519
			String cle = it.next();
520
			locMap.put(cle, referentielLocalite.get(cle).getLocalite());
521
		}
522
		return locMap;
523
	}
2650 aurelien 524
 
525
	public static native void  LogVersFirebug(Object o) /*-{
526
		if (!!($wnd.console && $wnd.console.log)) {
527
			console.log(o);
528
		}
529
	}-*/;
530
 
531
	public static String buildStackTrace(Throwable t, String log) {
532
	    if (t != null) {
533
		     log += t.getClass().toString();
534
		     log += t.getMessage();
535
		     //
536
		     StackTraceElement[] stackTrace = t.getStackTrace();
537
		     if (stackTrace != null) {
538
		    	 StringBuffer trace = new StringBuffer();
539
 
540
			     for (int i = 0; i < stackTrace.length; i++) {
541
			    	 trace.append(stackTrace[i].getClassName() + "." + stackTrace[i].getMethodName() + "("
542
			    			 + stackTrace[i].getFileName() + ":" + stackTrace[i].getLineNumber());
543
			     }
544
 
545
			     log += trace.toString();
546
		     }
547
		     //
548
		     Throwable cause = t.getCause();
549
		     if (cause != null && cause != t) {
550
		    	 log += buildStackTrace(cause, "CausedBy:\n");
551
		     }
552
	    }
553
	    return log;
554
	}
2 aperonnet 555
}