Subversion Repositories eFlore/Applications.cel

Rev

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