Salome HOME
Fix for mantis #0022093: To exclude the "In-Draft" state from drop-down list during...
[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.dal.bo.som.ValidationCycle;
20 import org.splat.dal.bo.som.ValidationStep;
21 import org.splat.manox.Reader;
22 import org.splat.manox.Toolbox;
23 import org.splat.service.DocumentService;
24 import org.splat.service.DocumentTypeService;
25 import org.splat.som.Revision;
26 import org.splat.som.Step;
27 import org.splat.wapp.Constants;
28
29 /**
30  * Action for adding a document into a study step.
31  */
32 public class ImportDocumentAction extends BaseUploadDocumentAction {
33
34         /**
35          * Serial version ID.
36          */
37         private static final long serialVersionUID = 2587822564883588556L;
38
39         /**
40          * Sorted list of document types for the selected study step.
41          */
42         private transient List<DocumentType> _documentTypes = null;
43         /**
44          * Sorted list of document types for the selected study step.
45          */
46         private transient final List<Boolean> _reviewable = new ArrayList<Boolean>();
47         /**
48          * The selected document type.
49          */
50         private long _documentType = 0;
51         /**
52          * Reference extracted from the imported file, if exist.
53          */
54         private String _reference = null;
55         /**
56          * Injected document service.
57          */
58         private DocumentService _documentService;
59         /**
60          * Injected document type service.
61          */
62         private DocumentTypeService _documentTypeService;
63
64         /**
65          * Initialize the operation.
66          * 
67          * @return SUCCESS in success, otherwise - ERROR
68          */
69         public String doInitialize() {
70
71                 File upfile = commonInitialize(Constants.FALSE);
72                 String[] table = _fileName.split("\\x2E");
73                 String filext = table[table.length - 1].toLowerCase();
74
75                 _mystudy = getOpenStudy();
76                 Step step = _mystudy.getSelectedStep();
77                 _documentTypes = getStepService().getValidDocumentTypes(step);
78                 // Set the document type by default
79                 _deftype = getApplicationSettings().getDefaultDocumentType(step, filext);
80                 if (_deftype != null) {
81                         setDefaultDocumentType(_deftype.getIndex());
82                 }
83                 _defuses = new ArrayList<Document>();
84                 _state = ProgressState.inWORK;
85
86                 String res = ERROR;
87                 if (extractProperties(upfile, filext)) {
88                         if (_docname == null) {
89                                 _docname = table[0];
90                                 for (int i = 1; i < table.length - 1; i++) {
91                                         _docname = _docname + "." + table[i];
92                                 }
93                         }
94                         if (_deftype != null) {
95                                 setupDefaultUses(_deftype);
96                         }
97
98                         DocumentType[] types = _documentTypes
99                                         .toArray(new DocumentType[_documentTypes.size()]);
100                         DocumentTypeComparator compare = new DocumentTypeComparator();
101                         Arrays.sort(types, compare);
102                         _documentTypes = Arrays.asList(types);
103                         res = SUCCESS;
104                 }
105
106                 // Initialize isReviewable: if a type has review state or not
107                 ValidationCycle cycle;
108                 boolean hasReview;
109                 for (DocumentType dtype : _documentTypes) {
110                         cycle = getStudyService().getValidationCycleOf(
111                                         _mystudy.getMystudy(), dtype);
112                         hasReview = (cycle != null) && cycle.enables(ValidationStep.REVIEW);
113                         _reviewable.add(hasReview);
114                 }
115                 return res;
116         }
117
118         /**
119          * Extract properties from the uploaded file.
120          * 
121          * @param upfile
122          *            the file to parse
123          * @param filext
124          *            the file extension
125          * @return true if succeeded, false if error
126          */
127         private boolean extractProperties(final File upfile, final String filext) {
128                 boolean isOk = true;
129                 Reader tool = Toolbox.getReader(upfile);
130                 if (tool == null) {
131                         if ("pdf".equals(filext)) {
132                                 _state = ProgressState.EXTERN; // TODO: Should external extensions be configurable ?
133                         }
134                 } else {
135                         String fileref = tool.extractProperty("reference");
136                         String filever = tool.extractProperty("version"); // Property kept even if the file is not referenced
137                         String filetype = tool.extractProperty("type"); // Property kept even if the file is not referenced
138                         for (Iterator<DocumentType> i = _documentTypes.iterator(); i
139                                         .hasNext();) {
140                                 DocumentType type = i.next();
141                                 if (type.getName().equals(filetype)) {
142                                         _deftype = type;
143                                         _documentType = type.getIndex(); // Disables the document type field
144                                         break;
145                                 }
146                         }
147                         if (fileref != null) {
148                                 isOk = findTypeByDocRef(fileref);
149                         }
150                         if (isOk) {
151                                 if (filever != null) {
152                                         try {
153                                                 Revision.Format get = new Revision.Format(
154                                                                 getProjectSettings().getRevisionPattern());
155                                                 Revision version = get.parse(filever);
156                                                 if (version.isNull()) {
157                                                         throw new ParseException(filever,
158                                                                         filever.length() - 1);
159                                                 }
160                                                 if (!version.isMinor()) {
161                                                         _state = ProgressState.inCHECK;
162                                                 }
163                                                 setVersion(version.toString());
164                                         } catch (ParseException e) {
165                                                 setErrorCode("message.error.format.version");
166                                                 isOk = false;
167                                         }
168                                 }
169                                 if (isOk) {
170                                         _docname = tool.extractProperty("title"); // Property kept even if the file is not referenced
171                                         isOk = extractDate(tool);
172                                 }
173                         }
174                 }
175                 return isOk;
176         }
177
178         /**
179          * Find document type by document reference.
180          * 
181          * @param fileref
182          *            the document reference
183          * @return true if succeeded, false if error
184          */
185         private boolean findTypeByDocRef(final String fileref) {
186                 boolean isOk = true;
187                 Document slot = getDocumentService().selectDocument(fileref,
188                                 new Revision().toString());
189                 if (slot == null) {
190                         setError("message.error.reference.undefined");
191                         isOk = false;
192                 } else {
193                         if (slot.isUndefined()) {
194                                 _reference = fileref; // Disables document name and state fields
195                                 _deftype = slot.getType(); // Just in case
196                                 _documentType = _deftype.getIndex(); // Disables the document type field
197                         } else {
198                                 setError("message.error.reference.duplicate");
199                                 isOk = false;
200                         }
201                 }
202                 return isOk;
203         }
204
205         /**
206          * Perform import of a document.
207          * 
208          * @return SUCCESS if ok, "cancel" - if canceled, ERROR - if error
209          */
210         public String doImport() {
211                 String res = ERROR;
212
213                 initializationScreenContext(Constants.STUDY_MENU, Constants.STUDY_MENU,
214                                 Constants.TRUE);
215
216                 if (_action == ToDo.cancel) {
217                         res = "cancel";
218                 } else if (_documentType == 0) {
219                         setErrorCode("message.error.import.type");
220
221                         initializationFullScreenContext(Constants.STUDY_MENU,
222                                         Constants.STUDY_MENU, Constants.TRUE, Constants.NONE,
223                                         Constants.STUDY_MENU);
224                 } else {
225                         try {
226                                 // Getting user inputs
227                                 _mystudy = getOpenStudy();
228                                 User user = getConnectedUser();
229                                 Step step = _mystudy.getSelectedStep();
230                                 Date aDate = null;
231                                 if (getDocumentDate().length() > 0) {
232                                         ResourceBundle locale = ResourceBundle.getBundle("som",
233                                                         getApplicationSettings().getCurrentLocale());
234                                         SimpleDateFormat get = new SimpleDateFormat(locale
235                                                         .getString("date.format"), getApplicationSettings()
236                                                         .getCurrentLocale());
237                                         aDate = get.parse(getDocumentDate());
238                                 }
239                                 // Creation of uses relations
240                                 List<Long> uses = new ArrayList<Long>();
241                                 if (_docuses != null) {
242                                         String[] list = _docuses.split(",");
243                                         for (int i = 0; i < list.length; i++) {
244                                                 uses.add(Long.valueOf(list[i].trim()));
245                                         }
246                                 }
247                                 if (LOG.isDebugEnabled()) {
248                                         LOG
249                                                         .debug("Document to be imported uses documents with following ids:");
250                                         for (Long usesId : uses) {
251                                                 LOG.debug("#" + usesId);
252                                         }
253                                 }
254                                 Publication addoc = getPublicationService().createDoc(
255                                                 _mystudy.getIndex(), step, _documentType,
256                                                 user.getIndex(), _fileName, _docname, _state, _reference,
257                                                 getVersion(), aDate, uses);
258
259                                 if (_reference.length() > 0) { // Importation of a not foreign document
260                                         _mystudy.updateSimulationContexts(); // In case of simulation contexts extracted from the imported document
261                                 }
262
263                                 // Creation of derived the document formats
264                                 // Document ndoc = addoc.value();
265                                 // Converter send = getApplicationSettings().getConverter(ndoc.getType(), ndoc.getFormat());
266                                 //
267                                 // if (send != null) send.converts(addoc); // Asynchronous process
268
269                                 _mystudy.add(addoc); // Updates the presentation
270                                 res = SUCCESS;
271                         } catch (FileNotFoundException error) {
272                                 LOG.error("Reason:", error);
273                                 setErrorCode("message.error.import.file");
274                         } catch (Exception error) {
275                                 LOG.error("Reason:", error);
276                                 setErrorCode("message.error.internal");
277                         }
278
279                         if (!SUCCESS.equals(res)) {
280                                 initializationFullScreenContext(Constants.STUDY_MENU,
281                                                 Constants.STUDY_MENU, Constants.TRUE, Constants.NONE,
282                                                 Constants.STUDY_MENU);
283                         }
284                 }
285
286                 return res;
287         }
288
289         // ==============================================================================================================================
290         // Getters and setters
291         // ==============================================================================================================================
292
293         /**
294          * Get sorted list of document types valid for the selected study step.
295          * 
296          * @return sorted list of document types
297          */
298         public List<DocumentType> getDocumentTypes() {
299                 return _documentTypes;
300         }
301
302         /**
303          * Get document type id.
304          * 
305          * @return document type id
306          */
307         public long getDocumentType() {
308                 return _documentType;
309         }
310
311         /**
312          * Get reference extracted from the imported file, if exist.
313          * 
314          * @return the document reference
315          */
316         public String getReference() {
317                 return _reference;
318         }
319
320         /**
321          * Set document name entered by the user if enabled.
322          * 
323          * @param name
324          *            the document name
325          */
326         public void setDocumentName(final String name) {
327                 this._docname = name; // Name entered by the user if enabled
328         }
329
330         /**
331          * Set the default title if no title was defined.
332          * 
333          * @param name
334          *            the default document title
335          */
336         public void setDocumentTitle(final String name) { // Called even if DocumentName is enabled
337                 if (this._docname == null) {
338                         this._docname = name;
339                 }
340         }
341
342         /**
343          * Set document type id.
344          * 
345          * @param value
346          *            the id as string
347          */
348         public void setDocumentType(final Long value) {
349                 this._documentType = value;
350         }
351
352         /**
353          * Set the default state if no state was selected.
354          * 
355          * @param state
356          *            the default state
357          */
358         public void setDefaultDocumentState(final String state) { // Called even if DocumentState is enabled
359                 if (this._state == null) {
360                         this._state = ProgressState.valueOf(state);
361                 }
362         }
363
364         /**
365          * Set the default type if no type was selected.
366          * 
367          * @param value
368          *            the default document type id
369          */
370         public void setDefaultDocumentType(final Long value) { // Called even if DocumentType is enabled
371                 if (this._documentType == 0) {
372                         this._documentType = value;
373                 }
374         }
375
376         /**
377          * Set document reference extracted from the imported file, if exist.
378          * 
379          * @param value
380          *            the reference
381          */
382         public void setReference(final String value) {
383                 this._reference = value;
384         }
385
386         /**
387          * Get the documentService.
388          * 
389          * @return the documentService
390          */
391         public DocumentService getDocumentService() {
392                 return _documentService;
393         }
394
395         /**
396          * Set the documentService.
397          * 
398          * @param documentService
399          *            the documentService to set
400          */
401         public void setDocumentService(final DocumentService documentService) {
402                 _documentService = documentService;
403         }
404
405         /**
406          * Get the documentTypeService.
407          * 
408          * @return the documentTypeService
409          */
410         public DocumentTypeService getDocumentTypeService() {
411                 return _documentTypeService;
412         }
413
414         /**
415          * Set the documentTypeService.
416          * 
417          * @param documentTypeService
418          *            the documentTypeService to set
419          */
420         public void setDocumentTypeService(
421                         final DocumentTypeService documentTypeService) {
422                 _documentTypeService = documentTypeService;
423         }
424
425         /**
426          * Get sorted list of available document states.
427          * 
428          * @return the documentStates
429          */
430         public List<ProgressState> getDocumentStates() {
431                 List<ProgressState> states = new ArrayList<ProgressState>();
432                 states.add(ProgressState.inWORK);
433                 states.add(ProgressState.inDRAFT);
434                 states.add(ProgressState.EXTERN);
435                 return states;
436         }
437
438         /**
439          * Get the isReviewable.
440          * 
441          * @return the isReviewable
442          */
443         public List<Boolean> getReviewable() {
444                 return _reviewable;
445         }
446 }