Subversion Repositories eFlore/Applications.cel

Rev

Rev 2693 | Go to most recent revision | Only display areas with differences | Ignore whitespace | Details | Blame | Last modification | View Log | RSS feed

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