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