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