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