Salome HOME
ImportDocumentAction got rid of Database class usage. EditSimulationContextAction...
[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.Arrays;
8 import java.util.Iterator;
9 import java.util.List;
10 import java.util.ResourceBundle;
11 import java.util.Vector;
12
13 import org.splat.dal.bo.kernel.User;
14 import org.splat.manox.Reader;
15 import org.splat.manox.Toolbox;
16 import org.splat.dal.bo.som.Document;
17 import org.splat.dal.bo.som.ProgressState;
18 import org.splat.service.DocumentService;
19 import org.splat.service.DocumentTypeService;
20 import org.splat.service.PublicationService;
21 import org.splat.service.StepService;
22 import org.splat.service.technical.ProjectSettingsService;
23 import org.splat.service.technical.RepositoryService;
24 import org.splat.dal.bo.som.Publication;
25 import org.splat.dal.bo.som.DocumentType;
26 import org.splat.som.Revision;
27 import org.splat.som.Step;
28
29 /**
30  * Action for adding a document into a study step.
31  */
32 public class ImportDocumentAction extends UploadBaseNextAction {
33
34         /**
35          * Serial version ID.
36          */
37         private static final long serialVersionUID = 2587822564883588556L;
38
39         private List<DocumentType> doctypes = null;
40         private long doctype = 0;
41         private String docref = null; // Reference extracted from the imported file, if exist
42         private String docver = ""; // Version number extracted from the imported file, if exist
43         private String date = ""; // Date extracted from the imported file, if exist
44         /**
45          * Injected project settings service.
46          */
47         private ProjectSettingsService _projectSettingsService;
48         /**
49          * Injected publication service.
50          */
51         private PublicationService _publicationService;
52         /**
53          * Injected step service.
54          */
55         private StepService _stepService;
56         /**
57          * Injected document service.
58          */
59         private DocumentService _documentService;
60         /**
61          * Injected document type service.
62          */
63         private DocumentTypeService _documentTypeService;
64         /**
65          * Injected repository service.
66          */
67         private RepositoryService _repositoryService;
68
69         // ==============================================================================================================================
70         // Action methods
71         // ==============================================================================================================================
72
73         /**
74          * Initialize the operation.
75          * @return SUCCESS in success, otherwise - ERROR
76          */
77         public String doInitialize() {
78                 User user = getConnectedUser();
79                 File updir = getRepositoryService().getDownloadDirectory(user);
80                 File upfile = new File(updir.getPath() + "/" + filename);
81                 String[] table = filename.split("\\x2E");
82                 String filext = table[table.length - 1].toLowerCase();
83
84                 mystudy = getOpenStudy();
85                 Step step = mystudy.getSelectedStep();
86                 doctypes = getStepService().getValidDocumentTypes(step);
87                 deftype = ApplicationSettings.getDefaultDocumentType(step, filext);
88                 defuses = new Vector<Document>();
89                 state = ProgressState.inWORK;
90
91                 Reader tool = Toolbox.getReader(upfile);
92                 if (tool != null) {
93                         String fileref = tool.extractProperty("reference");
94                         String filever = tool.extractProperty("version"); // Property kept even if the file is not referenced
95                         String filetype = tool.extractProperty("type"); // Property kept even if the file is not referenced
96                         for (Iterator<DocumentType> i = doctypes.iterator(); i.hasNext();) {
97                                 DocumentType type = i.next();
98                                 if (!type.getName().equals(filetype))
99                                         continue;
100                                 deftype = type;
101                                 doctype = type.getIndex(); // Disables the document type field
102                                 break;
103                         }
104                         if (fileref != null) {
105                                 Document slot = getDocumentService().selectDocument(fileref,
106                                                 new Revision().toString());
107                                 if (slot == null) {
108                                         setErrorCode("reference.undefined");
109                                         return ERROR;
110                                 } else {
111                                         if (!slot.isUndefined()) {
112                                                 setErrorCode("reference.duplicate");
113                                                 return ERROR;
114                                         }
115                                         docref = fileref; // Disables document name and state fields
116                                         deftype = slot.getType(); // Just in case
117                                         doctype = deftype.getIndex(); // Disables the document type field
118                                 }
119                         }
120                         if (filever != null)
121                                 try {
122                                         Revision.Format get = new Revision.Format(
123                                                         getProjectSettings().getRevisionPattern());
124                                         Revision version = get.parse(filever);
125                                         if (version.isNull())
126                                                 throw new ParseException(filever, filever.length() - 1);
127                                         if (!version.isMinor())
128                                                 state = ProgressState.inCHECK;
129                                         docver = version.toString();
130                                 } catch (ParseException e) {
131                                         setErrorCode("format.version");
132                                         return ERROR;
133                                 }
134                         docname = tool.extractProperty("title"); // Property kept even if the file is not referenced
135                         date = tool.extractProperty("date");
136                         if (date != null) {
137                                 ResourceBundle locale = ResourceBundle.getBundle("som",
138                                                 ApplicationSettings.getCurrentLocale());
139                                 SimpleDateFormat check = new SimpleDateFormat(
140                                                 locale.getString("date.format"));
141                                 try {
142                                         check.parse(date);
143                                 } catch (ParseException e) {
144                                         setErrorCode("format.date");
145                                         return ERROR;
146                                 }
147                         } else
148                                 date = "";
149                 } else if (filext.equals("pdf"))
150                         state = ProgressState.EXTERN; // TODO: Should external extensions be configurable ?
151                 if (docname == null) {
152                         docname = table[0];
153                         for (int i = 1; i < table.length - 1; i++)
154                                 docname = docname + "." + table[i];
155                 }
156                 if (deftype != null)
157                         setupDefaultUses(deftype);
158
159                 DocumentType[] types = doctypes.toArray(new DocumentType[doctypes
160                                 .size()]);
161                 DocumentTypeComparator compare = new DocumentTypeComparator();
162                 Arrays.sort(types, compare);
163                 doctypes = Arrays.asList(types);
164
165                 return SUCCESS;
166         }
167
168         /**
169          * Perform import of a document.
170          * @return SUCCESS if ok, "cancel" - if canceled, ERROR - if error
171          */
172         public String doImport() {
173                 // -------------------------
174                 if (action == ToDo.cancel)
175                         return "cancel";
176                 if (doctype == 0) {
177                         setErrorCode("import.type");
178                         return ERROR;
179                 }
180                 try {
181                         // Getting user inputs
182                         mystudy = getOpenStudy();
183                         User user = getConnectedUser();
184                         Step step = mystudy.getSelectedStep();
185                         DocumentType type = getDocumentTypeService().selectType((int)doctype);
186                         File updir = getRepositoryService().getDownloadDirectory(user);
187                         File upfile = new File(updir.getPath() + "/" + filename);
188                         String[] table = filename.split("\\x2E");
189
190                         // Creation of the document
191                         Document.Properties dprop = new Document.Properties();
192                         Publication addoc;
193
194                         if (docref.length() == 0) { // Importation of a foreign document
195                         // TODO: Extract property of supported documents (DOCX, ODT...)
196                                 addoc = getStepService().createDocument(step, dprop.setName(docname)
197                                                 .setType(type).setFormat(table[table.length - 1])
198                                                 .setAuthor(user));
199                                 updir = addoc.getSourceFile().asFile();
200                                 if (logger.isInfoEnabled())
201                                         logger.info("Moving \"" + upfile.getName() + "\" to \""
202                                                         + updir.getPath() + "\".");
203                                 upfile.renameTo(updir);
204                                 try {
205                                         getPublicationService().saveAs(addoc, state); // May throw FileNotFound if rename was not done
206                                 } catch (FileNotFoundException saverror) {
207                                         Thread.sleep(1000);
208                                         logger.info("Waiting for the file.");
209                                         upfile.renameTo(updir);
210                                         getPublicationService().saveAs(addoc, state); // Forget it if throw again FileNotFound
211                                 }
212                         } else { // Importation of a previously created template-based document
213                                 if (date.length() > 0) {
214                                         ResourceBundle locale = ResourceBundle.getBundle("som",
215                                                         ApplicationSettings.getCurrentLocale());
216                                         SimpleDateFormat get = new SimpleDateFormat(
217                                                         locale.getString("date.format"));
218                                         dprop.setDate(get.parse(date));
219                                 }
220                                 addoc = getStepService().assignDocument(step, dprop.setReference(docref).setName(
221                                                 docname));
222                                 updir = addoc.getSourceFile().asFile();
223                                 if (logger.isInfoEnabled())
224                                         logger.info("Moving \"" + upfile.getName() + "\" to \""
225                                                         + updir.getPath() + "\".");
226                                 upfile.renameTo(updir);
227                                 try {
228                                         if (docver.length() > 0)
229                                                 getPublicationService().saveAs(addoc,
230                                                                 new Revision(docver));
231                                         else
232                                                 getPublicationService().saveAs(addoc, state);
233                                 } catch (FileNotFoundException saverror) {
234                                         Thread.sleep(1000);
235                                         logger.info("Waiting for the file.");
236                                         upfile.renameTo(updir);
237                                         if (docver.length() > 0)
238                                                 getPublicationService().saveAs(addoc,
239                                                                 new Revision(docver));
240                                         else
241                                                 getPublicationService().saveAs(addoc, state);
242                                 }
243                                 mystudy.updateSimulationContexts(); // In case of simulation contexts extracted from the imported document
244                         }
245                         // Creation of uses relations
246                         if (docuses != null) {
247                                 String[] list = docuses.split(",");
248                                 for (int i = 0; i < list.length; i++) {
249                                         Integer index = Integer.valueOf(list[i].trim());
250                                         Publication used = getPublication(index);
251                                         addoc.addDependency(used);
252                                 }
253                         }
254                         // Creation of derived the document formats
255                         // Document ndoc = addoc.value();
256                         // Converter send = ApplicationSettings.getConverter(ndoc.getType(), ndoc.getFormat());
257                         //
258                         // if (send != null) send.converts(addoc); // Asynchronous process
259
260                         mystudy.add(addoc); // Updates the presentation
261                         return SUCCESS;
262                 } catch (FileNotFoundException error) {
263                         logger.error("Reason:", error);
264                         setErrorCode("import.file");
265                 } catch (Exception error) {
266                         logger.error("Reason:", error);
267                         setErrorCode("internal");
268                 }
269                 return ERROR;
270         }
271
272         // ==============================================================================================================================
273         // Getters and setters
274         // ==============================================================================================================================
275
276         public String getDocumentDate() {
277                 // --------------------------------
278                 return date;
279         }
280
281         public List<DocumentType> getDocumentTypes() {
282                 // ---------------------------------------------
283                 return doctypes;
284         }
285
286         public long getDocumentType() {
287                 // -----------------------------
288                 return doctype;
289         }
290
291         public String getReference() {
292                 // -----------------------------
293                 return docref;
294         }
295
296         public String getVersion() {
297                 // ---------------------------
298                 return docver;
299         }
300
301         public void setDocumentDate(String date) {
302                 // -----------------------------------------
303                 this.date = date;
304         }
305
306         public void setDocumentName(String name) {
307                 // -----------------------------------------
308                 this.docname = name; // Name entered by the user if enabled
309         }
310
311         public void setDocumentTitle(String name) { // Called even if DocumentName is enabled
312         // -----------------------------------------
313                 if (this.docname == null)
314                         this.docname = name;
315         }
316
317         public void setDocumentType(String value) {
318                 // ------------------------------------------
319                 this.doctype = Integer.valueOf(value);
320         }
321
322         public void setDefaultDocumentState(String state) { // Called even if DocumentState is enabled
323         // --------------------------------------------------
324                 if (this.state == null)
325                         this.state = ProgressState.valueOf(state);
326         }
327
328         public void setDefaultDocumentType(String value) { // Called even if DocumentType is enabled
329         // --------------------------------------------------
330                 if (this.doctype == 0)
331                         this.doctype = Integer.valueOf(value);
332         }
333
334         public void setReference(String value) {
335                 // ---------------------------------------
336                 this.docref = value;
337         }
338
339         public void setVersion(String value) {
340                 // -------------------------------------
341                 this.docver = value;
342         }
343
344         /**
345          * Get project settings.
346          * 
347          * @return Project settings service
348          */
349         private ProjectSettingsService getProjectSettings() {
350                 return _projectSettingsService;
351         }
352
353         /**
354          * Set project settings service.
355          * 
356          * @param projectSettingsService
357          *            project settings service
358          */
359         public void setProjectSettings(ProjectSettingsService projectSettingsService) {
360                 _projectSettingsService = projectSettingsService;
361         }
362
363         /**
364          * Get the publicationService.
365          * 
366          * @return the publicationService
367          */
368         public PublicationService getPublicationService() {
369                 return _publicationService;
370         }
371
372         /**
373          * Set the publicationService.
374          * 
375          * @param publicationService
376          *            the publicationService to set
377          */
378         public void setPublicationService(PublicationService publicationService) {
379                 _publicationService = publicationService;
380         }
381
382         /**
383          * Get the stepService.
384          * @return the stepService
385          */
386         public StepService getStepService() {
387                 return _stepService;
388         }
389
390         /**
391          * Set the stepService.
392          * @param stepService the stepService to set
393          */
394         public void setStepService(StepService stepService) {
395                 _stepService = stepService;
396         }
397
398         /**
399          * Get the documentService.
400          * @return the documentService
401          */
402         public DocumentService getDocumentService() {
403                 return _documentService;
404         }
405
406         /**
407          * Set the documentService.
408          * @param documentService the documentService to set
409          */
410         public void setDocumentService(DocumentService documentService) {
411                 _documentService = documentService;
412         }
413
414         /**
415          * Get the repositoryService.
416          * @return the repositoryService
417          */
418         public RepositoryService getRepositoryService() {
419                 return _repositoryService;
420         }
421
422         /**
423          * Set the repositoryService.
424          * @param repositoryService the repositoryService to set
425          */
426         public void setRepositoryService(RepositoryService repositoryService) {
427                 _repositoryService = repositoryService;
428         }
429
430         /**
431          * Get the documentTypeService.
432          * @return the documentTypeService
433          */
434         public DocumentTypeService getDocumentTypeService() {
435                 return _documentTypeService;
436         }
437
438         /**
439          * Set the documentTypeService.
440          * @param documentTypeService the documentTypeService to set
441          */
442         public void setDocumentTypeService(DocumentTypeService documentTypeService) {
443                 _documentTypeService = documentTypeService;
444         }
445 }