Salome HOME
Default document types mappings are moved from application settings (my.xml) to proje...
[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.ArrayList;
8 import java.util.Arrays;
9 import java.util.Iterator;
10 import java.util.List;
11 import java.util.ResourceBundle;
12
13 import org.splat.dal.bo.kernel.User;
14 import org.splat.dal.bo.som.Document;
15 import org.splat.dal.bo.som.DocumentType;
16 import org.splat.dal.bo.som.ProgressState;
17 import org.splat.dal.bo.som.Publication;
18 import org.splat.manox.Reader;
19 import org.splat.manox.Toolbox;
20 import org.splat.service.DocumentService;
21 import org.splat.service.DocumentTypeService;
22 import org.splat.service.PublicationService;
23 import org.splat.service.StepService;
24 import org.splat.service.technical.ProjectSettingsService;
25 import org.splat.service.technical.RepositoryService;
26 import org.splat.som.Revision;
27 import org.splat.som.Step;
28 import org.splat.wapp.Constants;
29
30 /**
31  * Action for adding a document into a study 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 transient List<DocumentType> _documentTypes = null;
41         private long _documentType = 0;
42         /**
43          * Reference extracted from the imported file, if exist.
44          */
45         private String _reference = null;
46         /**
47          * Version number extracted from the imported file, if exist.
48          */
49         private String _version = "";
50         /**
51          * Date extracted from the imported file, if exist.
52          */
53         private String _documentDate = "";
54         /**
55          * Injected project settings service.
56          */
57         private ProjectSettingsService _projectSettings;
58         /**
59          * Injected publication service.
60          */
61         private PublicationService _publicationService;
62         /**
63          * Injected step service.
64          */
65         private StepService _stepService;
66         /**
67          * Injected document service.
68          */
69         private DocumentService _documentService;
70         /**
71          * Injected document type service.
72          */
73         private DocumentTypeService _documentTypeService;
74         /**
75          * Injected repository service.
76          */
77         private RepositoryService _repositoryService;
78         /**
79          * Value of the menu property. It can be: none, create, open, study, knowledge, sysadmin, help.
80          */
81         private String _menuProperty;
82
83         /**
84          * Value of the title bar property. It can be: study, knowledge.
85          */
86         private String _titleProperty;
87
88         /**
89          * Value of the tool bar property. It can be: none, standard, study, back.
90          */
91         private String _toolProperty;
92
93         /**
94          * Value of the left menu property. It can be: open, study, knowledge, scenario.
95          */
96         private String _leftMenuProperty;
97
98         /**
99          * Property that indicates whether the current open study is editable or not. On the screen it looks like pen on the status icon, pop-up
100          * menu also can be called. It is necessary for correct building the title bar.
101          */
102         private String _editDisabledProperty = "false";
103
104         // ==============================================================================================================================
105         // Action methods
106         // ==============================================================================================================================
107
108         /**
109          * Initialize the operation.
110          * 
111          * @return SUCCESS in success, otherwise - ERROR
112          */
113         public String doInitialize() {
114
115                 setMenuProperty(Constants.STUDY_MENU);
116                 setTitleProperty(Constants.STUDY_MENU);
117                 setEditDisabledProperty("true");
118                 if ("true".equals(getWriteAccess())) {
119                         setToolProperty(Constants.STUDY_MENU);
120                 } else {
121                         setToolProperty(Constants.NONE);
122                 }
123                 setLeftMenuProperty(Constants.STUDY_MENU);
124                 initializationFullScreenContext(_menuProperty, _titleProperty,
125                                 _editDisabledProperty, _toolProperty, _leftMenuProperty);
126
127                 User user = getConnectedUser();
128                 File updir = getRepositoryService().getDownloadDirectory(user);
129                 File upfile = new File(updir.getPath() + "/" + filename);
130                 String[] table = filename.split("\\x2E");
131                 String filext = table[table.length - 1].toLowerCase();
132
133                 mystudy = getOpenStudy();
134                 Step step = mystudy.getSelectedStep();
135                 _documentTypes = getStepService().getValidDocumentTypes(step);
136                 deftype = getApplicationSettings().getDefaultDocumentType(step, filext);
137                 defuses = new ArrayList<Document>();
138                 state = ProgressState.inWORK;
139
140                 String res = ERROR;
141                 if (extractProperties(upfile, filext)) {
142                         if (docname == null) {
143                                 docname = table[0];
144                                 for (int i = 1; i < table.length - 1; i++) {
145                                         docname = docname + "." + table[i];
146                                 }
147                         }
148                         if (deftype != null) {
149                                 setupDefaultUses(deftype);
150                         }
151
152                         DocumentType[] types = _documentTypes
153                                         .toArray(new DocumentType[_documentTypes.size()]);
154                         DocumentTypeComparator compare = new DocumentTypeComparator();
155                         Arrays.sort(types, compare);
156                         _documentTypes = Arrays.asList(types);
157                         res = SUCCESS;
158                 }
159                 return res;
160         }
161
162         /**
163          * Extract properties from the uploaded file.
164          * 
165          * @param upfile
166          *            the file to parse
167          * @param filext
168          *            the file extension
169          * @return true if succeeded, false if error
170          */
171         private boolean extractProperties(final File upfile, final String filext) {
172                 boolean isOk = true;
173                 Reader tool = Toolbox.getReader(upfile);
174                 if (tool == null) {
175                         if ("pdf".equals(filext)) {
176                                 state = ProgressState.EXTERN; // TODO: Should external extensions be configurable ?
177                         }
178                 } else {
179                         String fileref = tool.extractProperty("reference");
180                         String filever = tool.extractProperty("version"); // Property kept even if the file is not referenced
181                         String filetype = tool.extractProperty("type"); // Property kept even if the file is not referenced
182                         for (Iterator<DocumentType> i = _documentTypes.iterator(); i
183                                         .hasNext();) {
184                                 DocumentType type = i.next();
185                                 if (type.getName().equals(filetype)) {
186                                         deftype = type;
187                                         _documentType = type.getIndex(); // Disables the document type field
188                                         break;
189                                 }
190                         }
191                         if (fileref != null) {
192                                 isOk = findTypeByDocRef(fileref);
193                         }
194                         if (isOk) {
195                                 if (filever != null) {
196                                         try {
197                                                 Revision.Format get = new Revision.Format(
198                                                                 getProjectSettings().getRevisionPattern());
199                                                 Revision version = get.parse(filever);
200                                                 if (version.isNull()) {
201                                                         throw new ParseException(filever,
202                                                                         filever.length() - 1);
203                                                 }
204                                                 if (!version.isMinor()) {
205                                                         state = ProgressState.inCHECK;
206                                                 }
207                                                 _version = version.toString();
208                                         } catch (ParseException e) {
209                                                 setError("message.error.format.version");
210                                                 isOk = false;
211                                         }
212                                 }
213                                 if (isOk) {
214                                         docname = tool.extractProperty("title"); // Property kept even if the file is not referenced
215                                         _documentDate = tool.extractProperty("date");
216                                         if (_documentDate == null) {
217                                                 _documentDate = "";
218                                         } else {
219                                                 ResourceBundle locale = ResourceBundle.getBundle("som",
220                                                                 getApplicationSettings().getCurrentLocale());
221                                                 SimpleDateFormat check = new SimpleDateFormat(locale
222                                                                 .getString("date.format"));
223                                                 try {
224                                                         check.parse(_documentDate);
225                                                 } catch (ParseException e) {
226                                                         setError("message.error.format.date");
227                                                         isOk = false;
228                                                 }
229                                         }
230                                 }
231                         }
232                 }
233                 return isOk;
234         }
235
236         /**
237          * Find document type by document reference.
238          * 
239          * @param fileref
240          *            the document reference
241          * @return true if succeeded, false if error
242          */
243         private boolean findTypeByDocRef(final String fileref) {
244                 boolean isOk = true;
245                 Document slot = getDocumentService().selectDocument(fileref,
246                                 new Revision().toString());
247                 if (slot == null) {
248                         setError("message.error.reference.undefined");
249                         isOk = false;
250                 } else {
251                         if (slot.isUndefined()) {
252                                 _reference = fileref; // Disables document name and state fields
253                                 deftype = slot.getType(); // Just in case
254                                 _documentType = deftype.getIndex(); // Disables the document type field
255                         } else {
256                                 setError("message.error.reference.duplicate");
257                                 isOk = false;
258                         }
259                 }
260                 return isOk;
261         }
262
263         /**
264          * Set error message and menus.
265          * 
266          * @param errorCode
267          *            error message key
268          */
269         private void setError(final String errorCode) {
270                 setErrorCode(errorCode);
271
272                 setToolProperty(Constants.NONE);
273                 initializationFullScreenContext(_menuProperty, _titleProperty,
274                                 _editDisabledProperty, _toolProperty, _leftMenuProperty);
275         }
276
277         /**
278          * Perform import of a document.
279          * 
280          * @return SUCCESS if ok, "cancel" - if canceled, ERROR - if error
281          */
282         public String doImport() {
283
284                 setMenuProperty(Constants.STUDY_MENU);
285                 setTitleProperty(Constants.STUDY_MENU);
286                 setEditDisabledProperty("true");
287                 initializationScreenContext(_menuProperty, _titleProperty,
288                                 _editDisabledProperty);
289
290                 if (action == ToDo.cancel) {
291                         return "cancel";
292                 }
293                 if (_documentType == 0) {
294                         setErrorCode("message.error.import.type");
295
296                         setToolProperty(Constants.NONE);
297                         setLeftMenuProperty(Constants.STUDY_MENU);
298                         initializationFullScreenContext(_menuProperty, _titleProperty,
299                                         _editDisabledProperty, _toolProperty, _leftMenuProperty);
300
301                         return ERROR;
302                 }
303                 try {
304                         // Getting user inputs
305                         mystudy = getOpenStudy();
306                         User user = getConnectedUser();
307                         Step step = mystudy.getSelectedStep();
308                         DocumentType type = getDocumentTypeService().selectType(
309                                         (int) _documentType);
310                         File updir = getRepositoryService().getDownloadDirectory(user);
311                         File upfile = new File(updir.getPath() + "/" + filename);
312                         String[] table = filename.split("\\x2E");
313
314                         // Creation of the document
315                         Document.Properties dprop = new Document.Properties();
316                         Publication addoc;
317
318                         if (_reference.length() == 0) { // Importation of a foreign document
319                                 // TODO: Extract property of supported documents (DOCX, ODT...)
320                                 addoc = getStepService().createDocument(
321                                                 step,
322                                                 dprop.setName(docname).setType(type).setFormat(
323                                                                 table[table.length - 1]).setAuthor(user));
324                                 updir = addoc.getSourceFile().asFile();
325                                 if (LOG.isInfoEnabled()) {
326                                         LOG.info("Moving \"" + upfile.getName() + "\" to \""
327                                                         + updir.getPath() + "\".");
328                                 }
329                                 upfile.renameTo(updir);
330                                 try {
331                                         getPublicationService().saveAs(addoc, state); // May throw FileNotFound if rename was not done
332                                 } catch (FileNotFoundException saverror) {
333                                         Thread.sleep(1000);
334                                         LOG.info("Waiting for the file.");
335                                         upfile.renameTo(updir);
336                                         getPublicationService().saveAs(addoc, state); // Forget it if throw again FileNotFound
337                                 }
338                         } else { // Importation of a previously created template-based document
339                                 if (_documentDate.length() > 0) {
340                                         ResourceBundle locale = ResourceBundle.getBundle("som",
341                                                         getApplicationSettings().getCurrentLocale());
342                                         SimpleDateFormat get = new SimpleDateFormat(locale
343                                                         .getString("date.format"));
344                                         dprop.setDate(get.parse(_documentDate));
345                                 }
346                                 addoc = getStepService().assignDocument(step,
347                                                 dprop.setReference(_reference).setName(docname));
348                                 updir = addoc.getSourceFile().asFile();
349                                 if (LOG.isInfoEnabled()) {
350                                         LOG.info("Moving \"" + upfile.getName() + "\" to \""
351                                                         + updir.getPath() + "\".");
352                                 }
353                                 upfile.renameTo(updir);
354                                 try {
355                                         if (_version.length() > 0) {
356                                                 getPublicationService().saveAs(addoc,
357                                                                 new Revision(_version));
358                                         } else {
359                                                 getPublicationService().saveAs(addoc, state);
360                                         }
361                                 } catch (FileNotFoundException saverror) {
362                                         Thread.sleep(1000);
363                                         LOG.info("Waiting for the file.");
364                                         upfile.renameTo(updir);
365                                         if (_version.length() > 0) {
366                                                 getPublicationService().saveAs(addoc,
367                                                                 new Revision(_version));
368                                         } else {
369                                                 getPublicationService().saveAs(addoc, state);
370                                         }
371                                 }
372                                 mystudy.updateSimulationContexts(); // In case of simulation contexts extracted from the imported document
373                         }
374                         // Creation of uses relations
375                         if (docuses != null) {
376                                 String[] list = docuses.split(",");
377                                 for (int i = 0; i < list.length; i++) {
378                                         Integer index = Integer.valueOf(list[i].trim());
379                                         Publication used = getPublication(index);
380                                         addoc.addDependency(used);
381                                 }
382                         }
383                         // Creation of derived the document formats
384                         // Document ndoc = addoc.value();
385                         // Converter send = getApplicationSettings().getConverter(ndoc.getType(), ndoc.getFormat());
386                         //
387                         // if (send != null) send.converts(addoc); // Asynchronous process
388
389                         mystudy.add(addoc); // Updates the presentation
390                         return SUCCESS;
391                 } catch (FileNotFoundException error) {
392                         LOG.error("Reason:", error);
393                         setErrorCode("message.error.import.file");
394                 } catch (Exception error) {
395                         LOG.error("Reason:", error);
396                         setErrorCode("message.error.internal");
397                 }
398
399                 setToolProperty(Constants.NONE);
400                 setLeftMenuProperty(Constants.STUDY_MENU);
401                 initializationFullScreenContext(_menuProperty, _titleProperty,
402                                 _editDisabledProperty, _toolProperty, _leftMenuProperty);
403
404                 return ERROR;
405         }
406
407         // ==============================================================================================================================
408         // Getters and setters
409         // ==============================================================================================================================
410
411         /**
412          * Date extracted from the imported file, if exist.
413          * 
414          * @return the file date
415          */
416         public String getDocumentDate() {
417                 return _documentDate;
418         }
419
420         public List<DocumentType> getDocumentTypes() {
421                 return _documentTypes;
422         }
423
424         /**
425          * Get document type id.
426          * 
427          * @return document type id
428          */
429         public long getDocumentType() {
430                 return _documentType;
431         }
432
433         /**
434          * Get reference extracted from the imported file, if exist.
435          * 
436          * @return the document reference
437          */
438         public String getReference() {
439                 return _reference;
440         }
441
442         /**
443          * Get version number extracted from the imported file, if exist.
444          * 
445          * @return the document version
446          */
447         public String getVersion() {
448                 return _version;
449         }
450
451         /**
452          * Set date extracted from the imported file.
453          * 
454          * @param date
455          *            the date to set
456          */
457         public void setDocumentDate(final String date) {
458                 this._documentDate = date;
459         }
460
461         /**
462          * Set document name entered by the user if enabled.
463          * 
464          * @param name
465          *            the document name
466          */
467         public void setDocumentName(final String name) {
468                 this.docname = name; // Name entered by the user if enabled
469         }
470
471         public void setDocumentTitle(final String name) { // Called even if DocumentName is enabled
472                 if (this.docname == null) {
473                         this.docname = name;
474                 }
475         }
476
477         /**
478          * Set document type id.
479          * 
480          * @param value
481          *            the id as string
482          */
483         public void setDocumentType(final String value) {
484                 this._documentType = Integer.valueOf(value);
485         }
486
487         public void setDefaultDocumentState(final String state) { // Called even if DocumentState is enabled
488                 if (this.state == null) {
489                         this.state = ProgressState.valueOf(state);
490                 }
491         }
492
493         public void setDefaultDocumentType(final String value) { // Called even if DocumentType is enabled
494                 if (this._documentType == 0) {
495                         this._documentType = Integer.valueOf(value);
496                 }
497         }
498
499         /**
500          * Set document reference extracted from the imported file, if exist.
501          * 
502          * @param value
503          *            the reference
504          */
505         public void setReference(final String value) {
506                 this._reference = value;
507         }
508
509         /**
510          * Set version number extracted from the imported file, if exist.
511          * 
512          * @param value
513          *            the version
514          */
515         public void setVersion(final String value) {
516                 this._version = value;
517         }
518
519         /**
520          * Get project settings.
521          * 
522          * @return Project settings service
523          */
524         private ProjectSettingsService getProjectSettings() {
525                 return _projectSettings;
526         }
527
528         /**
529          * Set project settings service.
530          * 
531          * @param projectSettingsService
532          *            project settings service
533          */
534         public void setProjectSettings(
535                         final ProjectSettingsService projectSettingsService) {
536                 _projectSettings = projectSettingsService;
537         }
538
539         /**
540          * Get the publicationService.
541          * 
542          * @return the publicationService
543          */
544         public PublicationService getPublicationService() {
545                 return _publicationService;
546         }
547
548         /**
549          * Set the publicationService.
550          * 
551          * @param publicationService
552          *            the publicationService to set
553          */
554         public void setPublicationService(
555                         final PublicationService publicationService) {
556                 _publicationService = publicationService;
557         }
558
559         /**
560          * Get the stepService.
561          * 
562          * @return the stepService
563          */
564         public StepService getStepService() {
565                 return _stepService;
566         }
567
568         /**
569          * Set the stepService.
570          * 
571          * @param stepService
572          *            the stepService to set
573          */
574         public void setStepService(final StepService stepService) {
575                 _stepService = stepService;
576         }
577
578         /**
579          * Get the documentService.
580          * 
581          * @return the documentService
582          */
583         public DocumentService getDocumentService() {
584                 return _documentService;
585         }
586
587         /**
588          * Set the documentService.
589          * 
590          * @param documentService
591          *            the documentService to set
592          */
593         public void setDocumentService(final DocumentService documentService) {
594                 _documentService = documentService;
595         }
596
597         /**
598          * Get the repositoryService.
599          * 
600          * @return the repositoryService
601          */
602         public RepositoryService getRepositoryService() {
603                 return _repositoryService;
604         }
605
606         /**
607          * Set the repositoryService.
608          * 
609          * @param repositoryService
610          *            the repositoryService to set
611          */
612         public void setRepositoryService(final RepositoryService repositoryService) {
613                 _repositoryService = repositoryService;
614         }
615
616         /**
617          * Get the documentTypeService.
618          * 
619          * @return the documentTypeService
620          */
621         public DocumentTypeService getDocumentTypeService() {
622                 return _documentTypeService;
623         }
624
625         /**
626          * Set the documentTypeService.
627          * 
628          * @param documentTypeService
629          *            the documentTypeService to set
630          */
631         public void setDocumentTypeService(
632                         final DocumentTypeService documentTypeService) {
633                 _documentTypeService = documentTypeService;
634         }
635
636         /**
637          * Get the menuProperty.
638          * 
639          * @return the menuProperty
640          */
641         public String getMenuProperty() {
642                 return _menuProperty;
643         }
644
645         /**
646          * Set the menuProperty.
647          * 
648          * @param menuProperty
649          *            the menuProperty to set
650          */
651         public void setMenuProperty(final String menuProperty) {
652                 this._menuProperty = menuProperty;
653         }
654
655         /**
656          * Get the _titleProperty.
657          * 
658          * @return the _titleProperty
659          */
660         public String getTitleProperty() {
661                 return _titleProperty;
662         }
663
664         /**
665          * Set the titleProperty.
666          * 
667          * @param titleProperty
668          *            the titleProperty to set
669          */
670         public void setTitleProperty(final String titleProperty) {
671                 _titleProperty = titleProperty;
672         }
673
674         /**
675          * Get the editDisabledProperty.
676          * 
677          * @return the editDisabledProperty
678          */
679         public final String getEditDisabledProperty() {
680                 return _editDisabledProperty;
681         }
682
683         /**
684          * Set the editDisabledProperty.
685          * 
686          * @param editDisabledProperty
687          *            the editDisabledProperty to set
688          */
689         public final void setEditDisabledProperty(final String editDisabledProperty) {
690                 _editDisabledProperty = editDisabledProperty;
691         }
692
693         /**
694          * Get the toolProperty.
695          * 
696          * @return the toolProperty
697          */
698         public String getToolProperty() {
699                 return _toolProperty;
700         }
701
702         /**
703          * Set the toolProperty.
704          * 
705          * @param toolProperty
706          *            the toolProperty to set
707          */
708         public void setToolProperty(final String toolProperty) {
709                 _toolProperty = toolProperty;
710         }
711
712         /**
713          * Get the leftMenuProperty.
714          * 
715          * @return the leftMenuProperty
716          */
717         public String getLeftMenuProperty() {
718                 return _leftMenuProperty;
719         }
720
721         /**
722          * Set the leftMenuProperty.
723          * 
724          * @param leftMenuProperty
725          *            the leftMenuProperty to set
726          */
727         public void setLeftMenuProperty(final String leftMenuProperty) {
728                 _leftMenuProperty = leftMenuProperty;
729         }
730 }