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.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;
30 public class ImportDocumentAction extends UploadBaseNextAction {
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;
41 private static final long serialVersionUID = 2587822564883588556L;
43 // ==============================================================================================================================
45 // ==============================================================================================================================
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();
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;
64 Reader tool = Toolbox.getReader(upfile);
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))
74 doctype = type.getIndex(); // Disables the document type field
77 if (fileref != null) {
78 Document slot = Database.selectDocument(fileref,
79 new Revision().toString());
81 setErrorCode("reference.undefined");
84 if (!slot.isUndefined()) {
85 setErrorCode("reference.duplicate");
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
95 Revision.Format get = new Revision.Format(
96 getProjectSettings().getRevisionPattern());
97 Revision version = get.parse(filever);
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");
107 docname = tool.extractProperty("title"); // Property kept even if the file is not referenced
108 date = tool.extractProperty("date");
110 ResourceBundle locale = ResourceBundle.getBundle("som",
111 ApplicationSettings.getCurrentLocale());
112 SimpleDateFormat check = new SimpleDateFormat(
113 locale.getString("date.format"));
116 } catch (ParseException e) {
117 setErrorCode("format.date");
122 } else if (filext.equals("pdf"))
123 state = ProgressState.EXTERN; // TODO: Should external extensions be configurable ?
124 if (docname == null) {
126 for (int i = 1; i < table.length - 1; i++)
127 docname = docname + "." + table[i];
130 setupDefaultUses(deftype);
132 DocumentType[] types = doctypes.toArray(new DocumentType[doctypes
134 DocumentTypeComparator compare = new DocumentTypeComparator();
135 Arrays.sort(types, compare);
136 doctypes = Arrays.asList(types);
142 public String doImport() {
143 // -------------------------
144 if (action == ToDo.cancel)
147 setErrorCode("import.type");
150 Session connex = Database.getSession();
151 Transaction transax = connex.beginTransaction();
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");
162 // Creation of the document
163 Document.Properties dprop = new Document.Properties();
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])
171 updir = addoc.getSourceFile().asFile();
172 if (logger.isInfoEnabled())
173 logger.info("Moving \"" + upfile.getName() + "\" to \""
174 + updir.getPath() + "\".");
175 upfile.renameTo(updir);
177 getPublicationService().saveAs(addoc, state); // May throw FileNotFound if rename was not done
178 } catch (FileNotFoundException saverror) {
180 logger.info("Waiting for the file.");
181 upfile.renameTo(updir);
182 getPublicationService().saveAs(addoc, state); // Forget it if throw again FileNotFound
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));
192 addoc = getStepService().assignDocument(step, dprop.setReference(docref).setName(
194 updir = addoc.getSourceFile().asFile();
195 if (logger.isInfoEnabled())
196 logger.info("Moving \"" + upfile.getName() + "\" to \""
197 + updir.getPath() + "\".");
198 upfile.renameTo(updir);
200 if (docver.length() > 0)
201 getPublicationService().saveAs(addoc,
202 new Revision(docver));
204 getPublicationService().saveAs(addoc, state);
205 } catch (FileNotFoundException saverror) {
207 logger.info("Waiting for the file.");
208 upfile.renameTo(updir);
209 if (docver.length() > 0)
210 getPublicationService().saveAs(addoc,
211 new Revision(docver));
213 getPublicationService().saveAs(addoc, state);
215 mystudy.updateSimulationContexts(); // In case of simulation contexts extracted from the imported document
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);
226 // Creation of derived the document formats
227 // Document ndoc = addoc.value();
228 // Converter send = ApplicationSettings.getConverter(ndoc.getType(), ndoc.getFormat());
230 // if (send != null) send.converts(addoc); // Asynchronous process
233 mystudy.add(addoc); // Updates the presentation
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");
242 if (transax != null && transax.isActive()) { // Probably useless test
243 // Second try-catch as the rollback could fail as well
246 } catch (HibernateException backerror) {
247 logger.debug("Error rolling back transaction", backerror);
253 // ==============================================================================================================================
254 // Getters and setters
255 // ==============================================================================================================================
257 public String getDocumentDate() {
258 // --------------------------------
262 public List<DocumentType> getDocumentTypes() {
263 // ---------------------------------------------
267 public int getDocumentType() {
268 // -----------------------------
272 public String getReference() {
273 // -----------------------------
277 public String getVersion() {
278 // ---------------------------
282 public void setDocumentDate(String date) {
283 // -----------------------------------------
287 public void setDocumentName(String name) {
288 // -----------------------------------------
289 this.docname = name; // Name entered by the user if enabled
292 public void setDocumentTitle(String name) { // Called even if DocumentName is enabled
293 // -----------------------------------------
294 if (this.docname == null)
298 public void setDocumentType(String value) {
299 // ------------------------------------------
300 this.doctype = Integer.valueOf(value);
303 public void setDefaultDocumentState(String state) { // Called even if DocumentState is enabled
304 // --------------------------------------------------
305 if (this.state == null)
306 this.state = ProgressState.valueOf(state);
309 public void setDefaultDocumentType(String value) { // Called even if DocumentType is enabled
310 // --------------------------------------------------
311 if (this.doctype == 0)
312 this.doctype = Integer.valueOf(value);
315 public void setReference(String value) {
316 // ---------------------------------------
320 public void setVersion(String value) {
321 // -------------------------------------
326 * Get project settings.
328 * @return Project settings service
330 private ProjectSettingsService getProjectSettings() {
331 return _projectSettingsService;
335 * Set project settings service.
337 * @param projectSettingsService
338 * project settings service
340 public void setProjectSettings(ProjectSettingsService projectSettingsService) {
341 _projectSettingsService = projectSettingsService;
345 * Get the publicationService.
347 * @return the publicationService
349 public PublicationService getPublicationService() {
350 return _publicationService;
354 * Set the publicationService.
356 * @param publicationService
357 * the publicationService to set
359 public void setPublicationService(PublicationService publicationService) {
360 _publicationService = publicationService;
364 * Get the stepService.
365 * @return the stepService
367 public StepService getStepService() {
372 * Set the stepService.
373 * @param stepService the stepService to set
375 public void setStepService(StepService stepService) {
376 _stepService = stepService;