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