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