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