Salome HOME
Actions menu properties are refactored, unnecessary code is removed.
[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         // ==============================================================================================================================
81         // Action methods
82         // ==============================================================================================================================
83
84         /**
85          * Initialize the operation.
86          * 
87          * @return SUCCESS in success, otherwise - ERROR
88          */
89         public String doInitialize() {
90
91                 if (Constants.TRUE.equals(getWriteAccess())) {
92                         setToolProperty(Constants.STUDY_MENU);
93                 } else {
94                         setToolProperty(Constants.NONE);
95                 }
96                 initializationFullScreenContext(Constants.STUDY_MENU, Constants.STUDY_MENU,
97                                 Constants.FALSE, getToolProperty(), Constants.STUDY_MENU);
98
99                 User user = getConnectedUser();
100                 File updir = getRepositoryService().getDownloadDirectory(user);
101                 File upfile = new File(updir.getPath() + "/" + filename);
102                 String[] table = filename.split("\\x2E");
103                 String filext = table[table.length - 1].toLowerCase();
104
105                 mystudy = getOpenStudy();
106                 Step step = mystudy.getSelectedStep();
107                 _documentTypes = getStepService().getValidDocumentTypes(step);
108                 deftype = getApplicationSettings().getDefaultDocumentType(step, filext);
109                 defuses = new ArrayList<Document>();
110                 state = ProgressState.inWORK;
111
112                 String res = ERROR;
113                 if (extractProperties(upfile, filext)) {
114                         if (docname == null) {
115                                 docname = table[0];
116                                 for (int i = 1; i < table.length - 1; i++) {
117                                         docname = docname + "." + table[i];
118                                 }
119                         }
120                         if (deftype != null) {
121                                 setupDefaultUses(deftype);
122                         }
123
124                         DocumentType[] types = _documentTypes
125                                         .toArray(new DocumentType[_documentTypes.size()]);
126                         DocumentTypeComparator compare = new DocumentTypeComparator();
127                         Arrays.sort(types, compare);
128                         _documentTypes = Arrays.asList(types);
129                         res = SUCCESS;
130                 }
131                 return res;
132         }
133
134         /**
135          * Extract properties from the uploaded file.
136          * 
137          * @param upfile
138          *            the file to parse
139          * @param filext
140          *            the file extension
141          * @return true if succeeded, false if error
142          */
143         private boolean extractProperties(final File upfile, final String filext) {
144                 boolean isOk = true;
145                 Reader tool = Toolbox.getReader(upfile);
146                 if (tool == null) {
147                         if ("pdf".equals(filext)) {
148                                 state = ProgressState.EXTERN; // TODO: Should external extensions be configurable ?
149                         }
150                 } else {
151                         String fileref = tool.extractProperty("reference");
152                         String filever = tool.extractProperty("version"); // Property kept even if the file is not referenced
153                         String filetype = tool.extractProperty("type"); // Property kept even if the file is not referenced
154                         for (Iterator<DocumentType> i = _documentTypes.iterator(); i
155                                         .hasNext();) {
156                                 DocumentType type = i.next();
157                                 if (type.getName().equals(filetype)) {
158                                         deftype = type;
159                                         _documentType = type.getIndex(); // Disables the document type field
160                                         break;
161                                 }
162                         }
163                         if (fileref != null) {
164                                 isOk = findTypeByDocRef(fileref);
165                         }
166                         if (isOk) {
167                                 if (filever != null) {
168                                         try {
169                                                 Revision.Format get = new Revision.Format(
170                                                                 getProjectSettings().getRevisionPattern());
171                                                 Revision version = get.parse(filever);
172                                                 if (version.isNull()) {
173                                                         throw new ParseException(filever,
174                                                                         filever.length() - 1);
175                                                 }
176                                                 if (!version.isMinor()) {
177                                                         state = ProgressState.inCHECK;
178                                                 }
179                                                 _version = version.toString();
180                                         } catch (ParseException e) {
181                                                 setError("message.error.format.version");
182                                                 isOk = false;
183                                         }
184                                 }
185                                 if (isOk) {
186                                         docname = tool.extractProperty("title"); // Property kept even if the file is not referenced
187                                         _documentDate = tool.extractProperty("date");
188                                         if (_documentDate == null) {
189                                                 _documentDate = "";
190                                         } else {
191                                                 ResourceBundle locale = ResourceBundle.getBundle("som",
192                                                                 getApplicationSettings().getCurrentLocale());
193                                                 SimpleDateFormat check = new SimpleDateFormat(locale
194                                                                 .getString("date.format"));
195                                                 try {
196                                                         check.parse(_documentDate);
197                                                 } catch (ParseException e) {
198                                                         setError("message.error.format.date");
199                                                         isOk = false;
200                                                 }
201                                         }
202                                 }
203                         }
204                 }
205                 return isOk;
206         }
207
208         /**
209          * Find document type by document reference.
210          * 
211          * @param fileref
212          *            the document reference
213          * @return true if succeeded, false if error
214          */
215         private boolean findTypeByDocRef(final String fileref) {
216                 boolean isOk = true;
217                 Document slot = getDocumentService().selectDocument(fileref,
218                                 new Revision().toString());
219                 if (slot == null) {
220                         setError("message.error.reference.undefined");
221                         isOk = false;
222                 } else {
223                         if (slot.isUndefined()) {
224                                 _reference = fileref; // Disables document name and state fields
225                                 deftype = slot.getType(); // Just in case
226                                 _documentType = deftype.getIndex(); // Disables the document type field
227                         } else {
228                                 setError("message.error.reference.duplicate");
229                                 isOk = false;
230                         }
231                 }
232                 return isOk;
233         }
234
235         /**
236          * Set error message and menus.
237          * 
238          * @param errorCode
239          *            error message key
240          */
241         private void setError(final String errorCode) {
242                 setErrorCode(errorCode);
243
244                 initializationFullScreenContext(Constants.STUDY_MENU, Constants.STUDY_MENU,
245                                 Constants.FALSE, Constants.NONE, Constants.STUDY_MENU);
246         }
247
248         /**
249          * Perform import of a document.
250          * 
251          * @return SUCCESS if ok, "cancel" - if canceled, ERROR - if error
252          */
253         public String doImport() {
254
255                 initializationScreenContext(Constants.STUDY_MENU, Constants.STUDY_MENU,
256                                 Constants.TRUE);
257
258                 if (action == ToDo.cancel) {
259                         return "cancel";
260                 }
261                 if (_documentType == 0) {
262                         setErrorCode("message.error.import.type");
263
264                         initializationFullScreenContext(Constants.STUDY_MENU, Constants.STUDY_MENU,
265                                         Constants.TRUE, Constants.NONE, Constants.STUDY_MENU);
266
267                         return ERROR;
268                 }
269                 try {
270                         // Getting user inputs
271                         mystudy = getOpenStudy();
272                         User user = getConnectedUser();
273                         Step step = mystudy.getSelectedStep();
274                         Date docdate = null;
275                         if (_documentDate.length() > 0) {
276                                 ResourceBundle locale = ResourceBundle.getBundle("som",
277                                                 getApplicationSettings().getCurrentLocale());
278                                 SimpleDateFormat get = new SimpleDateFormat(locale
279                                                 .getString("date.format"));
280                                 docdate = get.parse(_documentDate);
281                         }
282                         // Creation of uses relations
283                         List<Long> uses = new ArrayList<Long>();
284                         if (docuses != null) {
285                                 String[] list = docuses.split(",");
286                                 for (int i = 0; i < list.length; i++) {
287                                         uses.add(Long.valueOf(list[i].trim()));
288                                 }
289                         }
290                         if (LOG.isDebugEnabled()) {
291                                 LOG.debug("Document to be imported uses documents with following ids:");
292                                 for (Long usesId: uses) {
293                                         LOG.debug("#" + usesId);
294                                 }
295                         }
296                         Publication addoc = getPublicationService().createDoc(
297                                         mystudy.getIndex(), step, _documentType, user.getIndex(),
298                                         filename, docname, state, _reference, _version, docdate,
299                                         uses);
300
301                         if (_reference.length() > 0) { // Importation of a not foreign document
302                                 mystudy.updateSimulationContexts(); // In case of simulation contexts extracted from the imported document
303                         }
304
305                         // Creation of derived the document formats
306                         // Document ndoc = addoc.value();
307                         // Converter send = getApplicationSettings().getConverter(ndoc.getType(), ndoc.getFormat());
308                         //
309                         // if (send != null) send.converts(addoc); // Asynchronous process
310
311                         mystudy.add(addoc); // Updates the presentation
312                         return SUCCESS;
313                 } catch (FileNotFoundException error) {
314                         LOG.error("Reason:", error);
315                         setErrorCode("message.error.import.file");
316                 } catch (Exception error) {
317                         LOG.error("Reason:", error);
318                         setErrorCode("message.error.internal");
319                 }
320
321                 initializationFullScreenContext(Constants.STUDY_MENU, Constants.STUDY_MENU,
322                                 Constants.TRUE, Constants.NONE, Constants.STUDY_MENU);
323
324                 return ERROR;
325         }
326
327         // ==============================================================================================================================
328         // Getters and setters
329         // ==============================================================================================================================
330
331         /**
332          * Date extracted from the imported file, if exist.
333          * 
334          * @return the file date
335          */
336         public String getDocumentDate() {
337                 return _documentDate;
338         }
339
340         public List<DocumentType> getDocumentTypes() {
341                 return _documentTypes;
342         }
343
344         /**
345          * Get document type id.
346          * 
347          * @return document type id
348          */
349         public long getDocumentType() {
350                 return _documentType;
351         }
352
353         /**
354          * Get reference extracted from the imported file, if exist.
355          * 
356          * @return the document reference
357          */
358         public String getReference() {
359                 return _reference;
360         }
361
362         /**
363          * Get version number extracted from the imported file, if exist.
364          * 
365          * @return the document version
366          */
367         public String getVersion() {
368                 return _version;
369         }
370
371         /**
372          * Set date extracted from the imported file.
373          * 
374          * @param date
375          *            the date to set
376          */
377         public void setDocumentDate(final String date) {
378                 this._documentDate = date;
379         }
380
381         /**
382          * Set document name entered by the user if enabled.
383          * 
384          * @param name
385          *            the document name
386          */
387         public void setDocumentName(final String name) {
388                 this.docname = name; // Name entered by the user if enabled
389         }
390
391         public void setDocumentTitle(final String name) { // Called even if DocumentName is enabled
392                 if (this.docname == null) {
393                         this.docname = name;
394                 }
395         }
396
397         /**
398          * Set document type id.
399          * 
400          * @param value
401          *            the id as string
402          */
403         public void setDocumentType(final String value) {
404                 this._documentType = Integer.valueOf(value);
405         }
406
407         public void setDefaultDocumentState(final String state) { // Called even if DocumentState is enabled
408                 if (this.state == null) {
409                         this.state = ProgressState.valueOf(state);
410                 }
411         }
412
413         public void setDefaultDocumentType(final String value) { // Called even if DocumentType is enabled
414                 if (this._documentType == 0) {
415                         this._documentType = Integer.valueOf(value);
416                 }
417         }
418
419         /**
420          * Set document reference extracted from the imported file, if exist.
421          * 
422          * @param value
423          *            the reference
424          */
425         public void setReference(final String value) {
426                 this._reference = value;
427         }
428
429         /**
430          * Set version number extracted from the imported file, if exist.
431          * 
432          * @param value
433          *            the version
434          */
435         public void setVersion(final String value) {
436                 this._version = value;
437         }
438
439         /**
440          * Get project settings.
441          * 
442          * @return Project settings service
443          */
444         private ProjectSettingsService getProjectSettings() {
445                 return _projectSettings;
446         }
447
448         /**
449          * Set project settings service.
450          * 
451          * @param projectSettingsService
452          *            project settings service
453          */
454         public void setProjectSettings(
455                         final ProjectSettingsService projectSettingsService) {
456                 _projectSettings = projectSettingsService;
457         }
458
459         /**
460          * Get the publicationService.
461          * 
462          * @return the publicationService
463          */
464         public PublicationService getPublicationService() {
465                 return _publicationService;
466         }
467
468         /**
469          * Set the publicationService.
470          * 
471          * @param publicationService
472          *            the publicationService to set
473          */
474         public void setPublicationService(
475                         final PublicationService publicationService) {
476                 _publicationService = publicationService;
477         }
478
479         /**
480          * Get the stepService.
481          * 
482          * @return the stepService
483          */
484         public StepService getStepService() {
485                 return _stepService;
486         }
487
488         /**
489          * Set the stepService.
490          * 
491          * @param stepService
492          *            the stepService to set
493          */
494         public void setStepService(final StepService stepService) {
495                 _stepService = stepService;
496         }
497
498         /**
499          * Get the documentService.
500          * 
501          * @return the documentService
502          */
503         public DocumentService getDocumentService() {
504                 return _documentService;
505         }
506
507         /**
508          * Set the documentService.
509          * 
510          * @param documentService
511          *            the documentService to set
512          */
513         public void setDocumentService(final DocumentService documentService) {
514                 _documentService = documentService;
515         }
516
517         /**
518          * Get the repositoryService.
519          * 
520          * @return the repositoryService
521          */
522         public RepositoryService getRepositoryService() {
523                 return _repositoryService;
524         }
525
526         /**
527          * Set the repositoryService.
528          * 
529          * @param repositoryService
530          *            the repositoryService to set
531          */
532         public void setRepositoryService(final RepositoryService repositoryService) {
533                 _repositoryService = repositoryService;
534         }
535
536         /**
537          * Get the documentTypeService.
538          * 
539          * @return the documentTypeService
540          */
541         public DocumentTypeService getDocumentTypeService() {
542                 return _documentTypeService;
543         }
544
545         /**
546          * Set the documentTypeService.
547          * 
548          * @param documentTypeService
549          *            the documentTypeService to set
550          */
551         public void setDocumentTypeService(
552                         final DocumentTypeService documentTypeService) {
553                 _documentTypeService = documentTypeService;
554         }
555 }