Subversion Repositories eFlore/Applications.cel

Rev

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