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