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