Salome HOME
Menus are improved
[tools/siman.git] / Workspace / Siman / src / org / splat / simer / VersionDocumentAction.java
1 package org.splat.simer;
2
3 import java.io.File;
4 import java.io.FileNotFoundException;
5 import java.text.ParseException;
6 import java.text.SimpleDateFormat;
7 import java.util.HashSet;
8 import java.util.Iterator;
9 import java.util.List;
10 import java.util.ResourceBundle;
11 import java.util.Vector;
12
13 import org.hibernate.HibernateException;
14 import org.hibernate.Session;
15 import org.hibernate.Transaction;
16 import org.splat.kernel.InvalidPropertyException;
17 import org.splat.dal.bo.kernel.Relation;
18 import org.splat.dal.bo.kernel.User;
19 import org.splat.manox.Reader;
20 import org.splat.manox.Toolbox;
21 import org.splat.dal.dao.som.Database;
22 import org.splat.dal.bo.som.Document;
23 import org.splat.dal.bo.som.ProgressState;
24 import org.splat.service.PublicationService;
25 import org.splat.service.StepService;
26 import org.splat.service.technical.ProjectSettingsService;
27 import org.splat.service.technical.RepositoryService;
28 import org.splat.dal.bo.som.Publication;
29 import org.splat.som.Revision;
30 import org.splat.som.Step;
31 import org.splat.dal.bo.som.UsedByRelation;
32 import org.splat.dal.bo.som.UsesRelation;
33
34 public class VersionDocumentAction extends UploadBaseNextAction {
35
36         private String index = null; // Versioned document index
37         private List<Publication> usedby = null;
38         private String docusedby = null;
39         private String summary = null; // Summary of changes in the new version
40         private String docver = ""; // Version number extracted from the imported file, if exist
41         private String date = ""; // Date extracted from the imported file, if exist
42         private ProjectSettingsService _projectSettingsService;
43         private PublicationService _publicationService;
44         private StepService _stepService;
45         /**
46          * Injected repository service.
47          */
48         private RepositoryService _repositoryService;
49         /**
50          * Value of the menu property. 
51          * It can be: none, create, open, study, knowledge, sysadmin, help.
52          */
53         private String _menuProperty;
54
55         /**
56          * Serial version ID.
57          */
58         private static final long serialVersionUID = -5702264003232132168L;
59
60         // ==============================================================================================================================
61         // Action methods
62         // ==============================================================================================================================
63
64         public String doInitialize() {
65                 // -----------------------------
66                 
67                 setMenuProperty("study");
68             initializationScreenContext(_menuProperty);
69             
70                 Session connex = Database.getCurSession();
71                 Transaction transax = connex.beginTransaction();
72                 User user = getConnectedUser();
73                 File updir = getRepositoryService().getDownloadDirectory(user);
74                 File upfile = new File(updir.getPath() + "/" + filename);
75
76                 mystudy = getOpenStudy();
77
78                 Publication tag = mystudy.getSelectedStep().getDocument(
79                                 Integer.valueOf(index));
80                 Document doc = tag.value();
81                 deftype = doc.getType();
82                 docname = doc.getTitle();
83                 defuses = new Vector<Document>();
84                 usedby = new Vector<Publication>();
85
86                 Reader tool = Toolbox.getReader(upfile);
87                 if (tool != null) {
88                         String fileref = tool.extractProperty("reference");
89                         String filever = tool.extractProperty("version");
90                         if (fileref != null && !doc.getReference().equals(fileref)) {
91                                 setErrorCode("reference.mismatch");
92                                 return ERROR;
93                         }
94                         if (filever != null)
95                                 try {
96                                         Revision.Format get = new Revision.Format(
97                                                         getProjectSettings().getRevisionPattern());
98                                         Revision newver = get.parse(filever);
99                                         Revision oldver = new Revision(doc.getVersion());
100                                         if (!newver.isGraterThan(oldver))
101                                                 throw new InvalidPropertyException("version");
102                                         if (newver.isMinor())
103                                                 state = ProgressState.inWORK;
104                                         else
105                                                 state = ProgressState.inDRAFT;
106                                         docver = newver.toString();
107                                 } catch (Exception e) {
108                                         setErrorCode("version.mismatch");
109                                         return ERROR;
110                                 }
111                         summary = tool.extractProperty("history");
112                         date = tool.extractProperty("date");
113                         if (date != null) {
114                                 ResourceBundle locale = ResourceBundle.getBundle("som",
115                                                 ApplicationSettings.getCurrentLocale());
116                                 SimpleDateFormat check = new SimpleDateFormat(
117                                                 locale.getString("date.format"));
118                                 try {
119                                         check.parse(date);
120                                 } catch (ParseException e) {
121                                         setErrorCode("format.date");
122                                         return ERROR;
123                                 }
124                         } else
125                                 date = "";
126                 }
127                 setupDefaultUses(deftype);
128                 // Add additional documents used by the current version
129                 List<Relation> uses = doc.getRelations(UsesRelation.class);
130                 for (Iterator<Relation> i = uses.iterator(); i.hasNext();) {
131                         Document used = (Document) i.next().getTo();
132                         if (!defuses.contains(used))
133                                 defuses.add(used);
134                 }
135                 // Setup dependencies
136                 List<Publication> relist = tag.getRelations(UsedByRelation.class);
137                 for (Iterator<Publication> i = relist.iterator(); i.hasNext();) {
138                         usedby.add(i.next());
139                 }
140                 transax.commit();
141                 return SUCCESS;
142         }
143
144         public String doVersion() {
145                 // -------------------------
146                 setMenuProperty("study");
147             initializationScreenContext(_menuProperty);
148             
149                 if (action == ToDo.cancel)
150                         return "cancel";
151
152                 Session connex = Database.getCurSession();
153                 Transaction transax = connex.beginTransaction();
154                 try {
155                         // Getting user inputs
156                         mystudy = getOpenStudy();
157                         User user = getConnectedUser();
158                         Step step = mystudy.getSelectedStep();
159                         File updir = getRepositoryService().getDownloadDirectory(user);
160                         File upfile = new File(updir.getPath() + "/" + filename);
161
162                         // Versioning of the document
163                         Document.Properties dprop = new Document.Properties();
164                         Publication current = step.getDocument(Integer.valueOf(index));
165                         Publication next;
166
167                         if (docver.length() == 0) { // Importation of a foreign document
168                                 next = getStepService().versionDocument(step, current, dprop.setAuthor(user)
169                                                 .setDescription(summary));
170                                 updir = next.getSourceFile().asFile();
171                                 if (logger.isInfoEnabled())
172                                         logger.info("Moving \"" + upfile.getName() + "\" to \""
173                                                         + updir.getPath() + "\".");
174                                 upfile.renameTo(updir);
175                                 try {
176                                         getPublicationService().saveAs(next, state); // May throw FileNotFound if rename was not done
177                                 } catch (FileNotFoundException saverror) {
178                                         Thread.sleep(1000);
179                                         logger.info("Waiting for the file.");
180                                         upfile.renameTo(updir);
181                                         getPublicationService().saveAs(next, state); // Forget it if throw again FileNotFound
182                                 }
183                         } else {
184                                 if (date.length() > 0) {
185                                         ResourceBundle locale = ResourceBundle.getBundle("som",
186                                                         ApplicationSettings.getCurrentLocale());
187                                         SimpleDateFormat get = new SimpleDateFormat(
188                                                         locale.getString("date.format"));
189                                         dprop.setDate(get.parse(date));
190                                 }
191                                 next = getStepService().versionDocument(step, current, dprop.setAuthor(user)
192                                                 .setDescription(summary));
193                                 updir = next.getSourceFile().asFile();
194                                 if (logger.isInfoEnabled())
195                                         logger.info("Moving \"" + upfile.getName() + "\" to \""
196                                                         + updir.getPath() + "\".");
197                                 upfile.renameTo(updir);
198                                 try {
199                                         getPublicationService().saveAs(next, new Revision(docver));
200                                 } catch (FileNotFoundException saverror) {
201                                         Thread.sleep(1000);
202                                         logger.info("Waiting for the file.");
203                                         upfile.renameTo(updir);
204                                         getPublicationService().saveAs(next, state);
205                                 }
206                         }
207                         // TODO: Remove current document details from the contents of open study
208
209                         // Creation of uses relations
210                         if (docuses != null) {
211                                 String[] list = docuses.split(",");
212                                 for (int i = 0; i < list.length; i++) {
213                                         Integer index = Integer.valueOf(list[i].trim());
214                                         Publication used = getPublication(index);
215                                         next.addDependency(used);
216                                 }
217                         }
218                         // Outdating impacted document
219                         HashSet<Integer> compatible = new HashSet<Integer>();
220                         if (docusedby != null) {
221                                 String[] list = docusedby.split(",");
222                                 for (int i = 0; i < list.length; i++)
223                                         compatible.add(Integer.valueOf(list[i].trim()));
224                         }
225                         List<Publication> relist = current
226                                         .getRelations(UsedByRelation.class);
227                         for (Iterator<Publication> i = relist.iterator(); i.hasNext();) {
228                                 Publication using = i.next();
229                                 if (!compatible.contains(using.getIndex()))
230                                         getPublicationService().outdate(using);
231                         }
232                         // Update of the open study
233                         mystudy.setSelection(mystudy.getSelection()); // Rebuilds the presentation
234                         // TODO: Look is an optimization is possible (for example by updating the presentation of versioned document)
235
236                         transax.commit();
237                         return SUCCESS;
238                 } catch (FileNotFoundException error) {
239                         logger.error("Reason:", error);
240                         setErrorCode("import.file");
241                 } catch (Exception error) {
242                         logger.error("Reason:", error);
243                         setErrorCode("internal");
244                 }
245                 if (transax != null && transax.isActive()) {
246                         // Second try-catch as the rollback could fail as well
247                         try {
248                                 transax.rollback();
249                         } catch (HibernateException backerror) {
250                                 logger.debug("Error rolling back transaction", backerror);
251                         }
252                 }
253                 return ERROR;
254         }
255
256         // ==============================================================================================================================
257         // Getters and setters
258         // ==============================================================================================================================
259
260         public String getDate() {
261                 // ------------------------
262                 return date;
263         }
264
265         public List<Publication> getDependencies() {
266                 // -------------------------------------------
267                 return usedby;
268         }
269
270         public String getDescription() {
271                 // -------------------------------
272                 return summary;
273         }
274
275         public String getIndex() {
276                 // -------------------------
277                 return index;
278         }
279
280         public String getVersion() {
281                 // ---------------------------
282                 return docver;
283         }
284
285         public void setDate(String date) {
286                 // ---------------------------------
287                 this.date = date;
288         }
289
290         public void setDefaultDescription(String summary) {
291                 // --------------------------------------------------
292                 if (this.summary == null)
293                         this.summary = summary;
294         }
295
296         public void setDescription(String summary) {
297                 // -------------------------------------------
298                 this.summary = summary;
299         }
300
301         public void setIndex(String index) {
302                 // -----------------------------------
303                 this.index = index;
304         }
305
306         public void setUsedBy(String list) {
307                 // -----------------------------------
308                 this.docusedby = list;
309         }
310
311         public void setVersion(String value) {
312                 // -------------------------------------
313                 this.docver = value;
314         }
315
316         /**
317          * Get project settings.
318          * 
319          * @return Project settings service
320          */
321         private ProjectSettingsService getProjectSettings() {
322                 return _projectSettingsService;
323         }
324
325         /**
326          * Set project settings service.
327          * 
328          * @param projectSettingsService
329          *            project settings service
330          */
331         public void setProjectSettings(ProjectSettingsService projectSettingsService) {
332                 _projectSettingsService = projectSettingsService;
333         }
334
335         /**
336          * Get the publicationService.
337          * 
338          * @return the publicationService
339          */
340         public PublicationService getPublicationService() {
341                 return _publicationService;
342         }
343
344         /**
345          * Set the publicationService.
346          * 
347          * @param publicationService
348          *            the publicationService to set
349          */
350         public void setPublicationService(PublicationService publicationService) {
351                 _publicationService = publicationService;
352         }
353
354         /**
355          * Get the stepService.
356          * @return the stepService
357          */
358         public StepService getStepService() {
359                 return _stepService;
360         }
361
362         /**
363          * Set the stepService.
364          * @param stepService the stepService to set
365          */
366         public void setStepService(StepService stepService) {
367                 _stepService = stepService;
368         }
369
370         /**
371          * Get the repositoryService.
372          * @return the repositoryService
373          */
374         public RepositoryService getRepositoryService() {
375                 return _repositoryService;
376         }
377
378         /**
379          * Set the repositoryService.
380          * @param repositoryService the repositoryService to set
381          */
382         public void setRepositoryService(RepositoryService repositoryService) {
383                 _repositoryService = repositoryService;
384         }
385         
386         /**
387          * Get the menuProperty.
388          * @return the menuProperty
389          */
390         public String getMenuProperty() {
391                 return _menuProperty;
392         }
393
394         /**
395          * Set the menuProperty.
396          * @param menuProperty the menuProperty to set
397          */
398         public void setMenuProperty(String menuProperty) {
399                 this._menuProperty = menuProperty;
400         }
401 }