Subversion Repositories eFlore/Applications.cel

Compare Revisions

Ignore whitespace Rev 2170 → Rev 2171

/tags/v2.2-faucille/src/org/tela_botanica/client/util/AutoCompletionRefComboBox.java
New file
0,0 → 1,170
package org.tela_botanica.client.util;
 
import java.util.Iterator;
 
import org.tela_botanica.client.interfaces.Rafraichissable;
import org.tela_botanica.client.modeles.objets.ListeReferentielPerso;
import org.tela_botanica.client.modeles.objets.ListeReferentielPerso.TypesReferentiels;
import org.tela_botanica.client.observation.ObservationMediateur;
 
import com.gwtext.client.core.EventCallback;
import com.gwtext.client.core.EventObject;
import com.gwtext.client.core.ListenerConfig;
import com.gwtext.client.data.ArrayReader;
import com.gwtext.client.data.FieldDef;
import com.gwtext.client.data.MemoryProxy;
import com.gwtext.client.data.Record;
import com.gwtext.client.data.RecordDef;
import com.gwtext.client.data.Store;
import com.gwtext.client.data.StringFieldDef;
import com.gwtext.client.widgets.form.ComboBox;
import com.gwtext.client.widgets.form.event.ComboBoxListenerAdapter;
 
public abstract class AutoCompletionRefComboBox extends ComboBox implements Rafraichissable {
// TODO: faire un enum
private final int KEY_ALT = 18;
private final int KEY_BACKSPACE = 8;
private final int KEY_CTRL = 17;
private final int KEY_DELETE = 46;
private final int KEY_DOWN = 40;
private final int KEY_END = 35;
private final int KEY_ENTER = 13;
private final int KEY_ESCAPE = 27;
private final int KEY_HOME = 36;
private final int KEY_LEFT = 37;
private final int KEY_PAGEDOWN = 34;
private final int KEY_PAGEUP = 33;
private final int KEY_RIGHT = 39;
private final int KEY_SHIFT = 16;
private final int KEY_TAB = 9;
private final int KEY_UP = 38;
private ObservationMediateur oMediateur = null;
private TypesReferentiels typeRef = null;
private boolean selectionValeur = false;
private boolean estModifie = false;
final String resultTplRefPerso = "<div class=\"search-item-ref\">{element_referentiel}</div>";
public AutoCompletionRefComboBox(String label, String nom, ObservationMediateur oMediateur, TypesReferentiels typeRef) {
// Accesskey pour debugging
super(label,nom);
this.oMediateur = oMediateur;
this.typeRef = typeRef;
 
setTpl(resultTplRefPerso);
setMode(ComboBox.REMOTE);
setItemSelector("div.search-item-ref");
setTypeAhead(true);
setLoadingText("Recherche...");
setHideTrigger(true);
ListenerConfig listenerConfigAutocompletion=new ListenerConfig();
listenerConfigAutocompletion.setDelay(200);
listenerConfigAutocompletion.setStopPropagation(false);
listenerConfigAutocompletion.setStopEvent(false);
addKeyPressListener(new EventCallback() {
 
@Override
public void execute(EventObject e) {
 
switch(e.getKey()) {
case KEY_ALT:
case KEY_CTRL:
case KEY_DOWN:
case KEY_END:
case KEY_ESCAPE:
case KEY_HOME:
case KEY_LEFT:
case KEY_PAGEDOWN:
case KEY_PAGEUP:
case KEY_RIGHT:
case KEY_SHIFT:
case KEY_TAB:
case KEY_UP:
break;
case KEY_ENTER:
if (selectionValeur) {
estModifie= true;
selectionValeur=false;
onModificationValeur();
}
else {
onValidationSaisie();
}
break;
default:
estModifie = true;
onModificationValeur();
obtenirReferentiel();
}
}
},listenerConfigAutocompletion);
// Listener completion
addListener(new ComboBoxListenerAdapter() {
@Override
public void onSelect(ComboBox comboBox, Record record, int index) {
setValue(record.getAsString("element_referentiel"));
selectionValeur=true;
collapse();
}
});
}
 
@Override
public void rafraichir(Object nouvelleDonnees,
boolean repandreRaffraichissement) {
ListeReferentielPerso referentielPerso = (ListeReferentielPerso)nouvelleDonnees;
int i = 0;
Object[][] refData = new Object[referentielPerso.size()][1];
for (Iterator<String> it = referentielPerso.keySet().iterator(); it.hasNext();)
{
String ref= referentielPerso.get(it.next());
refData[i][0]= ref;
i++;
}
FieldDef defStation = new StringFieldDef("element_referentiel");
FieldDef[] defTab = {defStation};
RecordDef rd = new RecordDef(defTab);
final MemoryProxy dataProxy = new MemoryProxy(refData);
final ArrayReader reader = new ArrayReader(rd);
Store store=new Store(dataProxy,reader);
setStore(store);
store.load();
}
private void obtenirReferentiel() {
String valeurChamp = getValue();
if(valeurChamp == null) {
valeurChamp = "";
}
oMediateur.obtenirListeReferentielPerso(this, typeRef, valeurChamp);
}
public abstract void onValidationSaisie();
public abstract void onModificationValeur();
 
}
/tags/v2.2-faucille/src/org/tela_botanica/client/util/RequestBuilderWithCredentials.java
New file
0,0 → 1,11
package org.tela_botanica.client.util;
 
import com.google.gwt.http.client.RequestBuilder;
 
public class RequestBuilderWithCredentials extends RequestBuilder {
 
public RequestBuilderWithCredentials(Method httpMethod, String url) {
super(httpMethod, url);
this.setIncludeCredentials(true);
}
}
/tags/v2.2-faucille/src/org/tela_botanica/client/util/ChampSaisieEtendu.java
New file
0,0 → 1,245
package org.tela_botanica.client.util;
 
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
 
import org.tela_botanica.client.interfaces.Rafraichissable;
import org.tela_botanica.client.modeles.dao.ListeReferentielChampsEtendusDAO;
import org.tela_botanica.client.modeles.objets.Configuration;
 
import com.google.gwt.user.client.Timer;
import com.gwtext.client.core.EventCallback;
import com.gwtext.client.core.EventObject;
import com.gwtext.client.core.Ext;
import com.gwtext.client.core.ListenerConfig;
import com.gwtext.client.data.ArrayReader;
import com.gwtext.client.data.FieldDef;
import com.gwtext.client.data.MemoryProxy;
import com.gwtext.client.data.Record;
import com.gwtext.client.data.RecordDef;
import com.gwtext.client.data.Store;
import com.gwtext.client.data.StringFieldDef;
import com.gwtext.client.widgets.Component;
import com.gwtext.client.widgets.event.ComponentListenerAdapter;
import com.gwtext.client.widgets.form.ComboBox;
import com.gwtext.client.widgets.form.Field;
import com.gwtext.client.widgets.form.event.ComboBoxListenerAdapter;
 
public class ChampSaisieEtendu extends ComboBox implements Rafraichissable {
// TODO: faire un enum
private final int KEY_ALT = 18;
private final int KEY_BACKSPACE = 8;
private final int KEY_CTRL = 17;
private final int KEY_DELETE = 46;
private final int KEY_DOWN = 40;
private final int KEY_END = 35;
private final int KEY_ENTER = 13;
private final int KEY_ESCAPE = 27;
private final int KEY_HOME = 36;
private final int KEY_LEFT = 37;
private final int KEY_PAGEDOWN = 34;
private final int KEY_PAGEUP = 33;
private final int KEY_RIGHT = 39;
private final int KEY_SHIFT = 16;
private final int KEY_TAB = 9;
private final int KEY_UP = 38;
private boolean selectionValeur = false;
private boolean estModifie = false;
private String cle = null;
private String label = null;
private Timer timer = null;
final String resultTplRefPerso = "<div class=\"search-item-ref\">{valeur}</div>";
private List<String> cacheValeurs;
private Record rdSelectionne = null;
private String valeurBrute = "";
public ChampSaisieEtendu(String label, String cle) {
// Accesskey pour debugging
super(label,cle);
 
this.cle =cle;
this.label = label;
setTpl(resultTplRefPerso);
setMode(ComboBox.REMOTE);
setItemSelector("div.search-item-ref");
setTypeAhead(false);
setLoadingText("Recherche...");
setHideTrigger(true);
setValidateOnBlur(false);
ListenerConfig listenerConfigAutocompletion=new ListenerConfig();
listenerConfigAutocompletion.setDelay(200);
listenerConfigAutocompletion.setStopPropagation(false);
listenerConfigAutocompletion.setStopEvent(false);
initStoreVide();
if(Configuration.saisieChampsEtendusActivee()) {
addKeyPressListener(new EventCallback() {
@Override
public void execute(EventObject e) {
switch(e.getKey()) {
case KEY_ALT:
case KEY_CTRL:
case KEY_END:
case KEY_ESCAPE:
case KEY_HOME:
case KEY_LEFT:
case KEY_PAGEDOWN:
case KEY_PAGEUP:
case KEY_RIGHT:
case KEY_SHIFT:
case KEY_TAB:
case KEY_UP:
break;
case KEY_ENTER:
if(rdSelectionne != null) {
setValue(rdSelectionne.getAsString("valeur"));
selectionValeur=true;
valeurBrute = rdSelectionne.getAsString("valeur");
}
break;
case KEY_DOWN:
if(getValueAsString().isEmpty() && !isExpanded()) {
obtenirListeValeurs("*");
}
break;
default:
if(timer != null) {
timer.cancel();
}
timer = new Timer() {
@Override
public void run() {
obtenirListeValeurs();
}
};
timer.schedule(300);
valeurBrute = getValueAsString();
setValue(valeurBrute);
}
}
},listenerConfigAutocompletion);
}
addListener(new ComboBoxListenerAdapter() {
@Override
public void onSelect(ComboBox comboBox, Record record, int index) {
rdSelectionne = record;
setRawValue(rdSelectionne.getAsString("valeur"));
}
@Override
public void onBlur(Field field) {
if(rdSelectionne != null && !rdSelectionne.getAsString("valeur").equals(valeurBrute)) {
setRawValue(valeurBrute);
}
}
});
this.addListener(new ComponentListenerAdapter() {
@Override
public void onRender(Component component) {
setLargeurChamp();
}
});
}
 
@Override
public void rafraichir(Object nouvelleDonnees, boolean repandreRaffraichissement) {
@SuppressWarnings("unchecked")
ArrayList<String> valeurs = (ArrayList<String>)nouvelleDonnees;
cacheValeurs = valeurs;
 
int i = 0;
Object[][] refData = new Object[valeurs.size()][1];
for (Iterator<String> it = valeurs.iterator(); it.hasNext();)
{
refData[i][0]= it.next();
i++;
}
FieldDef defValeur = new StringFieldDef("valeur");
FieldDef[] defTab = {defValeur};
RecordDef rd = new RecordDef(defTab);
final MemoryProxy dataProxy = new MemoryProxy(refData);
final ArrayReader reader = new ArrayReader(rd);
Store store = new Store(dataProxy,reader);
setStore(store);
store.load();
}
private void obtenirListeValeurs() {
String valeurChamp = getRawValue();
obtenirListeValeurs(valeurChamp);
}
private void obtenirListeValeurs(String valeurChamp) {
if(valeurChamp == null) {
valeurChamp = "";
} else {
valeurChamp += "*";
}
ListeReferentielChampsEtendusDAO lrceDao = new ListeReferentielChampsEtendusDAO(null);
lrceDao.obtenirListeValeursChampEtendu(this, cle, valeurChamp);
}
public void setLargeurChamp() {
// Correction un peu moche pour améliorer l'affichage du champ
String idElementEnfant = Ext.get(("x-form-el-"+cle)).getFirstChild().getId();
Ext.get(idElementEnfant).setWidth("90%", false);
Ext.get(cle).setWidth("100%", false);
}
private void initStoreVide() {
Object[][] refData = new Object[0][1];
FieldDef defValeur = new StringFieldDef("valeur");
FieldDef[] defTab = {defValeur};
RecordDef rd = new RecordDef(defTab);
final MemoryProxy dataProxy = new MemoryProxy(refData);
final ArrayReader reader = new ArrayReader(rd);
Store store = new Store(dataProxy,reader);
setStore(store);
store.load();
}
@Override
public void setValue(String valeur) {
valeurBrute = valeur;
super.setValue(valeur);
}
public String getCle() {
return cle;
}
public String getLabel() {
return label;
}
}
/tags/v2.2-faucille/src/org/tela_botanica/client/util/Util.java
New file
0,0 → 1,304
package org.tela_botanica.client.util;
 
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
 
import org.tela_botanica.client.modeles.objets.ChampEtendu;
import org.tela_botanica.client.modeles.objets.Observation;
 
import com.google.gwt.http.client.URL;
import com.google.gwt.json.client.JSONArray;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONString;
 
public class Util {
 
public Util() {
}
public static String getValeurJsonOuVide(JSONObject jo, String index) {
return jsonNonNull(jo, index) ? ((JSONString)jo.get(index)).stringValue() : "";
}
public static Map<String, ChampEtendu> getMapValeursOuVide(JSONObject jo, String index) {
Map<String, ChampEtendu> mapValeurs = new HashMap<String, ChampEtendu>();
if(jo.get(index) != null && jo.get(index).isArray() != null) {
JSONArray tabJo = jo.get(index).isArray();
for (int i = 0; i < tabJo.size(); i++) {
JSONObject champJson = tabJo.get(i).isObject();
String cle = champJson.get("cle").isString().stringValue();
String label = champJson.get("label").isString().stringValue();
String valeur = champJson.get("valeur").isString().stringValue();
ChampEtendu champ = new ChampEtendu(cle, label, valeur);
mapValeurs.put(cle, champ);
}
 
}
return mapValeurs;
}
public static String convertirChampsEtendusEnChaineRequete(Map<String, ChampEtendu> map) {
String json = "";
if (map != null && !map.isEmpty()) {
JSONArray jsonArr = new JSONArray();
int i = 0;
for (Map.Entry<String, ChampEtendu> entry: map.entrySet()) {
jsonArr.set(i, convertirChampEtenduEnJson(entry.getValue()));
i++;
}
json = jsonArr.toString();
}
return json;
}
public static JSONObject convertirChampEtenduEnJson(ChampEtendu champEtendu) {
JSONObject jsonObj = new JSONObject();
jsonObj.put("cle", new JSONString(champEtendu.getCle()));
jsonObj.put("label", new JSONString(champEtendu.getLabel()));
jsonObj.put("valeur", new JSONString(champEtendu.getValeur()));
return jsonObj;
}
public static boolean jsonNonNull(JSONObject jo, String index) {
return (jo != null &&
jo.get(index) != null &&
jo.get(index).isNull() == null
);
}
public static String formaterLieu(Observation obs, String modeleLieu) {
String lieuModele = modeleLieu;
String commune = obs.getLocalite();
String lieuDit = obs.getLieudit();
String station = obs.getStation();
String lieuCommuneFormate = "";
String lieuDitFormate = "";
String stationFormatee = "";
if(commune != null && !commune.contains("000null") && !commune.trim().equals("")) {
String idLoc =obs.getIdentifiantLocalite().replaceAll(" ","/");
if(idLoc != null && !idLoc.contains("000null") && !idLoc.trim().equals("")) {
 
idLoc = idLoc.replaceAll("%","");
idLoc = idLoc.replaceAll("\"","");
idLoc = idLoc.replace('\\',' ');
idLoc = idLoc.trim();
if(idLoc.length() > 2) {
idLoc = idLoc.substring(0,2);
}
lieuCommuneFormate += idLoc+" - ";
}
lieuCommuneFormate += commune;
lieuModele = lieuModele.replaceAll("IDLOCCOMMUNE", lieuCommuneFormate);
} else {
lieuModele = lieuModele.replaceAll("IDLOCCOMMUNE,", lieuCommuneFormate);
}
if(lieuDit != null && !lieuDit.contains("000null") && !lieuDit.trim().equals("")) {
lieuDitFormate += lieuDit;
lieuModele = lieuModele.replaceAll("LIEUDIT", lieuDitFormate);
} else {
lieuModele = lieuModele.replaceAll("LIEUDIT,", lieuDitFormate);
}
if(station != null && !station.contains("000null") && !station.trim().equals("")) {
stationFormatee += station;
lieuModele = lieuModele.replaceAll("STATION", stationFormatee);
} else {
lieuModele = lieuModele.replaceAll("STATION", stationFormatee);
}
lieuModele = lieuModele.trim();
lieuModele = lieuModele.replaceAll(",$","");
lieuModele = lieuModele.replaceAll(",^$",", ");
return lieuModele;
}
public static String obtenirDepartementAPartirChaineCommune(String departement, String commune) {
String dep = "";
if(departement == null) {
departement = "";
}
if(departement.equals("000null") || departement.equals("")) {
String[] depCom = commune.split(" ");
if(depCom.length > 1) {
dep = depCom[1].replace('(', ' ');
} else {
dep = "";
}
} else {
dep = departement;
}
dep = dep.replace(')', ' ');
dep = dep.trim();
dep = dep.replace('\\',' ');
dep = dep.trim();
try
{
int nDep = Integer.parseInt(dep);
if(nDep > 0 && nDep < 110) {
departement = dep ;
}
if(departement.length() == 4) {
departement = "0"+departement;
}
departement = departement.substring(0,2);
}
catch(NumberFormatException e)
{
departement = "" ;
}
return departement;
}
public static String supprimerNumDepartementChaineLocalite(String chaineLocaliteComplete) {
return chaineLocaliteComplete.replaceAll(" \\([0-9]*\\)", "");
}
public static String convertirChaineZoneGeoVersDepartement(String chaineZoneGeo) {
return (!chaineZoneGeo.equals("000null") && !chaineZoneGeo.equals("") && chaineZoneGeo.replaceAll("INSEE-C:", "").length() >= 2) ?
chaineZoneGeo.replaceAll("INSEE-C:", "").substring(0, 2) :
chaineZoneGeo;
}
public static String convertirChaineZoneGeoVersCodeInsee(String chaineZoneGeo) {
return (!chaineZoneGeo.equals("000null") && !chaineZoneGeo.equals("")) ? chaineZoneGeo.replaceAll("INSEE-C:", ""): chaineZoneGeo;
}
/***
* Fusionne les éléments d'un tableau en une chaîne
* @param delim : la chaîne de séparation
* @param args : la tableau
* @return la chaîne fusionnée
*/
public static String implode(String delim, String[] args){
StringBuffer sb = new StringBuffer();
int lgArgs = args.length;
for(int i = 0; i < lgArgs; i++){
if (i > 0) {
sb.append(delim);
}
sb.append(args[i]);
}
return sb.toString();
}
public static boolean filtreValide(String[] filtre) {
return (filtre.length == 2 &&
filtre[0] != null &&
!filtre[0].equals("") &&
filtre[1] != null &&
!filtre[1].equals(""));
}
public static String renvoyerMois(int numMois) {
switch (numMois) {
case 1:
return "janvier" ;
case 2:
return "fevrier" ;
case 3:
return "mars" ;
case 4:
return "avril" ;
case 5:
return "mai" ;
case 6:
return "juin" ;
case 7:
return "juillet" ;
case 8:
return "août" ;
case 9:
return "septembre" ;
case 10:
return "octobre" ;
case 11:
return "novembre" ;
case 12:
return "décembre" ;
default:
return "Inconnu" ;
}
}
public static String remplacerSautsDeligneMalEncodes(String chaineAvecSautsDeLignesMalEncodes) {
String chaineAvecSautsDeLignesBienEncodes = chaineAvecSautsDeLignesMalEncodes.replace('\\','%');
chaineAvecSautsDeLignesBienEncodes = chaineAvecSautsDeLignesBienEncodes.replaceAll("%n","%");
chaineAvecSautsDeLignesBienEncodes = chaineAvecSautsDeLignesBienEncodes.replace('%','\n');
return chaineAvecSautsDeLignesBienEncodes;
}
public static boolean verifierDateFormatCel(String dateAVerifier) {
String dateRemplacee = remplacerSeparateursDateFormatCel(dateAVerifier);
String[] tabDate = dateRemplacee.split("/");
boolean retour = false;
if(tabDate.length == 3) {
//TODO: faire un parsing de date qui fonctionne mieux car
// on peut saisir un 31 novembre par exemple
// mais l'api date de java est mal gérée par gwt
try {
int jour = Integer.parseInt(tabDate[0]);
int mois = Integer.parseInt(tabDate[1]);
int annee = Integer.parseInt(tabDate[2]);
if(jour <= 31 && mois <= 12 && tabDate[2].length() == 4) {
retour = true;
}
} catch (Exception e) {
 
}
}
return retour;
}
public static String remplacerSeparateursDateFormatCel(String date) {
String dateRemplacee = date.replaceAll("-", "/");
return dateRemplacee;
}
public static boolean estZero(String s) {
boolean estZero = false;
try {
Double dou = Double.parseDouble(s);
estZero = (dou == 0);
} catch(NumberFormatException e) {
 
}
return estZero;
}
public static String formaterNombre(String s) {
s = s.indexOf(".") < 0 ? s : s.replaceAll("0*$", "").replaceAll("\\.$", "");
return s;
}
}
/tags/v2.2-faucille/src/org/tela_botanica/client/util/FormulaireSaisieChampEtendu.java
New file
0,0 → 1,399
package org.tela_botanica.client.util;
 
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
 
import org.tela_botanica.client.interfaces.Rafraichissable;
import org.tela_botanica.client.modeles.dao.ListeReferentielChampsEtendusDAO;
import org.tela_botanica.client.modeles.objets.Configuration;
import org.tela_botanica.client.modeles.objets.ListeChampsEtendus;
import org.tela_botanica.client.modeles.objets.ListeGroupesChampsEtendus;
 
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.gwtext.client.core.EventCallback;
import com.gwtext.client.core.EventObject;
import com.gwtext.client.core.ListenerConfig;
import com.gwtext.client.data.ArrayReader;
import com.gwtext.client.data.FieldDef;
import com.gwtext.client.data.MemoryProxy;
import com.gwtext.client.data.Record;
import com.gwtext.client.data.RecordDef;
import com.gwtext.client.data.SimpleStore;
import com.gwtext.client.data.Store;
import com.gwtext.client.data.StringFieldDef;
import com.gwtext.client.widgets.Button;
import com.gwtext.client.widgets.Panel;
import com.gwtext.client.widgets.event.ButtonListenerAdapter;
import com.gwtext.client.widgets.form.ComboBox;
import com.gwtext.client.widgets.form.Field;
import com.gwtext.client.widgets.form.FormPanel;
import com.gwtext.client.widgets.form.event.ComboBoxListenerAdapter;
import com.gwtext.client.widgets.layout.FormLayout;
 
@SuppressWarnings("unchecked")
public abstract class FormulaireSaisieChampEtendu extends FormPanel implements Rafraichissable {
private final int KEY_ALT = 18;
private final int KEY_BACKSPACE = 8;
private final int KEY_CTRL = 17;
private final int KEY_DELETE = 46;
private final int KEY_DOWN = 40;
private final int KEY_END = 35;
private final int KEY_ENTER = 13;
private final int KEY_ESCAPE = 27;
private final int KEY_HOME = 36;
private final int KEY_LEFT = 37;
private final int KEY_PAGEDOWN = 34;
private final int KEY_PAGEUP = 33;
private final int KEY_RIGHT = 39;
private final int KEY_SHIFT = 16;
private final int KEY_TAB = 9;
private final int KEY_UP = 38;
final ComboBox nChamp;
final String resultTplRefPerso = "<div class=\"search-item-ref\">{label}</div>";
Button ajouterChampsEtenduEtFermer;
Button ajouterChampsEtendu;
Button annulerAjouterChampEtendu;
String idChamp = null;
Panel conteneurGroupesChampsEtendus;
final ComboBox groupesChampsEtendus;
HTML indicationSaisieGroupe;
private static ListeGroupesChampsEtendus cacheGroupes;
private Timer timer = null;
private static Map<String, String> cacheClesValeur;
private Record rdSelectionne = null;
private Record groupeSelectionne = null;
private String valeurBrute = "";
public FormulaireSaisieChampEtendu() {
super();
setPaddings(3);
setBodyBorder(false);
indicationSaisieGroupe = new HTML("Vous pouvez ajouter plusieurs champs à la fois correspondant à un groupe "+
"par exemple les champs des projet 'sauvages de ma rue' ou 'florilèges', etc... <br />"+
"De nouveaux groupes seront ajoutés régulièrement en fonction des champs les plus utilisés");
indicationSaisieGroupe.addStyleName("aideCreerChampEtendu");
groupesChampsEtendus = new ComboBox();
groupesChampsEtendus.setWidth("350px");
groupesChampsEtendus.setLabel("Ajouter un groupe de champs");
groupesChampsEtendus.setDisplayField("label") ;
groupesChampsEtendus.setValueField("valeur");
groupesChampsEtendus.setEditable(false);
groupesChampsEtendus.setHideTrigger(false);
groupesChampsEtendus.setForceSelection(true);
groupesChampsEtendus.setCls("champ-separation");
groupesChampsEtendus.setValue("");
conteneurGroupesChampsEtendus = new Panel();
conteneurGroupesChampsEtendus.setBorder(false);
conteneurGroupesChampsEtendus.setPaddings(0);
conteneurGroupesChampsEtendus.setMargins(0);
conteneurGroupesChampsEtendus.setLayout(new FormLayout());
conteneurGroupesChampsEtendus.setWidth("100%");
add(conteneurGroupesChampsEtendus);
if(cacheGroupes == null) {
ListeReferentielChampsEtendusDAO lrceDao = new ListeReferentielChampsEtendusDAO(null);
lrceDao.obtenirGroupesChampsEtendus(this);
} else {
this.rafraichir(cacheGroupes, false);
}
HTML indicationSaisie = new HTML("Saisissez un nom de champ ou choisisez un nom proposé par l'autocomplétion "+
"Si vous choissisez un nom de champ existant vous pourrez profiter d'une autocomplétion "+
"sur les valeurs déjà saisies pour ce champ par les autres utilisateurs");
indicationSaisie.addStyleName("aideCreerChampEtendu");
add(indicationSaisie);
HorizontalPanel hp = new HorizontalPanel();
hp.setBorderWidth(0);
nChamp = new ComboBox("Nom du champ", "nom_champ_etendu");
add(nChamp);
ajouterChampsEtenduEtFermer = new Button("Ajouter et fermer");
ajouterChampsEtenduEtFermer.setTooltip("Ajouter un champ étendu ou un groupe de champs et fermer la fenêtre");
ajouterChampsEtendu = new Button("Ajouter");
ajouterChampsEtendu.setTooltip("Ajouter un champ étendu ou un groupe de champ");
annulerAjouterChampEtendu = new Button("Annuler");
annulerAjouterChampEtendu.setTooltip("Fermer la fenêtre sans ajouter de champ");
hp.add(ajouterChampsEtenduEtFermer);
hp.add(ajouterChampsEtendu);
hp.add(annulerAjouterChampEtendu);
add(hp);
nChamp.setTpl(resultTplRefPerso);
nChamp.setMode(ComboBox.REMOTE);
nChamp.setItemSelector("div.search-item-ref");
nChamp.setTypeAhead(false);
nChamp.setLoadingText("Recherche...");
nChamp.setHideTrigger(true);
nChamp.setValidateOnBlur(false);
nChamp.setWidth("350px");
nChamp.focus();
ajouterListeners();
}
 
private void ajouterListeners() {
ListenerConfig listenerConfigAutocompletion=new ListenerConfig();
listenerConfigAutocompletion.setDelay(200);
listenerConfigAutocompletion.setStopPropagation(false);
listenerConfigAutocompletion.setStopEvent(true);
nChamp.addKeyPressListener(new EventCallback() {
 
@Override
public void execute(EventObject e) {
 
switch(e.getKey()) {
case KEY_ALT:
case KEY_CTRL:
case KEY_END:
case KEY_HOME:
case KEY_LEFT:
case KEY_PAGEDOWN:
case KEY_PAGEUP:
case KEY_RIGHT:
case KEY_SHIFT:
case KEY_TAB:
case KEY_UP:
break;
case KEY_ENTER:
if(rdSelectionne != null) {
nChamp.setValue(rdSelectionne.getAsString("label"));
idChamp = rdSelectionne.getAsString("cle");
valeurBrute = rdSelectionne.getAsString("label");
}
break;
case KEY_DOWN:
if(nChamp.getValueAsString().isEmpty() && !nChamp.isExpanded()) {
obtenirListeValeurs("*");
}
break;
case KEY_ESCAPE:
surAnnulation();
break;
default:
if(timer != null) {
timer.cancel();
}
timer = new Timer() {
@Override
public void run() {
obtenirListeValeurs();
}
};
timer.schedule(300);
valeurBrute = nChamp.getValueAsString();
nChamp.setValue(valeurBrute);
}
}
},listenerConfigAutocompletion);
// Listener completion
nChamp.addListener(new ComboBoxListenerAdapter() {
@Override
public void onSelect(ComboBox comboBox, Record record, int index) {
rdSelectionne = record;
}
@Override
public void onBlur(Field field) {
nChamp.setRawValue(valeurBrute);
nChamp.collapse();
}
});
groupesChampsEtendus.addListener(new ComboBoxListenerAdapter() {
@Override
public void onSelect(ComboBox comboBox, Record record, int index) {
groupeSelectionne = record;
}
});
ajouterChampsEtenduEtFermer.addListener(new ButtonListenerAdapter() {
@Override
public void onClick(Button button, EventObject e) {
if(doitAjouterGroupe()) {
surValidationMultiple(renvoyerListeChampsEtendus(groupeSelectionne.getAsString("valeur")));
} else {
if(champEtenduEstValide()) {
surValidation(validerEtRenvoyerChampEtendu());
} else {
Window.alert("Le nom du champ étendu ne peut pas être vide");
}
}
}
});
ajouterChampsEtendu.addListener(new ButtonListenerAdapter() {
@Override
public void onClick(Button button, EventObject e) {
if(champEtenduEstValide()) {
surAjout(validerEtRenvoyerChampEtendu());
raz();
} else {
Window.alert("Le nom du champ étendu ne peut pas être vide");
}
}
});
annulerAjouterChampEtendu.addListener(new ButtonListenerAdapter() {
@Override
public void onClick(Button button, EventObject e) {
surAnnulation();
}
});
}
private void raz() {
timer = null;
idChamp = null;
nChamp.clearValue();
nChamp.focus();
}
private ChampSaisieEtendu validerEtRenvoyerChampEtendu() {
String valeurChamp = nChamp.getValueAsString();
String idNouveauChamp = "";
if(!estUnChampSelectionne(valeurChamp)) {
Date date = new Date();
// affectation d'un id temporaire qui sera remplacé par l'id auto généré à partir
// du label
idNouveauChamp = "tempid_"+date.getTime();
} else {
idNouveauChamp = idChamp;
}
ChampSaisieEtendu retour = new ChampSaisieEtendu(valeurChamp, idNouveauChamp);
retour.setId(idNouveauChamp);
return retour;
}
private List<ChampSaisieEtendu> renvoyerListeChampsEtendus(String groupe) {
List<ChampSaisieEtendu> champsDuGroupe = new ArrayList<ChampSaisieEtendu>();
HashMap<String, String> listeChampsEtendus = cacheGroupes.get(groupe);
for (Iterator<String> iterator = listeChampsEtendus.keySet().iterator(); iterator.hasNext();) {
String cle = iterator.next();
String label = listeChampsEtendus.get(cle);
ChampSaisieEtendu champ = new ChampSaisieEtendu(label, cle);
champsDuGroupe.add(champ);
}
 
return champsDuGroupe;
}
private boolean doitAjouterGroupe() {
return groupeSelectionne != null && !groupeSelectionne.getAsString("valeur").equals("");
}
private boolean champEtenduEstValide() {
String valeurChamp = nChamp.getValueAsString();
return (valeurChamp != null && !valeurChamp.isEmpty());
}
private boolean estUnChampSelectionne(String valeur) {
return cacheClesValeur.containsValue(valeur);
}
private void obtenirListeValeurs() {
obtenirListeValeurs(nChamp.getValueAsString());
}
private void obtenirListeValeurs(String valeur) {
ListeReferentielChampsEtendusDAO lrce = new ListeReferentielChampsEtendusDAO(null);
lrce.obtenirListeNomsChampsEtendus(this, valeur+"*");
}
public abstract void surAjout(ChampSaisieEtendu champ);
public abstract void surAjoutMultiple(List<ChampSaisieEtendu> champs);
public abstract void surValidation(ChampSaisieEtendu champ);
public abstract void surValidationMultiple(List<ChampSaisieEtendu> champs);
public abstract void surAnnulation();
public void rafraichir(Object nouvelleDonnees, boolean repandreRaffraichissement) {
if(nouvelleDonnees instanceof ListeChampsEtendus) {
int i = 0;
ListeChampsEtendus clesLabels = (ListeChampsEtendus)nouvelleDonnees;
cacheClesValeur = clesLabels;
Object[][] refData = new Object[clesLabels.keySet().size()][2];
for (Iterator<String> it = clesLabels.keySet().iterator(); it.hasNext();)
{
String cle = it.next();
String label= clesLabels.get(cle);
refData[i][0]= cle;
refData[i][1]= label;
i++;
}
FieldDef defCle = new StringFieldDef("cle");
FieldDef defLabel = new StringFieldDef("label");
FieldDef[] defTab = {defCle, defLabel};
RecordDef rd = new RecordDef(defTab);
final MemoryProxy dataProxy = new MemoryProxy(refData);
final ArrayReader reader = new ArrayReader(rd);
Store store=new Store(dataProxy,reader);
nChamp.setStore(store);
store.load();
}
if(nouvelleDonnees instanceof ListeGroupesChampsEtendus) {
cacheGroupes = (ListeGroupesChampsEtendus)nouvelleDonnees;
groupesChampsEtendus.setStore(getGroupesChampsEtendusStore(cacheGroupes));
if(cacheGroupes.size() > 0) {
conteneurGroupesChampsEtendus.add(indicationSaisieGroupe);
conteneurGroupesChampsEtendus.add(groupesChampsEtendus);
doLayout();
}
}
}
private Store getGroupesChampsEtendusStore(ListeGroupesChampsEtendus listeGroupesChampsEtendus) {
int i = 1;
Object[][] valeurs = new Object[listeGroupesChampsEtendus.size()+1][2];
valeurs[0][0] = "...";
valeurs[0][1] = "";
if(listeGroupesChampsEtendus.size() > 0) {
for (Iterator<String> it = listeGroupesChampsEtendus.keySet().iterator(); it.hasNext();)
{
String cle = it.next();
valeurs[i][0]= cle;
valeurs[i][1]= cle;
i++;
}
}
SimpleStore store = new SimpleStore(new String[] {"label","valeur"},valeurs);
store.load();
return store;
}
}
/tags/v2.2-faucille/src/org/tela_botanica/client/util/MotsClesUtilitaire.java
New file
0,0 → 1,158
package org.tela_botanica.client.util;
 
import java.util.HashMap;
 
import org.tela_botanica.client.cel2;
 
import com.google.gwt.json.client.JSONArray;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.user.client.Window;
import com.gwtext.client.data.Node;
import com.gwtext.client.data.Tree;
import com.gwtext.client.widgets.tree.TreeNode;
 
public class MotsClesUtilitaire {
//TODO rassembler tout ce qui construit les arbres de mots clés ici
private static String[] caracteresInterdits = {"\\", "/", ","};
public static String obtenirCheminParent(String cheminMotCle, String motCle) {
return cheminMotCle.substring(0, cheminMotCle.length() - motCle.length() -1).toLowerCase();
}
 
public static Object[] construireArbre(String NomRacine, String idRacine,
JSONArray arbreJson, boolean afficherCheckbox) {
Tree arbreMotsCles = new Tree() ;
HashMap<String, String> motsCles = new HashMap<String, String>(0);
HashMap<String, String> parentes = new HashMap<String, String>();
final int taillemax = arbreJson.size();
 
// on crée un arbre vide
TreeNode root = new TreeNode();
root.setId(idRacine);
root.setText(NomRacine);
String[] usObjRacine = {NomRacine, idRacine};
root.setUserObject(usObjRacine);
arbreMotsCles.setRootNode(root);
// le mot clé racine possède le chemin racine ("/")
parentes.put("/", idRacine);
 
// pour chacun des élements du tableau
for (int j = 0; j < taillemax; j++) {
// on extrait les élements du tableau
if (arbreJson.get(j).isObject() != null) {
JSONObject noeud = (JSONObject) arbreJson.get(j);
 
String idMotCle = noeud.get("id_mot_cle")
.isString().stringValue();
String motCle = noeud.get("mot_cle").isString()
.stringValue();
// le chemin est mis en minuscule afin de fusionner toutes
// la variantes minuscules majuscule d'un mot clé
// qui peuvent poser problème
String chemin = noeud.get("chemin").isString()
.stringValue().toLowerCase();
String cheminParent = MotsClesUtilitaire.obtenirCheminParent(chemin, motCle);
String parent = parentes.get(cheminParent);
String[] usObj = {motCle, idMotCle};
 
// et on construit l'arbre en ajoutant les noeuds un à un (qui sont renvoyés
// dans l'ordre hierarchique de leur niveau
// ce qui permet de les traiter séquentiellement)
TreeNode node = new TreeNode();
node.setId(idMotCle);
node.setText(motCle);
if(afficherCheckbox) {
node.setChecked(false);
}
 
Node parentNode = arbreMotsCles.getNodeById(parent);
node.setUserObject(usObj);
parentNode.appendChild(node);
parentes.put(chemin, idMotCle);
motsCles.put(idMotCle, motCle);
}
}
Object[] retour = {arbreMotsCles, motsCles};
return retour;
}
 
/**
* Fonction récursive qui prend deux noeuds d'arbre en paramètre et crée un
* copie du sous arbre du premier noeud, qu'elle concatène au deuxième
*
* @param ndPereOriginal
* le père des noeuds de l'arbre original
* @param ndPereCopie
* le père qui va recevoir les copies
*/
public static void copierFilsNoeud(Node ndPereOriginal, TreeNode ndPereCopie, boolean afficherCheckbox) {
if (ndPereCopie != null && ndPereOriginal != null) {
Node[] ndNodeFils = ndPereOriginal.getChildNodes();
for (int i = 0; i < ndNodeFils.length; i++) {
String[] usObj = (String[]) ndNodeFils[i].getUserObject();
TreeNode child = new TreeNode(usObj[0]);
child.setId(usObj[1]);
if(afficherCheckbox) {
child.setChecked(false);
}
child.setUserObject(usObj);
ndPereCopie.appendChild(child);
 
if (!ndNodeFils[i].isLeaf()) {
copierFilsNoeud(ndNodeFils[i], child, afficherCheckbox);
}
}
}
}
public static TreeNode ajouterNoeud(TreeNode parent, boolean afficherCheckbox) {
// on crée un nouveau noeud vide
TreeNode nd = new TreeNode("");
nd.setCls("x-view-treenode-keyword");
if(afficherCheckbox) {
nd.setChecked(true);
}
// on associe un objet au noeud qui contient des infos
String[] usObject = new String[2];
// l'objet contient le nom du noeud
usObject[0] = "";
usObject[1] = "";
nd.setUserObject(usObject);
String cheminTemporaireAjout = parent.getPath()+"/"+nd.getId();
nd.setId(cheminTemporaireAjout);
return nd;
}
public static String getChaineCaracteresInterdits() {
String interdits = "";
for (int i = 0; i < MotsClesUtilitaire.caracteresInterdits.length; i++) {
interdits += MotsClesUtilitaire.caracteresInterdits[i]+" ";
}
return interdits;
}
public static boolean estUnMotCleAutorise(String motCle) {
boolean valide = !motCle.trim().isEmpty();
for (int i = 0; i < MotsClesUtilitaire.caracteresInterdits.length; i++) {
if(motCle.indexOf(MotsClesUtilitaire.caracteresInterdits[i]) != -1) {
valide = false;
break;
}
}
return valide;
}
}