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.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.technical.ProjectSettingsService;
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;
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
36 private ProjectSettingsService _projectSettingsService;
37 private PublicationService _publicationService;
39 private static final long serialVersionUID = 2587822564883588556L;
41 // ==============================================================================================================================
43 // ==============================================================================================================================
45 public String doInitialize() {
46 // -----------------------------
47 Session connex = Database.getSession();
48 Transaction transax = connex.beginTransaction();
49 User user = getConnectedUser();
50 File updir = Database.getDownloadDirectory(user);
51 File upfile = new File(updir.getPath() + "/" + filename);
52 String[] table = filename.split("\\x2E");
53 String filext = table[table.length - 1].toLowerCase();
55 mystudy = getOpenStudy();
56 Step step = mystudy.getSelectedStep();
57 doctypes = step.getValidDocumentTypes();
58 deftype = ApplicationSettings.getDefaultDocumentType(step, filext);
59 defuses = new Vector<Document>();
60 state = ProgressState.inWORK;
62 Reader tool = Toolbox.getReader(upfile);
64 String fileref = tool.extractProperty("reference");
65 String filever = tool.extractProperty("version"); // Property kept even if the file is not referenced
66 String filetype = tool.extractProperty("type"); // Property kept even if the file is not referenced
67 for (Iterator<DocumentType> i = doctypes.iterator(); i.hasNext();) {
68 DocumentType type = i.next();
69 if (!type.getName().equals(filetype))
72 doctype = type.getIndex(); // Disables the document type field
75 if (fileref != null) {
76 Document slot = Database.selectDocument(fileref,
77 new Revision().toString());
79 setErrorCode("reference.undefined");
82 if (!slot.isUndefined()) {
83 setErrorCode("reference.duplicate");
86 docref = fileref; // Disables document name and state fields
87 deftype = slot.getType(); // Just in case
88 doctype = deftype.getIndex(); // Disables the document type field
93 Revision.Format get = new Revision.Format(
94 getProjectSettings().getRevisionPattern());
95 Revision version = get.parse(filever);
97 throw new ParseException(filever, filever.length() - 1);
98 if (!version.isMinor())
99 state = ProgressState.inCHECK;
100 docver = version.toString();
101 } catch (ParseException e) {
102 setErrorCode("format.version");
105 docname = tool.extractProperty("title"); // Property kept even if the file is not referenced
106 date = tool.extractProperty("date");
108 ResourceBundle locale = ResourceBundle.getBundle("som",
109 ApplicationSettings.getCurrentLocale());
110 SimpleDateFormat check = new SimpleDateFormat(
111 locale.getString("date.format"));
114 } catch (ParseException e) {
115 setErrorCode("format.date");
120 } else if (filext.equals("pdf"))
121 state = ProgressState.EXTERN; // TODO: Should external extensions be configurable ?
122 if (docname == null) {
124 for (int i = 1; i < table.length - 1; i++)
125 docname = docname + "." + table[i];
128 setupDefaultUses(deftype);
130 DocumentType[] types = doctypes.toArray(new DocumentType[doctypes
132 DocumentTypeComparator compare = new DocumentTypeComparator();
133 Arrays.sort(types, compare);
134 doctypes = Arrays.asList(types);
140 public String doImport() {
141 // -------------------------
142 if (action == ToDo.cancel)
145 setErrorCode("import.type");
148 Session connex = Database.getSession();
149 Transaction transax = connex.beginTransaction();
151 // Getting user inputs
152 mystudy = getOpenStudy();
153 User user = getConnectedUser();
154 Step step = mystudy.getSelectedStep();
155 DocumentType type = Document.selectType(doctype);
156 File updir = Database.getDownloadDirectory(user);
157 File upfile = new File(updir.getPath() + "/" + filename);
158 String[] table = filename.split("\\x2E");
160 // Creation of the document
161 Document.Properties dprop = new Document.Properties();
164 if (docref.length() == 0) { // Importation of a foreign document
165 // TODO: Extract property of supported documents (DOCX, ODT...)
166 addoc = step.createDocument(dprop.setName(docname)
167 .setType(type).setFormat(table[table.length - 1])
169 updir = addoc.getSourceFile().asFile();
170 if (logger.isInfoEnabled())
171 logger.info("Moving \"" + upfile.getName() + "\" to \""
172 + updir.getPath() + "\".");
173 upfile.renameTo(updir);
175 getPublicationService().saveAs(addoc, state); // May throw FileNotFound if rename was not done
176 } catch (FileNotFoundException saverror) {
178 logger.info("Waiting for the file.");
179 upfile.renameTo(updir);
180 getPublicationService().saveAs(addoc, state); // Forget it if throw again FileNotFound
182 } else { // Importation of a previously created template-based document
183 if (date.length() > 0) {
184 ResourceBundle locale = ResourceBundle.getBundle("som",
185 ApplicationSettings.getCurrentLocale());
186 SimpleDateFormat get = new SimpleDateFormat(
187 locale.getString("date.format"));
188 dprop.setDate(get.parse(date));
190 addoc = step.assignDocument(dprop.setReference(docref).setName(
192 updir = addoc.getSourceFile().asFile();
193 if (logger.isInfoEnabled())
194 logger.info("Moving \"" + upfile.getName() + "\" to \""
195 + updir.getPath() + "\".");
196 upfile.renameTo(updir);
198 if (docver.length() > 0)
199 getPublicationService().saveAs(addoc,
200 new Revision(docver));
202 getPublicationService().saveAs(addoc, state);
203 } catch (FileNotFoundException saverror) {
205 logger.info("Waiting for the file.");
206 upfile.renameTo(updir);
207 if (docver.length() > 0)
208 getPublicationService().saveAs(addoc,
209 new Revision(docver));
211 getPublicationService().saveAs(addoc, state);
213 mystudy.updateSimulationContexts(); // In case of simulation contexts extracted from the imported document
215 // Creation of uses relations
216 if (docuses != null) {
217 String[] list = docuses.split(",");
218 for (int i = 0; i < list.length; i++) {
219 Integer index = Integer.valueOf(list[i].trim());
220 Publication used = getPublication(index);
221 addoc.addDependency(used);
224 // Creation of derived the document formats
225 // Document ndoc = addoc.value();
226 // Converter send = ApplicationSettings.getConverter(ndoc.getType(), ndoc.getFormat());
228 // if (send != null) send.converts(addoc); // Asynchronous process
231 mystudy.add(addoc); // Updates the presentation
233 } catch (FileNotFoundException error) {
234 logger.error("Reason:", error);
235 setErrorCode("import.file");
236 } catch (Exception error) {
237 logger.error("Reason:", error);
238 setErrorCode("internal");
240 if (transax != null && transax.isActive()) { // Probably useless test
241 // Second try-catch as the rollback could fail as well
244 } catch (HibernateException backerror) {
245 logger.debug("Error rolling back transaction", backerror);
251 // ==============================================================================================================================
252 // Getters and setters
253 // ==============================================================================================================================
255 public String getDocumentDate() {
256 // --------------------------------
260 public List<DocumentType> getDocumentTypes() {
261 // ---------------------------------------------
265 public int getDocumentType() {
266 // -----------------------------
270 public String getReference() {
271 // -----------------------------
275 public String getVersion() {
276 // ---------------------------
280 public void setDocumentDate(String date) {
281 // -----------------------------------------
285 public void setDocumentName(String name) {
286 // -----------------------------------------
287 this.docname = name; // Name entered by the user if enabled
290 public void setDocumentTitle(String name) { // Called even if DocumentName is enabled
291 // -----------------------------------------
292 if (this.docname == null)
296 public void setDocumentType(String value) {
297 // ------------------------------------------
298 this.doctype = Integer.valueOf(value);
301 public void setDefaultDocumentState(String state) { // Called even if DocumentState is enabled
302 // --------------------------------------------------
303 if (this.state == null)
304 this.state = ProgressState.valueOf(state);
307 public void setDefaultDocumentType(String value) { // Called even if DocumentType is enabled
308 // --------------------------------------------------
309 if (this.doctype == 0)
310 this.doctype = Integer.valueOf(value);
313 public void setReference(String value) {
314 // ---------------------------------------
318 public void setVersion(String value) {
319 // -------------------------------------
324 * Get project settings.
326 * @return Project settings service
328 private ProjectSettingsService getProjectSettings() {
329 return _projectSettingsService;
333 * Set project settings service.
335 * @param projectSettingsService
336 * project settings service
338 public void setProjectSettings(ProjectSettingsService projectSettingsService) {
339 _projectSettingsService = projectSettingsService;
343 * Get the publicationService.
345 * @return the publicationService
347 public PublicationService getPublicationService() {
348 return _publicationService;
352 * Set the publicationService.
354 * @param publicationService
355 * the publicationService to set
357 public void setPublicationService(PublicationService publicationService) {
358 _publicationService = publicationService;