source: ether_megapoli/trunk/service/implementation/com/medias/megapoli/struts/actions/UpdateMetadataAction.java @ 151

Last change on this file since 151 was 151, checked in by vmipsl, 13 years ago

Import medias files and cleanup

File size: 15.0 KB
Line 
1/*
2 * Created on 16 févr. 2005
3 *
4 * TODO To change the template for this generated file go to
5 * Window - Preferences - Java - Code Style - Code Templates
6 */
7package com.medias.megapoli.struts.actions;
8
9import java.io.File;
10import java.io.FileOutputStream;
11import java.io.IOException;
12import java.io.InputStream;
13import java.io.OutputStream;
14import java.lang.reflect.Method;
15import java.util.ArrayList;
16import java.util.HashMap;
17import java.util.Map;
18
19import javax.servlet.ServletException;
20import javax.servlet.http.HttpServletRequest;
21import javax.servlet.http.HttpServletResponse;
22
23import org.apache.struts.action.Action;
24import org.apache.struts.action.ActionError;
25import org.apache.struts.action.ActionErrors;
26import org.apache.struts.action.ActionForm;
27import org.apache.struts.action.ActionForward;
28import org.apache.struts.action.ActionMapping;
29import org.apache.struts.action.ActionMessage;
30import org.apache.struts.action.ActionMessages;
31import org.apache.struts.upload.FormFile;
32import com.medias.annuaire.Annuaire;
33import com.medias.xml.hierarchie.Hierarchie;
34import com.medias.xml.metadata.Capteur;
35import com.medias.xml.metadata.Contact;
36import com.medias.xml.metadata.Metadata;
37import com.medias.xml.metadata.Parametre;
38import com.medias.xml.metadata.Plateforme;
39import com.medias.megapoli.struts.forms.MetadataForm;
40import com.medias.megapoli.utils.MegapoliInitialisation;
41import com.medias.Context;
42import com.medias.Nombre;
43import com.medias.mail.Mail;
44import com.medias.mail.MailFactory;
45
46
47/**
48 * @author combaz
49 *
50 * TODO To change the template for this generated type comment go to
51 * Window - Preferences - Java - Code Style - Code Templates
52 */
53public class UpdateMetadataAction extends Action {
54   
55        public ActionForward execute(ActionMapping mapping,ActionForm form,
56                        HttpServletRequest request, HttpServletResponse response)
57                throws ServletException {
58                String target = "failure";
59                HashMap<String, String> map = (HashMap<String, String>)this.getKeyMethodMap();
60                ActionErrors errors = new ActionErrors();
61                ActionMessages mess = new ActionMessages();
62                if(this.isCancelled(request)) {
63                        target = "cancel";
64                } else if(form!=null) {
65                        MetadataForm mform = (MetadataForm)form;
66
67                        //on récupÚre les messages envoyés par la vue et on les analyse...
68                        String message = mform.getMessText();
69                        Integer idx = mform.getMessIdx();
70                        String methodName = (String)map.get(message);
71                        // Si on veut effacer des images
72                        String idPI = (String)request.getParameter("idPI");
73                        if (idPI != null) {
74                                methodName = "removeFile";
75                            idx = new Integer(idPI.substring(idPI.indexOf("_")+1));
76                        }
77                        Metadata metadata = mform.getMetadata();
78                        Hierarchie tree = (Hierarchie) this.getServlet().getServletContext().getAttribute("APP_UPLOADTREE");
79                        //si, d'aprÚs les messages récupérés, une méthode particuliÚre doit être appliquée sur la métadonnée, on l'appelle
80                        if(methodName!=null) {
81                                try {
82                                        Class<?>[] paramClasses = null;
83                                        Object[] params = null;
84                                        if(methodName.startsWith("remove")) {
85                                                paramClasses = new Class[1];
86                                                paramClasses[0] = idx.getClass();
87                                                params = new Object[1];
88                                                params[0] = idx;
89                                        }
90                                        target="input";
91                                        if(methodName.equals("removeFile")) {
92                                                ArrayList<Plateforme> plats = metadata.getContenuPrevu().getPlateformes();
93                                                int idPlat = new Integer(idPI.substring(0,idPI.indexOf("_"))).intValue();
94                                                Method method = Plateforme.class.getMethod(methodName, paramClasses);
95                                                String filename = (String)method.invoke(plats.get(idPlat),params);
96                                                String cheminFic = MegapoliInitialisation.pathImages+"/"+metadata.getRelativePath();
97                                                boolean imgPresent = false;
98                                                for (Object plat: plats) {
99                                                        Object[] listeimg = ((Plateforme)plat).getListe_images();
100                                                        for (Object img: listeimg) {
101                                                                if (((String)img).equals(filename)) {
102                                                                        imgPresent = true;
103                                                                }
104                                                        }
105                                                }
106                                                File fichier = new File(cheminFic+"/"+filename);
107                                                if (!imgPresent) fichier.delete();
108                                                File fChemin = new File(cheminFic);
109                                                if (fChemin.listFiles().length==0) fChemin.delete();
110                                        }
111                                        else if(methodName.equals("setNewFile")){
112//                                                      &&  mform.getNewFile().getFileName().length() != 0) {
113                                                String path = mform.getSetPath();
114                                                FormFile file =mform.getNewFile();
115//                                              System.out.println(path);
116//                                              System.out.println(file.getFileName());
117                                                if(file != null && file.getFileSize()!=0 && path.length()!=0) {
118                                                        metadata.getContenuPrevu().getPlateformes().get(idx).getListe_imagesList().add(file.getFileName());
119                                                        try {
120                                                                copyFile(path,file);
121                                                                mess.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("data.upload.succeded"));
122                                                        }
123                                                        catch(Exception e){
124                                                                errors.add(ActionErrors.GLOBAL_MESSAGE, new ActionError("errors.upload.failed"));
125                                                                e.printStackTrace();
126                                                        }
127                                                } else {
128                                                        errors.add(ActionErrors.GLOBAL_MESSAGE, new ActionError("errors.upload.file"));
129                                                }
130                                                mform.setNewFile(null);
131                                        }
132//                                      else if(methodName.endsWith("Contact")) {
133//                                              Presentation pres = metadata.getPres();
134//                                              Method method = pres.getClass().getMethod(methodName, paramClasses);
135//                                              method.invoke(pres,params);
136//                                      }
137//                                      else {
138//                                              Contenu content = metadata.getContenuPrevu();
139//                                              Method method = content.getClass().getMethod(methodName, paramClasses);
140//                                              method.invoke(content,params);
141//                                      }
142                                        metadata.createXmlFile();
143                                }
144                                catch(Exception e) {
145                                        errors.add(ActionErrors.GLOBAL_MESSAGE, new ActionError("errors.upload.updateMetadata.failed",Context.getWebmaster(request)));
146                                        e.printStackTrace();
147                                }
148                        }
149
150                       
151                        //sinon: on a affaire à un submit tout simple.
152                        else {
153                                /* Vérification : un seul contact par type (1 PI et un technicien) et un mot de passe par contact */
154                                switch (metadata.updateContacts()) {
155                                        case Metadata.CONTACT_PI:
156                                                errors.add(ActionErrors.GLOBAL_MESSAGE, new ActionError("errors.upload.updateMetadata.failed.contact_pi"));
157                                                break;
158                                        case Metadata.CONTACT_TECH:
159                                                errors.add(ActionErrors.GLOBAL_MESSAGE, new ActionError("errors.upload.updateMetadata.failed.contact_tech"));
160                                                break;
161                                        case Metadata.CONTACT_WRONG:
162                                                errors.add(ActionErrors.GLOBAL_MESSAGE, new ActionError("errors.upload.updateMetadata.failed.pwd"));
163                                                break;
164                                        default:
165                                }
166                                boolean complet = true;
167                                if (errors.isEmpty()){
168                                        // Organisme obligatoire
169                                        if (metadata.getDesc().getOrganisme().equals(""))
170                                                complet = false;
171                                        // Au moins une personne doit avoir le rÃŽle de PI ou contact technique
172                                        boolean isRole = false;
173                                        for (Contact pers : metadata.getPres().getContactsList()) {
174                                                if (pers.getRole().equals("pi") || pers.getRole().equals("tech")) {
175                                                        isRole = true;
176                                                        break;
177                                                }
178                                        }
179                                        if (!isRole) complet = false;
180                                        ArrayList<Plateforme> plats = metadata.getContenuPrevu().getPlateformes();
181                                        for (Plateforme plat: plats) {
182                                                plat.formToModel();
183                                                if (plat.getNom().equals("")) {
184                                                        complet = false;
185//                                                      errors.add(ActionErrors.GLOBAL_MESSAGE, new ActionError("errors.upload.updateMetadata.failed.plat"));
186//                                                      break;
187                                                }
188                                                if (!plat.getLat_min().equals("") && !Nombre.isDoubleInInterval(plat.getLat_min(), -90, 90)) {
189                                                        errors.add(ActionErrors.GLOBAL_MESSAGE, new ActionError("errors.upload.updateMetadata.failed.lat"));
190                                                        break;
191                                                }
192                                                if (!plat.getLat_max().equals("") && !Nombre.isDoubleInInterval(plat.getLat_max(), -90, 90)) {
193                                                        errors.add(ActionErrors.GLOBAL_MESSAGE, new ActionError("errors.upload.updateMetadata.failed.lat"));
194                                                        break;
195                                                }
196                                                if (!plat.getLon_min().equals("") && !Nombre.isDoubleInInterval(plat.getLon_min(), -180, 180)) {
197                                                        errors.add(ActionErrors.GLOBAL_MESSAGE, new ActionError("errors.upload.updateMetadata.failed.lon"));
198                                                        break;
199                                                }
200                                                if (!plat.getLon_max().equals("") && !Nombre.isDoubleInInterval(plat.getLon_max(), -180, 180)) {
201                                                        errors.add(ActionErrors.GLOBAL_MESSAGE, new ActionError("errors.upload.updateMetadata.failed.lon"));
202                                                        break;
203                                                }
204                                                if (!plat.getAlt_min().equals("") && !Nombre.isDoubleInInterval(plat.getAlt_min(), 0, Double.MAX_VALUE)) {
205                                                        errors.add(ActionErrors.GLOBAL_MESSAGE, new ActionError("errors.upload.updateMetadata.failed.alt"));
206                                                        break;
207                                                }
208                                                if (!plat.getAlt_max().equals("") && !Nombre.isDoubleInInterval(plat.getAlt_max(), 0, Double.MAX_VALUE)) {
209                                                        errors.add(ActionErrors.GLOBAL_MESSAGE, new ActionError("errors.upload.updateMetadata.failed.alt"));
210                                                        break;
211                                                }
212                                                if (!plat.getLat_min().equals("") && !plat.getLat_max().equals("") && Double.parseDouble(plat.getLat_min()) > Double.parseDouble(plat.getLat_max())) {
213                                                        errors.add(ActionErrors.GLOBAL_MESSAGE, new ActionError("errors.upload.updateMetadata.failed.latbound"));
214                                                        break;
215                                                }
216                                                if (!plat.getLon_min().equals("") && !plat.getLon_max().equals("") && Double.parseDouble(plat.getLon_min()) > Double.parseDouble(plat.getLon_max())) {
217                                                        errors.add(ActionErrors.GLOBAL_MESSAGE, new ActionError("errors.upload.updateMetadata.failed.lonbound"));
218                                                        break;
219                                                }
220                                                if (!plat.getAlt_min().equals("") && !plat.getAlt_max().equals("") && Double.parseDouble(plat.getAlt_min()) > Double.parseDouble(plat.getAlt_max())) {
221                                                        errors.add(ActionErrors.GLOBAL_MESSAGE, new ActionError("errors.upload.updateMetadata.failed.altbound"));
222                                                        break;
223                                                }
224                                        }
225                                }
226                                if (errors.isEmpty()){
227                                ArrayList<Capteur> capts = metadata.getContenuPrevu().getCapteurs();
228                                        for (Capteur capt: capts) {
229                                                capt.formToModel();
230//                                              if (capt.getFabriquant().equals("")) {
231//                                                      complet = false;
232//                                                      errors.add(ActionErrors.GLOBAL_MESSAGE, new ActionError("errors.upload.updateMetadata.failed.captfab"));
233//                                                      break;
234//                                              }
235                                                if (capt.getType().equals("")) {
236                                                        complet = false;
237//                                                      errors.add(ActionErrors.GLOBAL_MESSAGE, new ActionError("errors.upload.updateMetadata.failed.capttype"));
238//                                                      break;
239                                                }
240//                                              if (capt.getModele().equals("")) {
241//                                                      complet = false;
242//                                                      errors.add(ActionErrors.GLOBAL_MESSAGE, new ActionError("errors.upload.updateMetadata.failed.captmodel"));
243//                                                      break;
244//                                              }
245//                                              if (capt.getNum().equals("")) {
246//                                                      complet = false;
247//                                                      errors.add(ActionErrors.GLOBAL_MESSAGE, new ActionError("errors.upload.updateMetadata.failed.captnum"));
248//                                                      break;
249//                                              }
250                                        }
251                                }
252                                if (errors.isEmpty()){
253                                        ArrayList<Parametre> params = metadata.getContenuPrevu().getParams();
254                                        for (Parametre param: params) {
255                                                param.formToModel();
256                                                if (param.getNom().equals("")) {
257                                                        complet = false;
258//                                                      errors.add(ActionErrors.GLOBAL_MESSAGE, new ActionError("errors.upload.updateMetadata.failed.paramnom"));
259//                                                      break;
260                                                }
261                                                if (param.getCategorie().equals("")) {
262                                                        complet = false;
263//                                                      errors.add(ActionErrors.GLOBAL_MESSAGE, new ActionError("errors.upload.updateMetadata.failed.paramabrev"));
264//                                                      break;
265                                                }
266//                                              if (param.getAbrev().equals("")) {
267//                                                      complet = false;
268//                                                      errors.add(ActionErrors.GLOBAL_MESSAGE, new ActionError("errors.upload.updateMetadata.failed.paramabrev"));
269//                                                      break;
270//                                              }
271                                                if (param.getUnite().equals("")) {
272                                                        complet = false;
273//                                                      errors.add(ActionErrors.GLOBAL_MESSAGE, new ActionError("errors.upload.updateMetadata.failed.paramunite"));
274//                                                      break;
275                                                }
276                                        }
277                                }
278                                if (errors.isEmpty()) {
279                                    target = "success";
280                                        //on met à jour l'annuaire, au cas où de nouveaux contacts aient été créés...
281                                        Annuaire annu = (Annuaire) this.getServlet().getServletContext().getAttribute("APP_ANNUAIRE");
282                                        try {
283                                                annu.update(metadata,mess);
284                                        }
285                                        catch(Exception e) {
286                                                System.out.println ("exception3");
287                                                errors.add(ActionErrors.GLOBAL_MESSAGE, new ActionError("errors.upload.newSet.updateAnnu.failed",Context.getWebmaster(request)));
288                                                e.printStackTrace();
289                                        }
290                                        try{
291                                                //on remet à jour la hiérarchie, au cas où le nom du jeu ait changé...
292                                                tree.synchronize(metadata, complet);
293                                               
294                                                //Envoi d'un mail automatique au webmaster
295                                                MailFactory mf = (MailFactory) this.servlet.getServletContext().getAttribute("APP_MAILFACTORY");
296                                                String from = "megapoli_info@obs-mip.fr";
297                                                String to = Context.getWebmaster(request);
298                                                String subject = "[MEGAPOLI] Metadonnees du jeu '"+metadata.getPres().getNom()+"' mises a jour ("+(complet?"complet":"incomplet")+")";
299                                                Mail mail = new Mail(from, to, null, "", subject);
300                                                mf.sendMail(mail);
301                                               
302                                                metadata.createXmlFile();
303                                                mess.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("data.upload.updateMetadata.succeded"));
304                                        }
305                                        catch(Exception e) {
306                                                errors.add(ActionErrors.GLOBAL_MESSAGE, new ActionError("errors.upload.updateMetadata.failed",Context.getWebmaster(request)));
307                                                e.printStackTrace();
308                                        }
309                                        //on remet les messages à zéro
310                                        mform.initMess();
311                                }
312                        }
313                }
314                       
315
316                if(!errors.isEmpty()){
317                        target = "failure";
318                        saveErrors(request, errors);
319                }
320
321                if(!mess.isEmpty()){
322                        saveMessages(request, mess);
323                }
324                return mapping.findForward(target);
325        }
326       
327        protected Map<String, String> getKeyMethodMap() {
328              Map<String, String> map = new HashMap<String, String>();
329              map.put("Ajouter un parametre", "addParam");
330              map.put("Add a parameter", "addParam");
331              map.put("Ajouter une plate-forme", "addPlateforme");
332              map.put("Add a platform", "addPlateforme");
333              map.put("Ajouter un capteur", "addCapteur");
334              map.put("Add a sensor", "addCapteur");
335              map.put("Ajouter un contact", "addContact");
336              map.put("Add a contact", "addContact");
337              map.put("Delete this contact", "removeContact");
338              map.put("Supprimer ce contact", "removeContact");
339              map.put("Delete this platform", "removePlateforme");
340              map.put("Supprimer cette plate-forme", "removePlateforme");
341              map.put("Delete this parameter", "removeParam");
342              map.put("Supprimer ce parametre", "removeParam");
343              map.put("Delete this sensor", "removeCapteur");
344              map.put("Supprimer ce capteur", "removeCapteur");
345              map.put("Delete this picture", "removeFile");
346              map.put("Supprimer cette image", "removeFile");
347              map.put("Deposer", "setNewFile");
348              map.put("Upload", "setNewFile");
349              return map;
350          }
351       
352        /**
353         * Enregistre le fichier file à sa place dans l'arborescence...
354         * @param filePath La place dans l'arborescence a laquelle on veut enregistrer le fichier
355         * @param file Le fichier a enregistrer
356         * @return target Le resultat de l'operation (success ou failure)
357         * @throws UploadException
358         */
359        public void copyFile(String filePath, FormFile file) throws IOException {
360                InputStream input = file.getInputStream();
361                String cheminJeu = MegapoliInitialisation.pathImages+"/"+filePath;
362                File fJeu = new File(cheminJeu);
363                if (!fJeu.exists()) {
364                    fJeu.mkdirs();
365                }
366                OutputStream output = new FileOutputStream(cheminJeu+"/"+file.getFileName());
367                int bytesRead = 0;
368                byte[] buffer = new byte[2048];
369                while ((bytesRead = input.read(buffer, 0, 2048)) != -1){
370                        output.write(buffer,0,bytesRead);
371                }
372                output.close();
373                input.close();
374        }
375}
Note: See TracBrowser for help on using the repository browser.