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