Salome HOME
Tool bar is improved.
[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.splat.dal.bo.kernel.User;
14 import org.splat.manox.Reader;
15 import org.splat.manox.Toolbox;
16 import org.splat.dal.bo.som.Document;
17 import org.splat.dal.bo.som.ProgressState;
18 import org.splat.service.DocumentService;
19 import org.splat.service.DocumentTypeService;
20 import org.splat.service.PublicationService;
21 import org.splat.service.StepService;
22 import org.splat.service.technical.ProjectSettingsService;
23 import org.splat.service.technical.RepositoryService;
24 import org.splat.dal.bo.som.Publication;
25 import org.splat.dal.bo.som.DocumentType;
26 import org.splat.som.Revision;
27 import org.splat.som.Step;
28
29 /**
30  * Action for adding a document into a study 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          * Injected document type service.
62          */
63         private DocumentTypeService _documentTypeService;
64         /**
65          * Injected repository service.
66          */
67         private RepositoryService _repositoryService;   
68         /**
69          * Value of the menu property. 
70          * It can be: none, create, open, study, knowledge, sysadmin, help.
71          */
72         private String _menuProperty;
73         
74         /**
75          * Value of the title bar property. 
76          * It can be: study, knowledge.
77          */
78         private String _titleProperty;
79         
80         /**
81          * Value of the tool bar property. 
82          * It can be: none, standard, study, back.
83          */
84         private String _toolProperty;
85         
86         /**
87          * Property that indicates whether the current open study is editable or not.
88          * On the screen it looks like pen on the status icon, pop-up menu also can be called.
89          * It is necessary for correct building the title bar.
90          */
91         private String _editDisabledProperty = "false";
92
93         // ==============================================================================================================================
94         // Action methods
95         // ==============================================================================================================================
96
97         /**
98          * Initialize the operation.
99          * @return SUCCESS in success, otherwise - ERROR
100          */
101         public String doInitialize() {
102                 
103                 setMenuProperty("study");
104                 setTitleProperty("study");
105                 setEditDisabledProperty("true");
106                 if ("true".equals(getWriteAccess())) {
107                         setToolProperty("study");
108                 } else {
109                         setToolProperty("none");
110                 }
111         initializationScreenContext(_menuProperty, _titleProperty, _editDisabledProperty, _toolProperty);
112               
113                 User user = getConnectedUser();
114                 File updir = getRepositoryService().getDownloadDirectory(user);
115                 File upfile = new File(updir.getPath() + "/" + filename);
116                 String[] table = filename.split("\\x2E");
117                 String filext = table[table.length - 1].toLowerCase();
118
119                 mystudy = getOpenStudy();
120                 Step step = mystudy.getSelectedStep();
121                 doctypes = getStepService().getValidDocumentTypes(step);
122                 deftype = getApplicationSettings().getDefaultDocumentType(step, filext);
123                 defuses = new Vector<Document>();
124                 state = ProgressState.inWORK;
125
126                 Reader tool = Toolbox.getReader(upfile);
127                 if (tool != null) {
128                         String fileref = tool.extractProperty("reference");
129                         String filever = tool.extractProperty("version"); // Property kept even if the file is not referenced
130                         String filetype = tool.extractProperty("type"); // Property kept even if the file is not referenced
131                         for (Iterator<DocumentType> i = doctypes.iterator(); i.hasNext();) {
132                                 DocumentType type = i.next();
133                                 if (!type.getName().equals(filetype))
134                                         continue;
135                                 deftype = type;
136                                 doctype = type.getIndex(); // Disables the document type field
137                                 break;
138                         }
139                         if (fileref != null) {
140                                 Document slot = getDocumentService().selectDocument(fileref,
141                                                 new Revision().toString());
142                                 if (slot == null) {
143                                         setErrorCode("reference.undefined");
144                                         
145                                         setToolProperty("none");
146                                         initializationScreenContext(_menuProperty, _titleProperty, _editDisabledProperty, _toolProperty);
147                                         
148                                         return ERROR;
149                                 } else {
150                                         if (!slot.isUndefined()) {
151                                                 setErrorCode("reference.duplicate");
152                                                 
153                                                 setToolProperty("none");
154                                                 initializationScreenContext(_menuProperty, _titleProperty, _editDisabledProperty, _toolProperty);
155                                                 
156                                                 return ERROR;
157                                         }
158                                         docref = fileref; // Disables document name and state fields
159                                         deftype = slot.getType(); // Just in case
160                                         doctype = deftype.getIndex(); // Disables the document type field
161                                 }
162                         }
163                         if (filever != null)
164                                 try {
165                                         Revision.Format get = new Revision.Format(
166                                                         getProjectSettings().getRevisionPattern());
167                                         Revision version = get.parse(filever);
168                                         if (version.isNull())
169                                                 throw new ParseException(filever, filever.length() - 1);
170                                         if (!version.isMinor())
171                                                 state = ProgressState.inCHECK;
172                                         docver = version.toString();
173                                 } catch (ParseException e) {
174                                         setErrorCode("format.version");
175                                         
176                                         setToolProperty("none");
177                                         initializationScreenContext(_menuProperty, _titleProperty, _editDisabledProperty, _toolProperty);
178                                         
179                                         return ERROR;
180                                 }
181                         docname = tool.extractProperty("title"); // Property kept even if the file is not referenced
182                         date = tool.extractProperty("date");
183                         if (date != null) {
184                                 ResourceBundle locale = ResourceBundle.getBundle("som",
185                                                 getApplicationSettings().getCurrentLocale());
186                                 SimpleDateFormat check = new SimpleDateFormat(
187                                                 locale.getString("date.format"));
188                                 try {
189                                         check.parse(date);
190                                 } catch (ParseException e) {
191                                         setErrorCode("format.date");
192                                         
193                                         setToolProperty("none");
194                                         initializationScreenContext(_menuProperty, _titleProperty, _editDisabledProperty, _toolProperty);
195                                         
196                                         return ERROR;
197                                 }
198                         } else
199                                 date = "";
200                 } else if (filext.equals("pdf"))
201                         state = ProgressState.EXTERN; // TODO: Should external extensions be configurable ?
202                 if (docname == null) {
203                         docname = table[0];
204                         for (int i = 1; i < table.length - 1; i++)
205                                 docname = docname + "." + table[i];
206                 }
207                 if (deftype != null)
208                         setupDefaultUses(deftype);
209
210                 DocumentType[] types = doctypes.toArray(new DocumentType[doctypes
211                                 .size()]);
212                 DocumentTypeComparator compare = new DocumentTypeComparator();
213                 Arrays.sort(types, compare);
214                 doctypes = Arrays.asList(types);
215
216                 return SUCCESS;
217         }
218
219         /**
220          * Perform import of a document.
221          * @return SUCCESS if ok, "cancel" - if canceled, ERROR - if error
222          */
223         public String doImport() {
224                 // -------------------------
225                 
226                 setMenuProperty("study");
227                 setTitleProperty("study");
228                 setEditDisabledProperty("true");
229         initializationScreenContext(_menuProperty, _titleProperty, _editDisabledProperty);
230             
231                 if (action == ToDo.cancel)
232                         return "cancel";
233                 if (doctype == 0) {
234                         setErrorCode("import.type");
235                         
236                         setToolProperty("none");
237                         initializationScreenContext(_menuProperty, _titleProperty, _editDisabledProperty, _toolProperty);
238                         
239                         return ERROR;
240                 }
241                 try {
242                         // Getting user inputs
243                         mystudy = getOpenStudy();
244                         User user = getConnectedUser();
245                         Step step = mystudy.getSelectedStep();
246                         DocumentType type = getDocumentTypeService().selectType((int)doctype);
247                         File updir = getRepositoryService().getDownloadDirectory(user);
248                         File upfile = new File(updir.getPath() + "/" + filename);
249                         String[] table = filename.split("\\x2E");
250
251                         // Creation of the document
252                         Document.Properties dprop = new Document.Properties();
253                         Publication addoc;
254
255                         if (docref.length() == 0) { // Importation of a foreign document
256                         // TODO: Extract property of supported documents (DOCX, ODT...)
257                                 addoc = getStepService().createDocument(step, dprop.setName(docname)
258                                                 .setType(type).setFormat(table[table.length - 1])
259                                                 .setAuthor(user));
260                                 updir = addoc.getSourceFile().asFile();
261                                 if (logger.isInfoEnabled())
262                                         logger.info("Moving \"" + upfile.getName() + "\" to \""
263                                                         + updir.getPath() + "\".");
264                                 upfile.renameTo(updir);
265                                 try {
266                                         getPublicationService().saveAs(addoc, state); // May throw FileNotFound if rename was not done
267                                 } catch (FileNotFoundException saverror) {
268                                         Thread.sleep(1000);
269                                         logger.info("Waiting for the file.");
270                                         upfile.renameTo(updir);
271                                         getPublicationService().saveAs(addoc, state); // Forget it if throw again FileNotFound
272                                 }
273                         } else { // Importation of a previously created template-based document
274                                 if (date.length() > 0) {
275                                         ResourceBundle locale = ResourceBundle.getBundle("som",
276                                                         getApplicationSettings().getCurrentLocale());
277                                         SimpleDateFormat get = new SimpleDateFormat(
278                                                         locale.getString("date.format"));
279                                         dprop.setDate(get.parse(date));
280                                 }
281                                 addoc = getStepService().assignDocument(step, dprop.setReference(docref).setName(
282                                                 docname));
283                                 updir = addoc.getSourceFile().asFile();
284                                 if (logger.isInfoEnabled())
285                                         logger.info("Moving \"" + upfile.getName() + "\" to \""
286                                                         + updir.getPath() + "\".");
287                                 upfile.renameTo(updir);
288                                 try {
289                                         if (docver.length() > 0)
290                                                 getPublicationService().saveAs(addoc,
291                                                                 new Revision(docver));
292                                         else
293                                                 getPublicationService().saveAs(addoc, state);
294                                 } catch (FileNotFoundException saverror) {
295                                         Thread.sleep(1000);
296                                         logger.info("Waiting for the file.");
297                                         upfile.renameTo(updir);
298                                         if (docver.length() > 0)
299                                                 getPublicationService().saveAs(addoc,
300                                                                 new Revision(docver));
301                                         else
302                                                 getPublicationService().saveAs(addoc, state);
303                                 }
304                                 mystudy.updateSimulationContexts(); // In case of simulation contexts extracted from the imported document
305                         }
306                         // Creation of uses relations
307                         if (docuses != null) {
308                                 String[] list = docuses.split(",");
309                                 for (int i = 0; i < list.length; i++) {
310                                         Integer index = Integer.valueOf(list[i].trim());
311                                         Publication used = getPublication(index);
312                                         addoc.addDependency(used);
313                                 }
314                         }
315                         // Creation of derived the document formats
316                         // Document ndoc = addoc.value();
317                         // Converter send = getApplicationSettings().getConverter(ndoc.getType(), ndoc.getFormat());
318                         //
319                         // if (send != null) send.converts(addoc); // Asynchronous process
320
321                         mystudy.add(addoc); // Updates the presentation
322                         return SUCCESS;
323                 } catch (FileNotFoundException error) {
324                         logger.error("Reason:", error);
325                         setErrorCode("import.file");
326                 } catch (Exception error) {
327                         logger.error("Reason:", error);
328                         setErrorCode("internal");
329                 }
330                 
331                 setToolProperty("none");
332                 initializationScreenContext(_menuProperty, _titleProperty, _editDisabledProperty, _toolProperty);
333                 
334                 return ERROR;
335         }
336
337         // ==============================================================================================================================
338         // Getters and setters
339         // ==============================================================================================================================
340
341         public String getDocumentDate() {
342                 // --------------------------------
343                 return date;
344         }
345
346         public List<DocumentType> getDocumentTypes() {
347                 // ---------------------------------------------
348                 return doctypes;
349         }
350
351         public long getDocumentType() {
352                 // -----------------------------
353                 return doctype;
354         }
355
356         public String getReference() {
357                 // -----------------------------
358                 return docref;
359         }
360
361         public String getVersion() {
362                 // ---------------------------
363                 return docver;
364         }
365
366         public void setDocumentDate(String date) {
367                 // -----------------------------------------
368                 this.date = date;
369         }
370
371         public void setDocumentName(String name) {
372                 // -----------------------------------------
373                 this.docname = name; // Name entered by the user if enabled
374         }
375
376         public void setDocumentTitle(String name) { // Called even if DocumentName is enabled
377         // -----------------------------------------
378                 if (this.docname == null)
379                         this.docname = name;
380         }
381
382         public void setDocumentType(String value) {
383                 // ------------------------------------------
384                 this.doctype = Integer.valueOf(value);
385         }
386
387         public void setDefaultDocumentState(String state) { // Called even if DocumentState is enabled
388         // --------------------------------------------------
389                 if (this.state == null)
390                         this.state = ProgressState.valueOf(state);
391         }
392
393         public void setDefaultDocumentType(String value) { // Called even if DocumentType is enabled
394         // --------------------------------------------------
395                 if (this.doctype == 0)
396                         this.doctype = Integer.valueOf(value);
397         }
398
399         public void setReference(String value) {
400                 // ---------------------------------------
401                 this.docref = value;
402         }
403
404         public void setVersion(String value) {
405                 // -------------------------------------
406                 this.docver = value;
407         }
408
409         /**
410          * Get project settings.
411          * 
412          * @return Project settings service
413          */
414         private ProjectSettingsService getProjectSettings() {
415                 return _projectSettingsService;
416         }
417
418         /**
419          * Set project settings service.
420          * 
421          * @param projectSettingsService
422          *            project settings service
423          */
424         public void setProjectSettings(ProjectSettingsService projectSettingsService) {
425                 _projectSettingsService = projectSettingsService;
426         }
427
428         /**
429          * Get the publicationService.
430          * 
431          * @return the publicationService
432          */
433         public PublicationService getPublicationService() {
434                 return _publicationService;
435         }
436
437         /**
438          * Set the publicationService.
439          * 
440          * @param publicationService
441          *            the publicationService to set
442          */
443         public void setPublicationService(PublicationService publicationService) {
444                 _publicationService = publicationService;
445         }
446
447         /**
448          * Get the stepService.
449          * @return the stepService
450          */
451         public StepService getStepService() {
452                 return _stepService;
453         }
454
455         /**
456          * Set the stepService.
457          * @param stepService the stepService to set
458          */
459         public void setStepService(StepService stepService) {
460                 _stepService = stepService;
461         }
462
463         /**
464          * Get the documentService.
465          * @return the documentService
466          */
467         public DocumentService getDocumentService() {
468                 return _documentService;
469         }
470
471         /**
472          * Set the documentService.
473          * @param documentService the documentService to set
474          */
475         public void setDocumentService(DocumentService documentService) {
476                 _documentService = documentService;
477         }
478
479         /**
480          * Get the repositoryService.
481          * @return the repositoryService
482          */
483         public RepositoryService getRepositoryService() {
484                 return _repositoryService;
485         }
486
487         /**
488          * Set the repositoryService.
489          * @param repositoryService the repositoryService to set
490          */
491         public void setRepositoryService(RepositoryService repositoryService) {
492                 _repositoryService = repositoryService;
493         }
494
495         /**
496          * Get the documentTypeService.
497          * @return the documentTypeService
498          */
499         public DocumentTypeService getDocumentTypeService() {
500                 return _documentTypeService;
501         }
502
503         /**
504          * Set the documentTypeService.
505          * @param documentTypeService the documentTypeService to set
506          */
507         public void setDocumentTypeService(DocumentTypeService documentTypeService) {
508                 _documentTypeService = documentTypeService;
509         }
510         
511         /**
512          * Get the menuProperty.
513          * @return the menuProperty
514          */
515         public String getMenuProperty() {
516                 return _menuProperty;
517         }
518
519         /**
520          * Set the menuProperty.
521          * @param menuProperty the menuProperty to set
522          */
523         public void setMenuProperty(String menuProperty) {
524                 this._menuProperty = menuProperty;
525         }
526         
527         /**
528          * Get the _titleProperty.
529          * @return the _titleProperty
530          */
531         public String getTitleProperty() {
532                 return _titleProperty;
533         }
534
535         /**
536          * Set the _titleProperty.
537          * @param _titleProperty the titleProperty to set
538          */
539         public void setTitleProperty(String titleProperty) {
540                 _titleProperty = titleProperty;
541         }
542
543         /**
544          * Get the editDisabledProperty.
545          * @return the editDisabledProperty
546          */
547         public final String getEditDisabledProperty() {
548                 return _editDisabledProperty;
549         }
550
551         /**
552          * Set the editDisabledProperty.
553          * @param editDisabledProperty the editDisabledProperty to set
554          */
555         public final void setEditDisabledProperty(String editDisabledProperty) {
556                 _editDisabledProperty = editDisabledProperty;
557         }
558
559         /**
560          * Get the toolProperty.
561          * @return the toolProperty
562          */
563         public String getToolProperty() {
564                 return _toolProperty;
565         }
566
567         /**
568          * Set the toolProperty.
569          * @param toolProperty the toolProperty to set
570          */
571         public void setToolProperty(final String toolProperty) {
572                 _toolProperty = toolProperty;
573         }
574 }