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