]> SALOME platform Git repositories - tools/siman.git/blob - Workspace/Siman/src/org/splat/simer/VersionDocumentAction.java
Salome HOME
SIMAN Eclipse workspace first version
[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.kernel.Relation;
18 import org.splat.kernel.User;
19 import org.splat.manox.Reader;
20 import org.splat.manox.Toolbox;
21 import org.splat.som.Database;
22 import org.splat.som.Document;
23 import org.splat.som.ProgressState;
24 import org.splat.som.ProjectSettings;
25 import org.splat.som.Publication;
26 import org.splat.som.Revision;
27 import org.splat.som.Step;
28 import org.splat.som.UsedByRelation;
29 import org.splat.som.UsesRelation;
30
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
41     private static final long serialVersionUID = -5702264003232132168L;
42
43 //  ==============================================================================================================================
44 //  Action methods
45 //  ==============================================================================================================================
46
47     public String doInitialize () {
48 //  -----------------------------
49       Session      connex  = Database.getSession();
50       Transaction  transax = connex.beginTransaction();
51       User         user    = getConnectedUser();
52           File         updir   = Database.getDownloadDirectory(user);
53           File         upfile  = new File(updir.getPath() + "/" + filename);
54
55           mystudy  =  getOpenStudy();
56
57           Publication tag = mystudy.getSelectedStep().getDocument(Integer.valueOf(index));
58           Document    doc = tag.value();
59           deftype  =  doc.getType();
60           docname  =  doc.getTitle();
61       defuses  =  new Vector<Document>();
62       usedby   =  new Vector<Publication>();
63
64           Reader tool = Toolbox.getReader(upfile);
65           if (tool != null) {
66         String  fileref = tool.extractProperty("reference");
67         String  filever = tool.extractProperty("version");
68         if (fileref != null && !doc.getReference().equals(fileref)) {
69           setErrorCode("reference.mismatch");
70           return ERROR;
71         }
72         if (filever != null) try {
73           Revision.Format get    = new Revision.Format(ProjectSettings.getRevisionPattern());          
74           Revision        newver = get.parse(filever);
75           Revision        oldver = new Revision(doc.getVersion());
76           if (!newver.isGraterThan(oldver)) throw new InvalidPropertyException("version");
77           if ( newver.isMinor() ) state = ProgressState.inWORK;
78           else                    state = ProgressState.inDRAFT;
79           docver  = newver.toString();
80         } catch (Exception e) {
81           setErrorCode("version.mismatch");
82           return ERROR;
83         }
84         summary = tool.extractProperty("history");
85         date    = tool.extractProperty("date");
86         if (date != null) {
87           ResourceBundle   locale = ResourceBundle.getBundle("som", ApplicationSettings.getCurrentLocale());
88           SimpleDateFormat check  = new SimpleDateFormat(locale.getString("date.format"));
89           try {
90                 check.parse(date);
91           } catch (ParseException e) {
92                 setErrorCode("format.date");
93                 return ERROR;
94           }
95         } else date = "";
96           }
97       setupDefaultUses(deftype);
98 //    Add additional documents used by the current version
99           List<Relation> uses = doc.getRelations(UsesRelation.class);
100       for (Iterator<Relation> i=uses.iterator(); i.hasNext();) {
101         Document   used = (Document)i.next().getTo();
102         if (!defuses.contains(used)) defuses.add(used);
103       }
104 //    Setup dependencies
105       List<Publication> relist = tag.getRelations(UsedByRelation.class);
106       for (Iterator<Publication> i=relist.iterator(); i.hasNext();) {
107         usedby.add(i.next());
108       }
109       transax.commit();
110       return SUCCESS;
111     }
112
113     public String doVersion () {
114 //  -------------------------
115       if (action == ToDo.cancel) return "cancel";
116       
117       Session      connex  = Database.getSession();
118           Transaction  transax = connex.beginTransaction();
119       try {
120 //      Getting user inputs
121               mystudy = getOpenStudy();
122         User  user    = getConnectedUser();
123         Step  step    = mystudy.getSelectedStep();
124         File  updir   = Database.getDownloadDirectory(user);
125         File  upfile  = new File(updir.getPath() + "/" + filename);
126
127 //      Versioning of the document
128         Document.Properties dprop   = new Document.Properties();
129         Publication         current = step.getDocument(Integer.valueOf(index));
130         Publication         next;
131
132         if (docver.length() == 0) {     // Importation of a foreign document
133           next  = step.versionDocument(current, dprop.setAuthor(user).setDescription(summary));
134           updir = next.getSourceFile().asFile();
135                   if (logger.isInfoEnabled()) logger.info("Moving \"" + upfile.getName() + "\" to \"" + updir.getPath() + "\".");
136           upfile.renameTo(updir);
137           try {
138             next.saveAs(state);        // May throw FileNotFound if rename was not done
139           } catch (FileNotFoundException saverror) {
140                 Thread.sleep(1000);
141             logger.info("Waiting for the file.");
142             upfile.renameTo(updir);
143             next.saveAs(state);        // Forget it if throw again FileNotFound
144           }
145         } else {
146           if (date.length() > 0) {
147             ResourceBundle   locale = ResourceBundle.getBundle("som", ApplicationSettings.getCurrentLocale());
148             SimpleDateFormat get    = new SimpleDateFormat(locale.getString("date.format"));            
149             dprop.setDate(get.parse(date));
150           }
151           next  = step.versionDocument(current, dprop.setAuthor(user).setDescription(summary));
152           updir = next.getSourceFile().asFile();
153                   if (logger.isInfoEnabled()) logger.info("Moving \"" + upfile.getName() + "\" to \"" + updir.getPath() + "\".");
154           upfile.renameTo(updir);
155           try {
156             next.saveAs(new Revision(docver));
157           } catch (FileNotFoundException saverror) {
158             Thread.sleep(1000);
159             logger.info("Waiting for the file.");
160             upfile.renameTo(updir);
161             next.saveAs(state);
162           }
163         }
164 //TODO: Remove current document details from the contents of open study
165
166 //      Creation of uses relations
167         if (docuses != null) {
168           String[]     list = docuses.split(",");
169           for (int i=0; i<list.length; i++) {
170                 Integer      index = Integer.valueOf(list[i].trim());
171                 Publication  used  = getPublication(index);
172                 next.addDependency(used);
173           }
174         }
175 //      Outdating impacted document
176         HashSet<Integer> compatible = new HashSet<Integer>();
177         if (docusedby != null) {
178           String[] list = docusedby.split(",");
179           for (int i=0; i<list.length; i++) compatible.add(Integer.valueOf(list[i].trim()));
180         }
181         List<Publication> relist = current.getRelations(UsedByRelation.class);
182         for (Iterator<Publication> i=relist.iterator(); i.hasNext();) {
183           Publication  using = i.next();
184           if (!compatible.contains(using.getIndex())) using.outdate();
185         }        
186 //      Update of the open study
187         mystudy.setSelection(mystudy.getSelection());   // Rebuilds the presentation
188 //TODO: Look is an optimization is possible (for example by updating the presentation of versioned document)
189
190         transax.commit();
191         return SUCCESS;
192       }
193       catch (FileNotFoundException error) {
194         logger.error("Reason:", error);
195         setErrorCode("import.file");
196       }
197       catch (Exception error) {
198         logger.error("Reason:", error);
199         setErrorCode("internal");
200       }
201       if (transax != null && transax.isActive()) {
202 //      Second try-catch as the rollback could fail as well
203         try {
204           transax.rollback();
205         } catch (HibernateException backerror) {
206           logger.debug("Error rolling back transaction", backerror);
207         }
208       }
209       return ERROR;
210     }
211 //  ==============================================================================================================================
212 //  Getters and setters
213 //  ==============================================================================================================================
214
215     public String getDate () {
216 //  ------------------------
217       return date;
218     }
219     public List<Publication> getDependencies () {
220 //  ------------------------------------------- 
221       return usedby;
222     }
223     public String getDescription () {
224 //  -------------------------------
225       return summary;
226     }
227     public String getIndex () {
228 //  -------------------------
229       return index;
230     }
231     public String getVersion () {
232 //  ---------------------------
233       return docver;
234     }
235
236     public void setDate (String date) {
237 //  ---------------------------------
238       this.date = date;
239     }
240     public void setDefaultDescription (String summary) {
241 //  --------------------------------------------------
242       if (this.summary == null) this.summary = summary;
243     }
244     public void setDescription (String summary) {
245 //  -------------------------------------------
246       this.summary = summary;
247     }
248     public void setIndex (String index) {
249 //  -----------------------------------
250       this.index = index;
251     }
252     public void setUsedBy (String list) {
253 //  -----------------------------------
254       this.docusedby = list;
255     }
256     public void setVersion (String value) {
257 //  -------------------------------------
258       this.docver = value;
259     }
260 }