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