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