Subversion Repositories eFlore/Applications.del

Compare Revisions

Ignore whitespace Rev 2093 → Rev 2094

/tags/v1.10-sodium/src/org/tela_botanica/del/client/utils/UtilitairesServiceResultat.java
New file
0,0 → 1,832
package org.tela_botanica.del.client.utils;
 
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
 
import org.tela_botanica.del.client.cache.CacheClient;
import org.tela_botanica.del.client.config.Config;
import org.tela_botanica.del.client.i18n.I18n;
import org.tela_botanica.del.client.modeles.ActiviteUtilisateur;
import org.tela_botanica.del.client.modeles.AuthInfo;
import org.tela_botanica.del.client.modeles.Commentaire;
import org.tela_botanica.del.client.modeles.Contributeur;
import org.tela_botanica.del.client.modeles.EvenementObs;
import org.tela_botanica.del.client.modeles.Image;
import org.tela_botanica.del.client.modeles.ImageServiceResultat;
import org.tela_botanica.del.client.modeles.InterventionForum;
import org.tela_botanica.del.client.modeles.MotCle;
import org.tela_botanica.del.client.modeles.Observation;
import org.tela_botanica.del.client.modeles.ObservationServiceResultat;
import org.tela_botanica.del.client.modeles.PropositionDetermination;
import org.tela_botanica.del.client.modeles.Protocole;
import org.tela_botanica.del.client.modeles.ProtocoleServiceResultat;
import org.tela_botanica.del.client.modeles.Utilisateur;
import org.tela_botanica.del.client.modeles.VoteDetermination;
import org.tela_botanica.del.client.modeles.VoteProtocole;
 
import com.google.gwt.core.shared.GWT;
import com.google.gwt.user.client.Window;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.json.client.JSONArray;
import com.google.gwt.json.client.JSONNumber;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONParser;
import com.google.gwt.json.client.JSONString;
import com.google.gwt.json.client.JSONValue;
 
/**
* Centralisation des methodes de parsing du code JSON retourné par les
* webservices
*
* @author LIENS
*
*/
public class UtilitairesServiceResultat {
 
/**
* Recupere un objet Image à partir du JSON
*
* @param imageJson
* @return
*/
public static Image parserImageJSON(JSONObject imageJson) {
 
Image image = new Image();
Config config = new Config();
String urlImages = config.getUrl("images");
String idImage = imageJson.get("id_image").isString().stringValue();
image.setIdImage(idImage);
image.setUrlFormat(urlImages + getIdAvecPadding(idImage) + "%s%.jpg");
image.setUrl(urlImages + getIdAvecPadding(idImage) + "CRS.jpg");
image.setMiniature(urlImages + getIdAvecPadding(idImage) + "XS.jpg");
image.setMotsClefs(parserMotsCles(UtilitairesServiceResultat.getValeurOuVide(imageJson, "mots_cles_texte")));
 
return image;
}
 
/**
* Recupere un objet Observation à partir du JSON
*
* @param imageJson
* @return
*/
public static Observation parserObservationJSON(JSONObject observationJson) {
 
Observation observation = new Observation();
observation.setAuteur(getValeurOuVide(observationJson, "auteur.prenom") + " " + getValeurOuVide(observationJson, "auteur.nom"));
observation.setNomAuteur(getValeurOuVide(observationJson, "auteur.nom"));
observation.setPrenomAuteur(getValeurOuVide(observationJson, "auteur.prenom"));
observation.setIdAuteur(getValeurOuVide(observationJson, "auteur.id"));
// TODO: renvoyer le courriel de l'auteur dans les obs
observation.setCourrielAuteur(getValeurOuVide(observationJson, "auteur.courriel"));
observation.setDateTransmission(getValeurOuVide(observationJson, "date_transmission"));
observation.setDateReleve(getValeurOuVide(observationJson, "date_observation"));
observation.setFamille(getValeurOuVide(observationJson, "determination.famille"));
observation.setId(getValeurOuVide(observationJson, "id_observation"));
observation.setPays(getValeurOuVide(observationJson, "pays"));
observation.setIdLocalite(getValeurOuVide(observationJson, "id_zone_geo"));
observation.setLocalite(getValeurOuVide(observationJson, "zone_geo"));
 
String nomRetenu = getValeurOuVide(observationJson, "determination.ns");
// Pour afficher quelque chose de plus pertinent qu'un nom vide
// (il en existe parfois et cela fausse l'affichage)
if(nomRetenu.trim().isEmpty()) {
nomRetenu = I18n.getVocabulary().indeterminee();
}
observation.setNomRetenu(nomRetenu);
observation.setMilieu(getValeurOuVide(observationJson, "milieu"));
observation.setLieuDit(getValeurOuVide(observationJson, "lieudit"));
observation.setStation(getValeurOuVide(observationJson, "station"));
observation.setCommentaire(getValeurOuVide(observationJson, "commentaire"));
observation.setNumNomenclatural(getValeurOuVide(observationJson, "determination.nn"));
observation.setReferentiel(getValeurOuVide(observationJson, "determination.referentiel"));
String nbCom = getValeurOuVide(observationJson, "nb_commentaires");
nbCom = nbCom.equals("") ? "0" : nbCom;
observation.setNbCommentaires(nbCom);
observation.setMotsClefs(parserMotsCles(UtilitairesServiceResultat.getValeurOuVide(observationJson, "mots_cles_texte")));
JSONValue propositions = observationJson.get("commentaires");
JSONValue evenements = observationJson.get("evenements");
List<EvenementObs> evenementsObs = new ArrayList<EvenementObs>();
if (evenements != null && evenements.isArray() != null) {
JSONArray evenementsTab = evenements.isArray();
for (int i = 0; i < evenementsTab.size(); i++) {
String type = evenementsTab.get(i).isObject().get("type").isString().stringValue();
String infosComplementaires = evenementsTab.get(i).isObject().get("infos_complementaires").isString().stringValue();
EvenementObs evtObs = new EvenementObs(type, infosComplementaires);
evenementsObs.add(evtObs);
}
}
observation.setEvenementsAssocies(evenementsObs);
 
boolean creerPropositionAPartirObs = true;
boolean propositionInitialeExiste = false;
PropositionDetermination propositionPotentiellementInitiale = null;
if (propositions != null && propositions.isObject() != null) {
List<InterventionForum> interventions = parserInterventions(propositions.isObject());
for (InterventionForum interventionForum : interventions) {
interventionForum.setObservation(observation);
if (interventionForum instanceof PropositionDetermination) {
PropositionDetermination proposition = (PropositionDetermination) interventionForum;
// Si une proposition avec les même nums noms et référentiel que l'observation est déjà présente,
// alors il n'est pas nécessaire de créer la proposition "factice"
if (especePropositionEtObservationCorrespondent(observation, proposition)) {
creerPropositionAPartirObs = false;
// Si de plus les auteurs correspondent, alors nous avons affaire à la proposition initiale
if(proposition.getContributeur().getNomComplet().equals(observation.getAuteur())) {
propositionPotentiellementInitiale = proposition;
}
}
if (proposition.estPropositionInitiale()) {
propositionInitialeExiste = true;
}
}
}
observation.setInterventionsForum(interventions);
}
if (!propositionInitialeExiste && propositionPotentiellementInitiale != null) {
// Ceci permet à la la proposition d'être mise en valeur différemment dans l'interface
propositionPotentiellementInitiale.setEstPropositionInitiale(true);
}
if (creerPropositionAPartirObs) {
// Si elle est nécessaire, la proposition factice est ajoutée au début
observation.getInterventionsForum().add(0, creerPropositionDeterminationAPartirObservation(observation, propositionInitialeExiste));
}
return observation;
 
}
public static boolean especePropositionEtObservationCorrespondent(Observation observation, PropositionDetermination proposition) {
boolean correspondent = false;
// pas la peine de comparer deux choses pourraient éventuellement être vide
if(!observation.getNumNomenclatural().isEmpty() && !observation.getReferentiel().isEmpty()) {
// Vérification si les num noms et référentiels correspondent
correspondent = (observation.getNumNomenclatural().equals(proposition.getNumNomenclatural())) && (observation.getReferentiel().equals(proposition.getReferentiel()));
}
return correspondent;
}
 
/**
* Créée une proposition de determination à partir d'une observation
*
* @param observation
* @return
*/
private static PropositionDetermination creerPropositionDeterminationAPartirObservation(Observation observation, boolean propositionInitialeExiste) {
 
String utilisateurNom = observation.getNomAuteur();
String utilisateurPrenom = observation.getPrenomAuteur();
 
String utilisateurCourriel = observation.getCourrielAuteur();
String utilisateurId = observation.getIdAuteur();
PropositionDetermination propositionDetermination = new PropositionDetermination(observation);
Contributeur contributeur = new Contributeur(utilisateurId, utilisateurNom, utilisateurPrenom, utilisateurCourriel);
propositionDetermination.setContributeur(contributeur);
java.util.Date datePropDeter = parserDateObservation(observation.getDateTransmission());
propositionDetermination.setDate(datePropDeter);
propositionDetermination.setEspece(observation.getNomRetenu());
propositionDetermination.setNumNomenclatural(observation.getNumNomenclatural());
propositionDetermination.setReferentiel(observation.getReferentiel());
if (!propositionInitialeExiste) {
propositionDetermination.setEstPropositionInitiale(true);
}
 
return propositionDetermination;
}
 
/**
* Recupere une liste de commentaires à partir du JSON
*
* @param imageJson
* @return
*/
public static List<Commentaire> parserCommentaires(JSONObject commentaires) {
List<InterventionForum> interventionForums = parserInterventions(commentaires);
List<Commentaire> commentairesListe = new ArrayList<Commentaire>();
for (InterventionForum interventionForum : interventionForums) {
if (interventionForum instanceof Commentaire) {
commentairesListe.add((Commentaire) interventionForum);
}
}
return commentairesListe;
 
}
 
/**
* Recupere une liste d'interventions à partir du JSON
*
* @param imageJson
* @return
*/
public static List<InterventionForum> parserInterventions(JSONObject interventions) {
HashMap<String, InterventionForum> interventionsNonTypees = new HashMap<String, InterventionForum>();
 
List<InterventionForum> retour = new ArrayList<InterventionForum>();
 
// parcourir les interventions et en faire un tableau
if (interventions == null) {
return retour;
}
Iterator<String> itInterventions = interventions.keySet().iterator();
while (itInterventions.hasNext()) {
JSONObject jsonIntervention = interventions.get(itInterventions.next()).isObject();
String nomSel = getValeurOuVide(jsonIntervention, "nom_sel");
 
String id = getValeurOuVide(jsonIntervention, "id_commentaire");
String idParent = getValeurOuVide(jsonIntervention, "id_parent");
String texte = getValeurOuVide(jsonIntervention, "texte");
 
String idUtilisateur = getValeurOuVide(jsonIntervention, "auteur.id");
String nom = getValeurOuVide(jsonIntervention, "auteur.nom");
String prenom = getValeurOuVide(jsonIntervention, "auteur.prenom");
String courriel = getValeurOuVide(jsonIntervention, "auteur.courriel");
Contributeur contributeur = new Contributeur(idUtilisateur, nom, prenom, courriel);
Date date = parserDateObservation(getValeurOuVide(jsonIntervention, "date"));
 
if (!nomSel.equals("")) {
String nom_sel = getValeurOuVide(jsonIntervention, "nom_sel");
String nom_sel_nn = getValeurOuVide(jsonIntervention, "nom_sel_nn");
String nom_ret = getValeurOuVide(jsonIntervention, "nom_ret");
String nom_ret_nn = getValeurOuVide(jsonIntervention, "nom_ret_nn");
String famille = getValeurOuVide(jsonIntervention, "famille");
String nom_referentiel = getValeurOuVide(jsonIntervention, "nom_referentiel");
String nbCommentaires = getValeurOuVide(jsonIntervention, "nb_commentaires");
 
PropositionDetermination intervention = new PropositionDetermination(id, contributeur, texte);
String proposition_initiale = getValeurOuVide(jsonIntervention, "proposition_initiale");
if (proposition_initiale != null && proposition_initiale.equals("1")) {
intervention.setEstPropositionInitiale(true);
}
String proposition_retenue = getValeurOuVide(jsonIntervention, "proposition_retenue");
if (proposition_retenue != null && proposition_retenue.equals("1")) {
intervention.setEstPropositionRetenue(true);
}
intervention.setEspece(nom_sel);
 
if (!nbCommentaires.equals("")) {
int nbComm = Integer.parseInt(nbCommentaires);
intervention.setNbCommentaires(nbComm);
}
 
if (nom_sel_nn != null && !nom_sel_nn.equals("")) {
intervention.setNumNomenclatural(nom_sel_nn);
}
if(nom_referentiel != null && !nom_referentiel.equals("")) {
intervention.setReferentiel(nom_referentiel);
}
if (!idParent.equals("")) {
intervention.setIdParent(idParent);
}
 
if (jsonIntervention.get("votes") != null && jsonIntervention.get("votes").isObject() != null) {
intervention.setVotesDeterminations(parserVotesDetermination(jsonIntervention.get("votes").isObject()));
}
 
intervention.setDate(date);
interventionsNonTypees.put(intervention.getId(), intervention);
 
} else {
Commentaire intervention = new Commentaire(contributeur, date, texte);
intervention.setId(id);
intervention.setDate(date);
interventionsNonTypees.put(intervention.getId(), intervention);
if (!idParent.equals("")) {
intervention.setIdParent(idParent);
}
}
}
 
Iterator<String> itIntervention = interventionsNonTypees.keySet().iterator();
while (itIntervention.hasNext()) {
String id = itIntervention.next();
InterventionForum intervention = interventionsNonTypees.get(id);
String idParent = intervention.getIdParent();
if (idParent != null && !idParent.equals("") && !idParent.equals("0") && interventionsNonTypees.containsKey(idParent)) {
InterventionForum parent = interventionsNonTypees.get(idParent);
intervention.setParent(parent);
parent.ajouterCommentaire((Commentaire) intervention);
} else {
retour.add(intervention);
}
}
 
return retour;
}
 
/**
* Recupere une liste de commentaires à partir du JSON
*
* @param imageJson
* @return
*/
public static String convertirEtParserRetourAjoutCommentaire(String retour) {
JSONObject retourJson = JSONParser.parseStrict(retour).isObject();
return parserRetourAjoutCommentaire(retourJson);
}
 
/**
* Recupere une liste de commentaires à partir d'un objet JSON
*
* @param imageJson
* @return
*/
public static String parserRetourAjoutCommentaire(JSONObject retour) {
String id = "";
if (retour != null) {
id = getValeurOuVide(retour, "id_commentaire");
}
return id;
}
 
public static String getValeurOuVide(JSONObject objet, String index) {
return (objet.get(index) != null && objet.get(index).isString() != null) ? objet.get(index).isString().stringValue() : "";
}
 
/**
* Recupere une liste de votes sur une determination à partir du JSON
*
* @param imageJson
* @return
*/
public static HashMap<String, VoteDetermination> parserRetourListeVotesDetermination(String votesString) {
 
HashMap<String, VoteDetermination> retour = null;
 
JSONObject votes = JSONParser.parseStrict(votesString).isObject();
if (votes != null && votes.get("resultats") != null && votes.get("resultats").isObject() != null) {
JSONObject resultat = votes.get("resultats").isObject();
retour = parserVotesDetermination(resultat);
}
return retour;
}
 
/**
* Recupere une liste de votes sur une determination à partir d'un objet
* JSON
*
* @param imageJson
* @return
*/
public static HashMap<String, VoteDetermination> parserVotesDetermination(JSONObject votes) {
HashMap<String, VoteDetermination> votesDetermination = new HashMap<String, VoteDetermination>();
java.util.Iterator<String> itVotes = votes.keySet().iterator();
while (itVotes.hasNext()) {
JSONObject vote = votes.get(itVotes.next()).isObject();
VoteDetermination vd = new VoteDetermination();
vd.setContributeur(getValeurOuVide(vote, "auteur.id"));
vd.setDate(parserDateObservation(getValeurOuVide(vote, "date")));
vd.setId(getValeurOuVide(vote, "vote.id"));
vd.setVote(Integer.parseInt(getValeurOuVide(vote, "vote")));
vd.setContributeur(getValeurOuVide(vote, "auteur.id"));
 
if (vote.get("auteur.nom") != null && vote.get("auteur.nom") != null && vote.get("auteur.courriel") != null) {
Contributeur auteur = new Contributeur(getValeurOuVide(vote, "auteur.id"), getValeurOuVide(vote, "auteur.nom"), getValeurOuVide(vote, "auteur.prenom"), getValeurOuVide(vote, "auteur.courriel"));
vd.setAuteur(auteur);
}
 
votesDetermination.put(getValeurOuVide(vote, "auteur.id"), vd);
}
return votesDetermination;
}
 
/**
* Recupere une liste de votes sur des images à partir d'un objet JSON
*
* @param imageJson
* @return
*/
public static HashMap<String, HashMap<String, VoteProtocole>> parserVotesProtocoles(JSONObject votes) {
 
HashMap<String, HashMap<String, VoteProtocole>> votesProtocoles = new HashMap<String, HashMap<String, VoteProtocole>>();
java.util.Iterator<String> itProtocoles = votes.keySet().iterator();
while (itProtocoles.hasNext()) {
JSONObject protocole = votes.get(itProtocoles.next()).isObject();
JSONObject votesPourCeProtocoles = protocole.get("votes").isObject();
String idProtocoleVote = protocole.get("protocole.id").isString().stringValue();
java.util.Iterator<String> itVotes = votesPourCeProtocoles.keySet().iterator();
while (itVotes.hasNext()) {
JSONObject voteEnCours = votesPourCeProtocoles.get(itVotes.next()).isObject();
VoteProtocole vd = new VoteProtocole();
vd.setContributeur(voteEnCours.get("auteur.id").isString().stringValue());
vd.setId(voteEnCours.get("vote.id").isString().stringValue());
// TODO récupérer la date du vote et la parser
vd.setDate(parserDateObservation(getValeurOuVide(voteEnCours, "date")));
int valeurVote = Integer.parseInt(voteEnCours.get("vote").isString().stringValue());
vd.setVote(valeurVote);
if (!votesProtocoles.containsKey(idProtocoleVote)) {
votesProtocoles.put(idProtocoleVote, new HashMap<String, VoteProtocole>());
}
// un seul vote par utilisateur - garde le premier pour être cohérent avec commun/Stats (PHP)
if (! votesProtocoles.get(idProtocoleVote).containsKey(vd.getContributeur())) {
votesProtocoles.get(idProtocoleVote).put(vd.getContributeur(), vd);
}
}
}
 
return votesProtocoles;
}
 
/**
* Recupere une date à partir du JSON
*
* @param imageJson
* @return
*/
public static Date parserDateObservation(String date) {
Date dateParsee = new Date();
DateTimeFormat formatDateObs = DateTimeFormat.getFormat("yyyy-MM-dd HH:mm:ss");
try {
dateParsee = formatDateObs.parse(date);
} catch (IllegalArgumentException e) {
dateParsee = new java.sql.Date(0);
}
return dateParsee;
}
 
/**
* Recupere des mots-clefs à partir du JSON
*
* @param imageJson
* @return
*/
public static List<String> parserMotsCles(String motsClesTexte) {
String[] tabMotsCle = motsClesTexte.split(",");
List<String> motsClesParses = new ArrayList<String>();
for (int i = 0; i < tabMotsCle.length; i++) {
motsClesParses.add(tabMotsCle[i].trim());
}
 
return motsClesParses;
}
 
public static String getIdAvecPadding(String id) {
int maxZeros = 9 - id.length();
for (int i = 0; i < maxZeros; i++) {
id = "0" + id;
}
return id;
}
 
/**
* Recupere un utilisateur à partir du JSON
*
* @param imageJson
* @return
*/
public static Utilisateur parserUtilisateurJson(JSONValue valeurJson) {
JSONObject utilisateurJson = valeurJson.isObject();
boolean connecteUtilisateur = utilisateurJson.get("connecte").isBoolean().booleanValue();
String idUtilisateur = utilisateurJson.get("id_utilisateur").isString().stringValue();
String sessionId = utilisateurJson.get("session_id").isString().stringValue();
GWT.log(valeurJson.toString());
Utilisateur utilisateur;
if (connecteUtilisateur) {
String courrielUtilisateur = utilisateurJson.get("courriel").isString().stringValue();
String nomUtilisateur = utilisateurJson.get("nom").isString().stringValue();
String prenomUtilisateur = utilisateurJson.get("prenom").isString().stringValue();
String adminNiveau = "";
if (utilisateurJson.get("admin").isString() != null) {
adminNiveau = utilisateurJson.get("admin").isString().stringValue();
}
String nbEvtsUtilisateur = utilisateurJson.get("nb_evenements").isString().stringValue();
String dateDerniereConsultationEvts = utilisateurJson.get("date_derniere_consultation_evenements").isString().stringValue();
 
utilisateur = new Utilisateur(sessionId, idUtilisateur, prenomUtilisateur, nomUtilisateur,
courrielUtilisateur, adminNiveau);
ActiviteUtilisateur activite = new ActiviteUtilisateur();
activite.setNbEvenements(nbEvtsUtilisateur);
activite.setDateDerniereConsultationEvenements(dateDerniereConsultationEvts);
utilisateur.setActivite(activite);
} else {
utilisateur = new Utilisateur(sessionId, idUtilisateur);
}
return utilisateur;
}
 
/**
* Recupere des informations d'authentification à partir du JSON renvoyé par les
* services Auth de l'annuaire (SSO)
*
* @param valeurJson
* @return AuthInfo
*/
public static AuthInfo parserAuthJson(JSONValue valeurJson) {
AuthInfo authInfo = new AuthInfo();
JSONObject authJson = valeurJson.isObject();
 
JSONValue erreurJSON = authJson.get("error");
// test si erreur
if (erreurJSON != null) {
JSONString erreur = erreurJSON.isString();
if (erreur != null) {
authInfo.error = erreur.stringValue();
} else {
authInfo.error = "erreur d'authentification";
}
} else {
boolean session = authJson.get("session").isBoolean().booleanValue();
authInfo.session = session;
// test si session ouverte
if (session) {
JSONValue tokenJson = authJson.get("token");
String token = null;
// protection paranoïaque
if (tokenJson != null) {
JSONString tokenString = tokenJson.isString();
if (tokenString != null) {
token = tokenString.stringValue();
}
}
String tokenId = authJson.get("token_id").isString().stringValue();
int duration = (int) authJson.get("duration").isNumber().doubleValue();
JSONValue lastModifJson = authJson.get("last_modif");
 
authInfo.token = token;
authInfo.tokenId = tokenId;
authInfo.duration = duration;
// test si lastModif est null
if (lastModifJson != null) {
JSONNumber lastModif = lastModifJson.isNumber();
if (lastModif != null) {
authInfo.lastModif = (int) lastModif.doubleValue();
}
}
}
}
//GWT.log(valeurJson.toString());
return authInfo;
}
/**
* Recupere un utilisateur à partir du JSON
*
* @param imageJson
* @return
*/
public static HashMap<String, String> parserPreferencesUtilisateur(JSONValue valeurJson) {
JSONObject utilisateurJson = valeurJson.isObject();
HashMap<String, String> preferences = new HashMap<String, String>();
JSONObject preferencesJson = utilisateurJson.get("preferences").isObject();
java.util.Iterator<String> it = preferencesJson.keySet().iterator();
while (it.hasNext()) {
String cle = it.next();
preferences.put(cle, preferencesJson.get(cle).isString().stringValue());
}
return preferences;
}
 
/**
* Retourne un objet {@link ProtocoleServiceResultat} à partir d'un objet
* JSON
*
* @param retourJson
* @return
*/
public static ProtocoleServiceResultat parserProtocoleServiceResultat(JSONValue retourJson) {
List<Protocole> protocoles = new ArrayList<Protocole>();
JSONObject tableauProto = retourJson.isObject().get("resultats").isObject();
 
if (tableauProto != null) {
java.util.Iterator<String> it = tableauProto.keySet().iterator();
while (it.hasNext()) {
 
JSONObject protocoleJSON = tableauProto.get(it.next()).isObject();
Protocole protocole = new Protocole();
String idProtocole = UtilitairesServiceResultat.getValeurOuVide(protocoleJSON, "protocole.id");
protocole.setId(Integer.parseInt(idProtocole));
String doitEtreIdentifiePourVoter = UtilitairesServiceResultat.getValeurOuVide(protocoleJSON, "protocole.identifie");
boolean boolDoitEtreIdentifie = doitEtreIdentifiePourVoter.equals("1") ? true : false;
protocole.setDoitEtreIdentifiePourVoter(boolDoitEtreIdentifie);
protocole.setNom(UtilitairesServiceResultat.getValeurOuVide(protocoleJSON, "protocole.intitule"));
protocole.setDescription(UtilitairesServiceResultat.getValeurOuVide(protocoleJSON, "protocole.descriptif"));
protocole.setTag(UtilitairesServiceResultat.getValeurOuVide(protocoleJSON, "protocole.tag"));
protocole.setMotsClesProtocole(UtilitairesServiceResultat.getValeurOuVide(protocoleJSON, "protocole.mots_cles"));
protocoles.add(protocole);
}
}
 
return new ProtocoleServiceResultat(protocoles);
}
 
/**
* Retourne un objet {@link ImageServiceResultat} à partir du JSON
*
* @param retourJson
* @return
*/
public static ImageServiceResultat parserImageServiceResultat(JSONValue retourJson) {
 
ImageServiceResultat imageServiceResultat = new ImageServiceResultat();
int nbTotalImagesPourLaRecherche;
 
List<Image> images = new ArrayList<Image>();
// TODO ajouter vérifications plus précises
if (retourJson.isObject().get("entete") != null) {
double total = retourJson.isObject().get("entete").isObject().get("total").isNumber().doubleValue();
nbTotalImagesPourLaRecherche = (int) total;
// ATTENTION : "resultats" devrait contenir un array car il garantit l'ordre ce qui est important pour
// résultat de recherche. Migration progressive des ws pour qu'ils retourne un array et non un objet.
if (retourJson.isObject().get("resultats").isObject() != null) {
// TODO : supprimer cette condition quand tous les ws seront migrés vers array.
JSONObject tableauImg = retourJson.isObject().get("resultats").isObject();
if (tableauImg != null) {
java.util.Iterator<String> it = tableauImg.keySet().iterator();
while (it.hasNext()) {
JSONObject imageJson = tableauImg.get(it.next()).isObject();
Image image = parserRetourImage(imageJson);
images.add(image);
}
}
} else if (retourJson.isObject().get("resultats").isArray() != null) {
JSONArray tableauImg = retourJson.isObject().get("resultats").isArray();
if (tableauImg != null) {
int nbInfosImagesRetournees = (int) tableauImg.size();
for (int i = 0; i < nbInfosImagesRetournees; i++) {
JSONObject imageJson = tableauImg.get(i).isObject();
Image image = parserRetourImage(imageJson);
images.add(image);
}
}
}
} else {
JSONArray tableauImg = retourJson.isObject().get("images").isArray();
nbTotalImagesPourLaRecherche = (int) tableauImg.size();
for (int i = 0; i < nbTotalImagesPourLaRecherche; i++) {
JSONObject imageJson = tableauImg.get(i).isObject();
Image image = parserRetourImage(imageJson);
images.add(image);
}
}
 
imageServiceResultat.setImages(images);
imageServiceResultat.setNbTotalImagesPourLaRecherche(nbTotalImagesPourLaRecherche);
 
return imageServiceResultat;
 
}
 
/**
* Retourne un objet {@link Image} à partir du JSON
*
* @param retourJson
* @return
*/
public static Image parserRetourImage(JSONObject imageJson) {
Image image = UtilitairesServiceResultat.parserImageJSON(imageJson);
 
if (imageJson.get("observation") != null && imageJson.get("observation").isObject() != null) {
JSONObject observationJson = imageJson.get("observation").isObject();
image.setObservation(UtilitairesServiceResultat.parserObservationJSON(observationJson));
}
 
if (imageJson.get("protocoles_votes") != null && imageJson.get("protocoles_votes").isObject() != null) {
JSONObject votes = imageJson.get("protocoles_votes").isObject();
image.setVoteProtocoles(UtilitairesServiceResultat.parserVotesProtocoles(votes));
}
 
return image;
}
 
/**
* Retourne un objet {@link ObservationServiceResultat} à partir du JSON
*
* @param retourJson
* @return
*/
public static ObservationServiceResultat parserObservationServiceResultat(JSONValue retourJson) {
 
ObservationServiceResultat observationServiceResultat = new ObservationServiceResultat();
 
List<Observation> observations = new ArrayList<Observation>();
int nbTotalObservationsPourLaRecherche = 0;
 
if (retourJson.isObject().get("entete") != null) {
// TODO ajouter vérifications plus précises
double total = retourJson.isObject().get("entete").isObject().get("total").isNumber().doubleValue();
nbTotalObservationsPourLaRecherche = (int) total;
JSONArray tableauObs = retourJson.isObject().get("resultats").isArray();
 
if (tableauObs != null) {
for(int i = 0; i < tableauObs.size(); i++) {
JSONObject observationJson = tableauObs.get(i).isObject();
Observation observation = analyserObservation(observationJson);
observations.add(observation);
}
}
} else {
JSONObject observationJson = retourJson.isObject();
Observation observation = analyserObservation(observationJson);
observations.add(observation);
CacheClient.getInstance().setObservationCourante(observation);
}
 
observationServiceResultat.setObservations(observations);
observationServiceResultat.setNbTotalObservationsPourLaRecherche(nbTotalObservationsPourLaRecherche);
 
return observationServiceResultat;
}
 
/**
* Retourne un objet {@link Observation} avec ses {@link Image} associées à
* partir du JSON
*
* @param retourJson
* @return
*/
private static Observation analyserObservation(JSONObject observationJson) {
Observation observation = UtilitairesServiceResultat.parserObservationJSON(observationJson);
JSONArray tableauImagesObs = observationJson.get("images").isArray();
List<Image> imagesPourObs = new ArrayList<Image>();
 
int nbImages = tableauImagesObs.size();
for (int j = 0; j < nbImages; j++) {
JSONObject imageJson = tableauImagesObs.get(j).isObject();
 
Image image = UtilitairesServiceResultat.parserImageJSON(imageJson);
if (imageJson.get("protocoles_votes") != null && imageJson.get("protocoles_votes").isObject() != null) {
JSONObject votes = imageJson.get("protocoles_votes").isObject();
image.setVoteProtocoles(UtilitairesServiceResultat.parserVotesProtocoles(votes));
}
image.setObservation(observation);
imagesPourObs.add(image);
}
 
observation.setImages(imagesPourObs);
 
return observation;
}
 
public static List<MotCle> parserRetourListeMotsClesImage(JSONObject retourJson) {
List<MotCle> motsCles = new ArrayList<MotCle>();
JSONObject tableauMc = retourJson;
if (tableauMc != null) {
java.util.Iterator<String> it = tableauMc.keySet().iterator();
while (it.hasNext()) {
JSONObject mc = tableauMc.get(it.next()).isObject();
MotCle motCle = new MotCle(getValeurOuVide(mc, "id_mot_cle"), getValeurOuVide(mc, "image"), getValeurOuVide(mc, "mot_cle"));
motsCles.add(motCle);
}
}
return motsCles;
}
 
public static String parserRetourAjoutVoteProtocole(JSONObject retour) {
String id = "";
if (retour != null) {
id = getValeurOuVide(retour, "id_vote");
}
return id;
}
 
public static Map<String, String> parserListePays(JSONValue retourJson) {
Map<String, String> listePays = new LinkedHashMap<String, String>();
JSONArray tableauPays = retourJson.isArray();
int nbPays = (int) tableauPays.size();
for (int i = 0; i < nbPays; i++) {
JSONObject pays = tableauPays.get(i).isObject();
listePays.put(pays.get("code_iso_3166_1").isString().stringValue(), pays.get("nom_fr").isString().stringValue());
}
return listePays;
}
 
public static ActiviteUtilisateur parserActiviteUtilisateurJson(JSONValue valeurJson) {
JSONObject activiteJson = valeurJson.isObject();
String nbEvtsUtilisateur = activiteJson.get("nb_evenements").isString().stringValue();
String dateDerniereConsultationEvts = activiteJson.get("date_derniere_consultation_evenements").isString().stringValue();
 
ActiviteUtilisateur activite = new ActiviteUtilisateur();
activite.setNbEvenements(nbEvtsUtilisateur);
activite.setDateDerniereConsultationEvenements(dateDerniereConsultationEvts);
return activite;
}
}