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