Salome HOME
Siman codebase is refactored. Spring beans are introduced in the context.
[tools/siman.git] / Workspace / Siman / src / org / splat / simer / ImportDocumentAction.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.Arrays;
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.dal.bo.kernel.User;
17 import org.splat.manox.Reader;
18 import org.splat.manox.Toolbox;
19 import org.splat.dal.dao.som.Database;
20 import org.splat.dal.bo.som.Document;
21 import org.splat.dal.bo.som.ProgressState;
22 import org.splat.service.PublicationService;
23 import org.splat.service.technical.ProjectSettingsService;
24 import org.splat.dal.bo.som.Publication;
25 import org.splat.dal.bo.som.DocumentType;
26 import org.splat.som.Revision;
27 import org.splat.som.Step;
28
29 public class ImportDocumentAction extends UploadBaseNextAction {
30
31         private List<DocumentType> doctypes = null;
32         private int doctype = 0;
33         private String docref = null; // Reference extracted from the imported file, if exist
34         private String docver = ""; // Version number extracted from the imported file, if exist
35         private String date = ""; // Date extracted from the imported file, if exist
36         private ProjectSettingsService _projectSettingsService;
37         private PublicationService _publicationService;
38
39         private static final long serialVersionUID = 2587822564883588556L;
40
41         // ==============================================================================================================================
42         // Action methods
43         // ==============================================================================================================================
44
45         public String doInitialize() {
46                 // -----------------------------
47                 Session connex = Database.getSession();
48                 Transaction transax = connex.beginTransaction();
49                 User user = getConnectedUser();
50                 File updir = Database.getDownloadDirectory(user);
51                 File upfile = new File(updir.getPath() + "/" + filename);
52                 String[] table = filename.split("\\x2E");
53                 String filext = table[table.length - 1].toLowerCase();
54
55                 mystudy = getOpenStudy();
56                 Step step = mystudy.getSelectedStep();
57                 doctypes = step.getValidDocumentTypes();
58                 deftype = ApplicationSettings.getDefaultDocumentType(step, filext);
59                 defuses = new Vector<Document>();
60                 state = ProgressState.inWORK;
61
62                 Reader tool = Toolbox.getReader(upfile);
63                 if (tool != null) {
64                         String fileref = tool.extractProperty("reference");
65                         String filever = tool.extractProperty("version"); // Property kept even if the file is not referenced
66                         String filetype = tool.extractProperty("type"); // Property kept even if the file is not referenced
67                         for (Iterator<DocumentType> i = doctypes.iterator(); i.hasNext();) {
68                                 DocumentType type = i.next();
69                                 if (!type.getName().equals(filetype))
70                                         continue;
71                                 deftype = type;
72                                 doctype = type.getIndex(); // Disables the document type field
73                                 break;
74                         }
75                         if (fileref != null) {
76                                 Document slot = Database.selectDocument(fileref,
77                                                 new Revision().toString());
78                                 if (slot == null) {
79                                         setErrorCode("reference.undefined");
80                                         return ERROR;
81                                 } else {
82                                         if (!slot.isUndefined()) {
83                                                 setErrorCode("reference.duplicate");
84                                                 return ERROR;
85                                         }
86                                         docref = fileref; // Disables document name and state fields
87                                         deftype = slot.getType(); // Just in case
88                                         doctype = deftype.getIndex(); // Disables the document type field
89                                 }
90                         }
91                         if (filever != null)
92                                 try {
93                                         Revision.Format get = new Revision.Format(
94                                                         getProjectSettings().getRevisionPattern());
95                                         Revision version = get.parse(filever);
96                                         if (version.isNull())
97                                                 throw new ParseException(filever, filever.length() - 1);
98                                         if (!version.isMinor())
99                                                 state = ProgressState.inCHECK;
100                                         docver = version.toString();
101                                 } catch (ParseException e) {
102                                         setErrorCode("format.version");
103                                         return ERROR;
104                                 }
105                         docname = tool.extractProperty("title"); // Property kept even if the file is not referenced
106                         date = tool.extractProperty("date");
107                         if (date != null) {
108                                 ResourceBundle locale = ResourceBundle.getBundle("som",
109                                                 ApplicationSettings.getCurrentLocale());
110                                 SimpleDateFormat check = new SimpleDateFormat(
111                                                 locale.getString("date.format"));
112                                 try {
113                                         check.parse(date);
114                                 } catch (ParseException e) {
115                                         setErrorCode("format.date");
116                                         return ERROR;
117                                 }
118                         } else
119                                 date = "";
120                 } else if (filext.equals("pdf"))
121                         state = ProgressState.EXTERN; // TODO: Should external extensions be configurable ?
122                 if (docname == null) {
123                         docname = table[0];
124                         for (int i = 1; i < table.length - 1; i++)
125                                 docname = docname + "." + table[i];
126                 }
127                 if (deftype != null)
128                         setupDefaultUses(deftype);
129
130                 DocumentType[] types = doctypes.toArray(new DocumentType[doctypes
131                                 .size()]);
132                 DocumentTypeComparator compare = new DocumentTypeComparator();
133                 Arrays.sort(types, compare);
134                 doctypes = Arrays.asList(types);
135
136                 transax.commit();
137                 return SUCCESS;
138         }
139
140         public String doImport() {
141                 // -------------------------
142                 if (action == ToDo.cancel)
143                         return "cancel";
144                 if (doctype == 0) {
145                         setErrorCode("import.type");
146                         return ERROR;
147                 }
148                 Session connex = Database.getSession();
149                 Transaction transax = connex.beginTransaction();
150                 try {
151                         // Getting user inputs
152                         mystudy = getOpenStudy();
153                         User user = getConnectedUser();
154                         Step step = mystudy.getSelectedStep();
155                         DocumentType type = Document.selectType(doctype);
156                         File updir = Database.getDownloadDirectory(user);
157                         File upfile = new File(updir.getPath() + "/" + filename);
158                         String[] table = filename.split("\\x2E");
159
160                         // Creation of the document
161                         Document.Properties dprop = new Document.Properties();
162                         Publication addoc;
163
164                         if (docref.length() == 0) { // Importation of a foreign document
165                         // TODO: Extract property of supported documents (DOCX, ODT...)
166                                 addoc = step.createDocument(dprop.setName(docname)
167                                                 .setType(type).setFormat(table[table.length - 1])
168                                                 .setAuthor(user));
169                                 updir = addoc.getSourceFile().asFile();
170                                 if (logger.isInfoEnabled())
171                                         logger.info("Moving \"" + upfile.getName() + "\" to \""
172                                                         + updir.getPath() + "\".");
173                                 upfile.renameTo(updir);
174                                 try {
175                                         getPublicationService().saveAs(addoc, state); // May throw FileNotFound if rename was not done
176                                 } catch (FileNotFoundException saverror) {
177                                         Thread.sleep(1000);
178                                         logger.info("Waiting for the file.");
179                                         upfile.renameTo(updir);
180                                         getPublicationService().saveAs(addoc, state); // Forget it if throw again FileNotFound
181                                 }
182                         } else { // Importation of a previously created template-based document
183                                 if (date.length() > 0) {
184                                         ResourceBundle locale = ResourceBundle.getBundle("som",
185                                                         ApplicationSettings.getCurrentLocale());
186                                         SimpleDateFormat get = new SimpleDateFormat(
187                                                         locale.getString("date.format"));
188                                         dprop.setDate(get.parse(date));
189                                 }
190                                 addoc = step.assignDocument(dprop.setReference(docref).setName(
191                                                 docname));
192                                 updir = addoc.getSourceFile().asFile();
193                                 if (logger.isInfoEnabled())
194                                         logger.info("Moving \"" + upfile.getName() + "\" to \""
195                                                         + updir.getPath() + "\".");
196                                 upfile.renameTo(updir);
197                                 try {
198                                         if (docver.length() > 0)
199                                                 getPublicationService().saveAs(addoc,
200                                                                 new Revision(docver));
201                                         else
202                                                 getPublicationService().saveAs(addoc, state);
203                                 } catch (FileNotFoundException saverror) {
204                                         Thread.sleep(1000);
205                                         logger.info("Waiting for the file.");
206                                         upfile.renameTo(updir);
207                                         if (docver.length() > 0)
208                                                 getPublicationService().saveAs(addoc,
209                                                                 new Revision(docver));
210                                         else
211                                                 getPublicationService().saveAs(addoc, state);
212                                 }
213                                 mystudy.updateSimulationContexts(); // In case of simulation contexts extracted from the imported document
214                         }
215                         // Creation of uses relations
216                         if (docuses != null) {
217                                 String[] list = docuses.split(",");
218                                 for (int i = 0; i < list.length; i++) {
219                                         Integer index = Integer.valueOf(list[i].trim());
220                                         Publication used = getPublication(index);
221                                         addoc.addDependency(used);
222                                 }
223                         }
224                         // Creation of derived the document formats
225                         // Document ndoc = addoc.value();
226                         // Converter send = ApplicationSettings.getConverter(ndoc.getType(), ndoc.getFormat());
227                         //
228                         // if (send != null) send.converts(addoc); // Asynchronous process
229                         transax.commit();
230
231                         mystudy.add(addoc); // Updates the presentation
232                         return SUCCESS;
233                 } catch (FileNotFoundException error) {
234                         logger.error("Reason:", error);
235                         setErrorCode("import.file");
236                 } catch (Exception error) {
237                         logger.error("Reason:", error);
238                         setErrorCode("internal");
239                 }
240                 if (transax != null && transax.isActive()) { // Probably useless test
241                 // Second try-catch as the rollback could fail as well
242                         try {
243                                 transax.rollback();
244                         } catch (HibernateException backerror) {
245                                 logger.debug("Error rolling back transaction", backerror);
246                         }
247                 }
248                 return ERROR;
249         }
250
251         // ==============================================================================================================================
252         // Getters and setters
253         // ==============================================================================================================================
254
255         public String getDocumentDate() {
256                 // --------------------------------
257                 return date;
258         }
259
260         public List<DocumentType> getDocumentTypes() {
261                 // ---------------------------------------------
262                 return doctypes;
263         }
264
265         public int getDocumentType() {
266                 // -----------------------------
267                 return doctype;
268         }
269
270         public String getReference() {
271                 // -----------------------------
272                 return docref;
273         }
274
275         public String getVersion() {
276                 // ---------------------------
277                 return docver;
278         }
279
280         public void setDocumentDate(String date) {
281                 // -----------------------------------------
282                 this.date = date;
283         }
284
285         public void setDocumentName(String name) {
286                 // -----------------------------------------
287                 this.docname = name; // Name entered by the user if enabled
288         }
289
290         public void setDocumentTitle(String name) { // Called even if DocumentName is enabled
291         // -----------------------------------------
292                 if (this.docname == null)
293                         this.docname = name;
294         }
295
296         public void setDocumentType(String value) {
297                 // ------------------------------------------
298                 this.doctype = Integer.valueOf(value);
299         }
300
301         public void setDefaultDocumentState(String state) { // Called even if DocumentState is enabled
302         // --------------------------------------------------
303                 if (this.state == null)
304                         this.state = ProgressState.valueOf(state);
305         }
306
307         public void setDefaultDocumentType(String value) { // Called even if DocumentType is enabled
308         // --------------------------------------------------
309                 if (this.doctype == 0)
310                         this.doctype = Integer.valueOf(value);
311         }
312
313         public void setReference(String value) {
314                 // ---------------------------------------
315                 this.docref = value;
316         }
317
318         public void setVersion(String value) {
319                 // -------------------------------------
320                 this.docver = value;
321         }
322
323         /**
324          * Get project settings.
325          * 
326          * @return Project settings service
327          */
328         private ProjectSettingsService getProjectSettings() {
329                 return _projectSettingsService;
330         }
331
332         /**
333          * Set project settings service.
334          * 
335          * @param projectSettingsService
336          *            project settings service
337          */
338         public void setProjectSettings(ProjectSettingsService projectSettingsService) {
339                 _projectSettingsService = projectSettingsService;
340         }
341
342         /**
343          * Get the publicationService.
344          * 
345          * @return the publicationService
346          */
347         public PublicationService getPublicationService() {
348                 return _publicationService;
349         }
350
351         /**
352          * Set the publicationService.
353          * 
354          * @param publicationService
355          *            the publicationService to set
356          */
357         public void setPublicationService(PublicationService publicationService) {
358                 _publicationService = publicationService;
359         }
360 }