Subversion Repositories eFlore/Applications.cel

Rev

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