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