1 package org.splat.simer;
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;
10 import java.util.ResourceBundle;
11 import java.util.Vector;
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;
29 public class ImportDocumentAction extends UploadBaseNextAction {
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
37 private static final long serialVersionUID = 2587822564883588556L;
39 // ==============================================================================================================================
41 // ==============================================================================================================================
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();
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;
60 Reader tool = Toolbox.getReader(upfile);
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;
69 doctype = type.getIndex(); // Disables the document type field
72 if (fileref != null) {
73 Document slot = Database.selectDocument(fileref, new Revision().toString());
75 setErrorCode("reference.undefined");
79 if (!slot.isUndefined()) {
80 setErrorCode("reference.duplicate");
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
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");
98 docname = tool.extractProperty("title"); // Property kept even if the file is not referenced
99 date = tool.extractProperty("date");
101 ResourceBundle locale = ResourceBundle.getBundle("som", ApplicationSettings.getCurrentLocale());
102 SimpleDateFormat check = new SimpleDateFormat(locale.getString("date.format"));
105 } catch (ParseException e) {
106 setErrorCode("format.date");
111 if (filext.equals("pdf")) state = ProgressState.EXTERN; //TODO: Should external extensions be configurable ?
112 if (docname == null) {
114 for (int i=1; i<table.length-1; i++) docname = docname + "." + table[i];
116 if (deftype != null) setupDefaultUses(deftype);
118 DocumentType[] types = doctypes.toArray( new DocumentType[doctypes.size()] );
119 DocumentTypeComparator compare = new DocumentTypeComparator();
120 Arrays.sort(types, compare);
121 doctypes = Arrays.asList(types);
127 public String doImport () {
128 // -------------------------
129 if (action == ToDo.cancel) return "cancel";
131 setErrorCode("import.type");
134 Session connex = Database.getSession();
135 Transaction transax = connex.beginTransaction();
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");
146 // Creation of the document
147 Document.Properties dprop = new Document.Properties();
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);
157 addoc.saveAs(state); // May throw FileNotFound if rename was not done
158 } catch (FileNotFoundException saverror) {
160 logger.info("Waiting for the file.");
161 upfile.renameTo(updir);
162 addoc.saveAs(state); // Forget it if throw again FileNotFound
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));
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);
176 if (docver.length() > 0) addoc.saveAs(new Revision(docver));
177 else addoc.saveAs(state);
178 } catch (FileNotFoundException saverror) {
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);
185 mystudy.updateSimulationContexts(); // In case of simulation contexts extracted from the imported document
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);
196 // Creation of derived the document formats
197 // Document ndoc = addoc.value();
198 // Converter send = ApplicationSettings.getConverter(ndoc.getType(), ndoc.getFormat());
200 // if (send != null) send.converts(addoc); // Asynchronous process
203 mystudy.add(addoc); // Updates the presentation
206 catch (FileNotFoundException error) {
207 logger.error("Reason:", error);
208 setErrorCode("import.file");
210 catch (Exception error) {
211 logger.error("Reason:", error);
212 setErrorCode("internal");
214 if (transax != null && transax.isActive()) { // Probably useless test
215 // Second try-catch as the rollback could fail as well
218 } catch (HibernateException backerror) {
219 logger.debug("Error rolling back transaction", backerror);
225 // ==============================================================================================================================
226 // Getters and setters
227 // ==============================================================================================================================
229 public String getDocumentDate () {
230 // --------------------------------
233 public List<DocumentType> getDocumentTypes () {
234 // ---------------------------------------------
237 public int getDocumentType () {
238 // -----------------------------
241 public String getReference () {
242 // -----------------------------
245 public String getVersion () {
246 // ---------------------------
250 public void setDocumentDate (String date) {
251 // -----------------------------------------
254 public void setDocumentName (String name) {
255 // -----------------------------------------
256 this.docname = name; // Name entered by the user if enabled
258 public void setDocumentTitle (String name) { // Called even if DocumentName is enabled
259 // -----------------------------------------
260 if (this.docname == null) this.docname = name;
262 public void setDocumentType (String value) {
263 // ------------------------------------------
264 this.doctype = Integer.valueOf(value);
266 public void setDefaultDocumentState (String state) { // Called even if DocumentState is enabled
267 // --------------------------------------------------
268 if (this.state == null) this.state = ProgressState.valueOf(state);
270 public void setDefaultDocumentType (String value) { // Called even if DocumentType is enabled
271 // --------------------------------------------------
272 if (this.doctype == 0) this.doctype = Integer.valueOf(value);
274 public void setReference (String value) {
275 // ---------------------------------------
278 public void setVersion (String value) {
279 // -------------------------------------