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