Salome HOME
d9d7bf1e72d810b89b1afe2814b7837089a101c4
[tools/siman.git] / Workspace / Siman / src / org / splat / module / SaveDocumentAction.java
1 package org.splat.module;
2
3 import java.io.File;
4 import java.util.Iterator;
5 import java.util.List;
6 import java.util.Set;
7 import java.util.Vector;
8
9 import org.hibernate.HibernateException;
10 import org.hibernate.Session;
11 import org.hibernate.Transaction;
12 import org.splat.kernel.Do;
13 import org.splat.dal.bo.kernel.User;
14 import org.splat.service.PublicationService;
15 import org.splat.service.ScenarioService;
16 import org.splat.service.StepService;
17 import org.splat.simer.Action;
18 import org.splat.simer.OpenStudy;
19 import org.splat.dal.bo.som.ConvertsRelation;
20 import org.splat.dal.dao.som.Database;
21 import org.splat.dal.bo.som.Document;
22 import org.splat.dal.bo.som.DocumentType;
23 import org.splat.dal.bo.som.ProgressState;
24 import org.splat.dal.bo.som.Publication;
25 import org.splat.dal.bo.som.Scenario;
26 import org.splat.dal.bo.som.SimulationContext;
27 import org.splat.dal.bo.som.SimulationContextType;
28 import org.splat.som.Step;
29
30 public class SaveDocumentAction extends Action {
31
32         private OpenStudy mystudy = null;
33         private int doctype = 0;
34         private String filename = null;
35         private String docname = null;
36         private ProgressState state = null;
37         private List<Document> defuses = null;
38         private String summary = null; // Summary of changes in the new version
39         private ScenarioService _scenarioService;
40         private PublicationService _publicationService;
41         private StepService _stepService;
42
43         private static final long serialVersionUID = -3364960833373200115L;
44
45         // ==============================================================================================================================
46         // Action methods
47         // ==============================================================================================================================
48
49         public String doSave() {
50                 // -----------------------
51                 Session connex = Database.getSession();
52                 Transaction transax = connex.beginTransaction();
53                 try {
54                         // Getting user inputs
55                         mystudy = getOpenStudy();
56                         User user = getConnectedUser();
57                         Step step = mystudy.getSelectedStep();
58                         DocumentType type = Document.selectType(doctype);
59                         // File updir = Database.getDownloadDirectory(user);
60                         // File upfile = new File(updir.getPath() + "/" + filename);
61                         String upath = Database.getTemplatePath(); // Instead of DownloadDirectory for sharing the "uploaded" file between users
62                         File upfile = new File(upath + filename);
63                         String[] table = filename.split("\\x2E");
64                         String format = table[table.length - 1];
65
66                         // Creation of the document
67                         getScenarioService().checkin((Scenario) step.getOwner()); // Modules necessarily save their data in a scenario step
68                         connex.flush();
69
70                         Document.Properties dprop = new Document.Properties();
71                         Publication credoc = getStepService().createDocument(step, dprop.setName(docname)
72                                         .setType(type).setFormat(format).setAuthor(user));
73                         // Writing the uploaded file into the created document
74                         File target = credoc.getSourceFile().asFile();
75                         if (target.exists())
76                                 target.delete();
77                         Do.copy(upfile, target); // Instead of rename for keeping the "uploaded" file for further use
78                         // upfile.renameTo(target);
79
80                         // Saving the document in given state
81                         getPublicationService().saveAs(credoc, state);
82
83                         // Creation of default uses relations
84                         defuses = new Vector<Document>();
85                         setupDefaultUses(type); // Recursive function
86                         for (Iterator<Document> i = defuses.iterator(); i.hasNext();) {
87                                 credoc.addDependency(i.next());
88                         }
89
90                         // Execution of module specific operations
91
92                         // 1. Conversion of the document to internal format, if required
93                         // TODO: The following code is temporary, waiting for the support of converters
94                         if (format.equals("part")) {
95                                 ConvertsRelation export = credoc.attach("brep");
96
97                                 target = export.getTo().asFile();
98                                 if (target.exists())
99                                         target.delete();
100                                 Do.copy(upfile, target); // Instead of rename for keeping the "uploaded" file for further use
101                         }
102                         // 2. Addition of simulation contexts
103                         if (type.equals("model")) { // Set the characteristics of the mesh
104                                 SimulationContext.Properties cprop = new SimulationContext.Properties();
105                                 SimulationContextType ctype = SimulationContext
106                                                 .selectType("model");
107                                 SimulationContext context = Database.selectSimulationContext(
108                                                 ctype, "Éléments finis");
109                                 if (context == null) {
110                                         getStepService().addSimulationContext(step,
111                                                         cprop.setType(ctype).setValue("Éléments finis"));
112                                 } else {
113                                         getStepService().addSimulationContext(step, context);
114                                 }
115                                 ctype = SimulationContext.selectType("element");
116                                 context = Database.selectSimulationContext(ctype, "Surfacique");
117                                 if (context == null) {
118                                         getStepService().addSimulationContext(step,
119                                                         cprop.setType(ctype).setValue("Surfacique"));
120                                 } else {
121                                         getStepService().addSimulationContext(step, context);
122                                 }
123                                 ctype = SimulationContext.selectType("shape");
124                                 context = Database.selectSimulationContext(ctype, "Triangles");
125                                 if (context == null) {
126                                         getStepService().addSimulationContext(step,
127                                                         cprop.setType(ctype).setValue("Triangles"));
128                                 } else {
129                                         getStepService().addSimulationContext(step, context);
130                                 }
131                         }
132                         // Update of the open study
133                         // mystudy.add(credoc); // Useless while the SIMER page need to be refreshed manually
134                         getMenu("study").selects(mystudy.getSelection()); // Updates the menu icon, in case of first added document
135
136                         transax.commit();
137                         return SUCCESS;
138                 } catch (Exception saverror) {
139                         logger.error("Reason:", saverror);
140                         if (transax != null && transax.isActive()) {
141                                 // Second try-catch as the rollback could fail as well
142                                 try {
143                                         transax.rollback();
144                                 } catch (HibernateException backerror) {
145                                         logger.debug("Error rolling back transaction", backerror);
146                                 }
147                         }
148                         return ERROR;
149                 }
150         }
151
152         /**
153          * Get the publicationService.
154          * 
155          * @return publicationService
156          */
157         private PublicationService getPublicationService() {
158                 return _publicationService;
159         }
160
161         /**
162          * Set the publicationService.
163          * 
164          * @param publicationService
165          *            the publicationService to set
166          */
167         public void setPublicationService(PublicationService publicationService) {
168                 _publicationService = publicationService;
169         }
170
171         /**
172          * Get the scenarioService.
173          * 
174          * @return scenarioService
175          */
176         public ScenarioService getScenarioService() {
177                 return _scenarioService;
178         }
179
180         /**
181          * Set the scenarioService.
182          * 
183          * @param scenarioService
184          *            the scenarioService to set
185          */
186         public void setScenarioService(ScenarioService scenarioService) {
187                 _scenarioService = scenarioService;
188         }
189
190         /**
191          * Get the stepService.
192          * 
193          * @return the stepService
194          */
195         public StepService getStepService() {
196                 return _stepService;
197         }
198
199         /**
200          * Set the stepService.
201          * 
202          * @param stepService
203          *            the stepService to set
204          */
205         public void setStepService(StepService stepService) {
206                 _stepService = stepService;
207         }
208
209         public String doUpdate() {
210                 // -------------------------
211                 return SUCCESS;
212         }
213
214         public String doVersion() {
215                 // --------------------------
216                 Session connex = Database.getSession();
217                 Transaction transax = connex.beginTransaction();
218                 try {
219                         // Getting user inputs
220                         mystudy = getOpenStudy();
221                         User user = getConnectedUser();
222                         Step step = mystudy.getSelectedStep();
223                         // File updir = Database.getDownloadDirectory(user);
224                         // File upfile = new File(updir.getPath() + "/" + filename);
225                         String upath = Database.getTemplatePath(); // Instead of DownloadDirectory for sharing the "uploaded" file between users
226                         File upfile = new File(upath + filename);
227                         String[] table = filename.split("\\x2E");
228                         String format = table[table.length - 1];
229
230                         // Versioning of the document
231                         Publication current = mystudy.getSelectedDocument();
232                         Document.Properties dprop = new Document.Properties();
233                         dprop.setAuthor(user);
234                         if (summary.length() > 0)
235                                 dprop.setDescription(summary);
236
237                         Publication next = getStepService().versionDocument(step, current, dprop);
238
239                         // Writing the uploaded file into the created document
240                         File target = next.getSourceFile().asFile();
241                         if (target.exists())
242                                 target.delete();
243                         Do.copy(upfile, target); // Instead of rename for keeping the "uploaded" file for further use
244                         // upfile.renameTo(target);
245
246                         // Saving the document in given state
247                         getPublicationService().saveAs(next, state);
248
249                         // Creation of default uses relations
250                         defuses = new Vector<Document>();
251                         setupDefaultUses(next.value().getType()); // Recursive function
252                         for (Iterator<Document> i = defuses.iterator(); i.hasNext();) {
253                                 next.addDependency(i.next());
254                         }
255                         // TODO: Outdating impacted document
256
257                         // Execution of module specific operations
258
259                         // 1. Conversion of the document to internal format, if required
260                         // TODO: The following code is temporary, waiting for the support of converters
261                         if (format.equals("part")) {
262                                 ConvertsRelation export = next.attach("brep");
263                                 String fname = table[0];
264
265                                 for (int i = 1; i < table.length - 1; i++)
266                                         fname = fname + table[i];
267                                 upfile = new File(upath + fname + ".brep");
268                                 upfile.renameTo(export.getTo().asFile());
269                         }
270
271                         // Update of the open study
272                         // mystudy.setSelection(mystudy.getSelection()); // Rebuild the presentation
273
274                         transax.commit();
275                         return SUCCESS;
276                 } catch (Exception saverror) {
277                         logger.error("Reason:", saverror);
278                         if (transax != null && transax.isActive()) {
279                                 // Second try-catch as the rollback could fail as well
280                                 try {
281                                         transax.rollback();
282                                 } catch (HibernateException backerror) {
283                                         logger.debug("Error rolling back transaction", backerror);
284                                 }
285                         }
286                         return ERROR;
287                 }
288         }
289
290         // ==============================================================================================================================
291         // Getters and setters
292         // ==============================================================================================================================
293
294         public String getDescription() {
295                 // -------------------------------
296                 return summary;
297         }
298
299         public void setDescription(String summary) {
300                 // -------------------------------------------
301                 this.summary = summary;
302         }
303
304         public void setDocumentName(String name) {
305                 // -----------------------------------------
306                 this.docname = name;
307         }
308
309         public void setDocumentState(String state) {
310                 // -------------------------------------------
311                 this.state = ProgressState.valueOf(state);
312         }
313
314         public void setDocumentType(String value) {
315                 // ------------------------------------------
316                 this.doctype = Integer.valueOf(value);
317         }
318
319         public void setFileName(String name) {
320                 // -------------------------------------
321                 this.filename = name;
322         }
323
324         // ==============================================================================================================================
325         // Private service
326         // ==============================================================================================================================
327
328         private void setupDefaultUses(DocumentType type) {
329                 // -------------------------------------------------
330                 Set<DocumentType> uses = type.getDefaultUses();
331
332                 for (Iterator<DocumentType> i = uses.iterator(); i.hasNext();) {
333                         DocumentType usetype = i.next();
334                         List<Document> usedoc = mystudy.collectInvolvedDocuments(usetype);
335                         if (usedoc.isEmpty())
336                                 setupDefaultUses(usetype);
337                         else
338                                 defuses.addAll(usedoc);
339                 }
340         }
341 }