Salome HOME
529d48aa84a351f007dd0819f2bff18ac769d3ff
[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          * Value of the title bar property. 
57          * It can be: study, knowledge.
58          */
59         private String _titleProperty;
60         
61         /**
62          * Property that indicates whether the current open study is editable or not.
63          * On the screen it looks like pen on the status icon, pop-up menu also can be called.
64          * It is necessary for correct building the title bar.
65          */
66         private String _editDisabledProperty = "false";
67
68         /**
69          * Serial version ID.
70          */
71         private static final long serialVersionUID = -5702264003232132168L;
72
73         // ==============================================================================================================================
74         // Action methods
75         // ==============================================================================================================================
76
77         public String doInitialize() {
78                 // -----------------------------
79                 
80                 setMenuProperty("study");
81                 setTitleProperty("study");
82                 setEditDisabledProperty("true");
83         initializationScreenContext(_menuProperty, _titleProperty, _editDisabledProperty);
84             
85                 Session connex = Database.getCurSession();
86                 Transaction transax = connex.beginTransaction();
87                 User user = getConnectedUser();
88                 File updir = getRepositoryService().getDownloadDirectory(user);
89                 File upfile = new File(updir.getPath() + "/" + filename);
90
91                 mystudy = getOpenStudy();
92
93                 Publication tag = mystudy.getSelectedStep().getDocument(
94                                 Integer.valueOf(index));
95                 Document doc = tag.value();
96                 deftype = doc.getType();
97                 docname = doc.getTitle();
98                 defuses = new Vector<Document>();
99                 usedby = new Vector<Publication>();
100
101                 Reader tool = Toolbox.getReader(upfile);
102                 if (tool != null) {
103                         String fileref = tool.extractProperty("reference");
104                         String filever = tool.extractProperty("version");
105                         if (fileref != null && !doc.getReference().equals(fileref)) {
106                                 setErrorCode("reference.mismatch");
107                                 return ERROR;
108                         }
109                         if (filever != null)
110                                 try {
111                                         Revision.Format get = new Revision.Format(
112                                                         getProjectSettings().getRevisionPattern());
113                                         Revision newver = get.parse(filever);
114                                         Revision oldver = new Revision(doc.getVersion());
115                                         if (!newver.isGraterThan(oldver))
116                                                 throw new InvalidPropertyException("version");
117                                         if (newver.isMinor())
118                                                 state = ProgressState.inWORK;
119                                         else
120                                                 state = ProgressState.inDRAFT;
121                                         docver = newver.toString();
122                                 } catch (Exception e) {
123                                         setErrorCode("version.mismatch");
124                                         return ERROR;
125                                 }
126                         summary = tool.extractProperty("history");
127                         date = tool.extractProperty("date");
128                         if (date != null) {
129                                 ResourceBundle locale = ResourceBundle.getBundle("som",
130                                                 ApplicationSettings.getCurrentLocale());
131                                 SimpleDateFormat check = new SimpleDateFormat(
132                                                 locale.getString("date.format"));
133                                 try {
134                                         check.parse(date);
135                                 } catch (ParseException e) {
136                                         setErrorCode("format.date");
137                                         return ERROR;
138                                 }
139                         } else
140                                 date = "";
141                 }
142                 setupDefaultUses(deftype);
143                 // Add additional documents used by the current version
144                 List<Relation> uses = doc.getRelations(UsesRelation.class);
145                 for (Iterator<Relation> i = uses.iterator(); i.hasNext();) {
146                         Document used = (Document) i.next().getTo();
147                         if (!defuses.contains(used))
148                                 defuses.add(used);
149                 }
150                 // Setup dependencies
151                 List<Publication> relist = tag.getRelations(UsedByRelation.class);
152                 for (Iterator<Publication> i = relist.iterator(); i.hasNext();) {
153                         usedby.add(i.next());
154                 }
155                 transax.commit();
156                 return SUCCESS;
157         }
158
159         public String doVersion() {
160                 // -------------------------
161                 setMenuProperty("study");
162                 setTitleProperty("study");
163                 setEditDisabledProperty("true");
164         initializationScreenContext(_menuProperty, _titleProperty, _editDisabledProperty);
165             
166                 if (action == ToDo.cancel)
167                         return "cancel";
168
169                 Session connex = Database.getCurSession();
170                 Transaction transax = connex.beginTransaction();
171                 try {
172                         // Getting user inputs
173                         mystudy = getOpenStudy();
174                         User user = getConnectedUser();
175                         Step step = mystudy.getSelectedStep();
176                         File updir = getRepositoryService().getDownloadDirectory(user);
177                         File upfile = new File(updir.getPath() + "/" + filename);
178
179                         // Versioning of the document
180                         Document.Properties dprop = new Document.Properties();
181                         Publication current = step.getDocument(Integer.valueOf(index));
182                         Publication next;
183
184                         if (docver.length() == 0) { // Importation of a foreign document
185                                 next = getStepService().versionDocument(step, current, dprop.setAuthor(user)
186                                                 .setDescription(summary));
187                                 updir = next.getSourceFile().asFile();
188                                 if (logger.isInfoEnabled())
189                                         logger.info("Moving \"" + upfile.getName() + "\" to \""
190                                                         + updir.getPath() + "\".");
191                                 upfile.renameTo(updir);
192                                 try {
193                                         getPublicationService().saveAs(next, state); // May throw FileNotFound if rename was not done
194                                 } catch (FileNotFoundException saverror) {
195                                         Thread.sleep(1000);
196                                         logger.info("Waiting for the file.");
197                                         upfile.renameTo(updir);
198                                         getPublicationService().saveAs(next, state); // Forget it if throw again FileNotFound
199                                 }
200                         } else {
201                                 if (date.length() > 0) {
202                                         ResourceBundle locale = ResourceBundle.getBundle("som",
203                                                         ApplicationSettings.getCurrentLocale());
204                                         SimpleDateFormat get = new SimpleDateFormat(
205                                                         locale.getString("date.format"));
206                                         dprop.setDate(get.parse(date));
207                                 }
208                                 next = getStepService().versionDocument(step, current, dprop.setAuthor(user)
209                                                 .setDescription(summary));
210                                 updir = next.getSourceFile().asFile();
211                                 if (logger.isInfoEnabled())
212                                         logger.info("Moving \"" + upfile.getName() + "\" to \""
213                                                         + updir.getPath() + "\".");
214                                 upfile.renameTo(updir);
215                                 try {
216                                         getPublicationService().saveAs(next, new Revision(docver));
217                                 } catch (FileNotFoundException saverror) {
218                                         Thread.sleep(1000);
219                                         logger.info("Waiting for the file.");
220                                         upfile.renameTo(updir);
221                                         getPublicationService().saveAs(next, state);
222                                 }
223                         }
224                         // TODO: Remove current document details from the contents of open study
225
226                         // Creation of uses relations
227                         if (docuses != null) {
228                                 String[] list = docuses.split(",");
229                                 for (int i = 0; i < list.length; i++) {
230                                         Integer index = Integer.valueOf(list[i].trim());
231                                         Publication used = getPublication(index);
232                                         next.addDependency(used);
233                                 }
234                         }
235                         // Outdating impacted document
236                         HashSet<Integer> compatible = new HashSet<Integer>();
237                         if (docusedby != null) {
238                                 String[] list = docusedby.split(",");
239                                 for (int i = 0; i < list.length; i++)
240                                         compatible.add(Integer.valueOf(list[i].trim()));
241                         }
242                         List<Publication> relist = current
243                                         .getRelations(UsedByRelation.class);
244                         for (Iterator<Publication> i = relist.iterator(); i.hasNext();) {
245                                 Publication using = i.next();
246                                 if (!compatible.contains(using.getIndex()))
247                                         getPublicationService().outdate(using);
248                         }
249                         // Update of the open study
250                         mystudy.setSelection(mystudy.getSelection()); // Rebuilds the presentation
251                         // TODO: Look is an optimization is possible (for example by updating the presentation of versioned document)
252
253                         transax.commit();
254                         return SUCCESS;
255                 } catch (FileNotFoundException error) {
256                         logger.error("Reason:", error);
257                         setErrorCode("import.file");
258                 } catch (Exception error) {
259                         logger.error("Reason:", error);
260                         setErrorCode("internal");
261                 }
262                 if (transax != null && transax.isActive()) {
263                         // Second try-catch as the rollback could fail as well
264                         try {
265                                 transax.rollback();
266                         } catch (HibernateException backerror) {
267                                 logger.debug("Error rolling back transaction", backerror);
268                         }
269                 }
270                 return ERROR;
271         }
272
273         // ==============================================================================================================================
274         // Getters and setters
275         // ==============================================================================================================================
276
277         public String getDate() {
278                 // ------------------------
279                 return date;
280         }
281
282         public List<Publication> getDependencies() {
283                 // -------------------------------------------
284                 return usedby;
285         }
286
287         public String getDescription() {
288                 // -------------------------------
289                 return summary;
290         }
291
292         public String getIndex() {
293                 // -------------------------
294                 return index;
295         }
296
297         public String getVersion() {
298                 // ---------------------------
299                 return docver;
300         }
301
302         public void setDate(String date) {
303                 // ---------------------------------
304                 this.date = date;
305         }
306
307         public void setDefaultDescription(String summary) {
308                 // --------------------------------------------------
309                 if (this.summary == null)
310                         this.summary = summary;
311         }
312
313         public void setDescription(String summary) {
314                 // -------------------------------------------
315                 this.summary = summary;
316         }
317
318         public void setIndex(String index) {
319                 // -----------------------------------
320                 this.index = index;
321         }
322
323         public void setUsedBy(String list) {
324                 // -----------------------------------
325                 this.docusedby = list;
326         }
327
328         public void setVersion(String value) {
329                 // -------------------------------------
330                 this.docver = value;
331         }
332
333         /**
334          * Get project settings.
335          * 
336          * @return Project settings service
337          */
338         private ProjectSettingsService getProjectSettings() {
339                 return _projectSettingsService;
340         }
341
342         /**
343          * Set project settings service.
344          * 
345          * @param projectSettingsService
346          *            project settings service
347          */
348         public void setProjectSettings(ProjectSettingsService projectSettingsService) {
349                 _projectSettingsService = projectSettingsService;
350         }
351
352         /**
353          * Get the publicationService.
354          * 
355          * @return the publicationService
356          */
357         public PublicationService getPublicationService() {
358                 return _publicationService;
359         }
360
361         /**
362          * Set the publicationService.
363          * 
364          * @param publicationService
365          *            the publicationService to set
366          */
367         public void setPublicationService(PublicationService publicationService) {
368                 _publicationService = publicationService;
369         }
370
371         /**
372          * Get the stepService.
373          * @return the stepService
374          */
375         public StepService getStepService() {
376                 return _stepService;
377         }
378
379         /**
380          * Set the stepService.
381          * @param stepService the stepService to set
382          */
383         public void setStepService(StepService stepService) {
384                 _stepService = stepService;
385         }
386
387         /**
388          * Get the repositoryService.
389          * @return the repositoryService
390          */
391         public RepositoryService getRepositoryService() {
392                 return _repositoryService;
393         }
394
395         /**
396          * Set the repositoryService.
397          * @param repositoryService the repositoryService to set
398          */
399         public void setRepositoryService(RepositoryService repositoryService) {
400                 _repositoryService = repositoryService;
401         }
402         
403         /**
404          * Get the menuProperty.
405          * @return the menuProperty
406          */
407         public String getMenuProperty() {
408                 return _menuProperty;
409         }
410
411         /**
412          * Set the menuProperty.
413          * @param menuProperty the menuProperty to set
414          */
415         public void setMenuProperty(String menuProperty) {
416                 this._menuProperty = menuProperty;
417         }
418         
419         /**
420          * Get the _titleProperty.
421          * @return the _titleProperty
422          */
423         public String getTitleProperty() {
424                 return _titleProperty;
425         }
426
427         /**
428          * Set the _titleProperty.
429          * @param _titleProperty the titleProperty to set
430          */
431         public void setTitleProperty(String titleProperty) {
432                 _titleProperty = titleProperty;
433         }
434
435         /**
436          * Get the _editDisabledProperty.
437          * @return the _editDisabledProperty
438          */
439         public String getEditDisabledProperty() {
440                 return _editDisabledProperty;
441         }
442
443         /**
444          * Set the _editDisabledProperty.
445          * @param _editDisabledProperty the _editDisabledProperty to set
446          */
447         public void setEditDisabledProperty(String _editDisabledProperty) {
448                 this._editDisabledProperty = _editDisabledProperty;
449         }
450 }