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.DocumentService;
23 import org.splat.service.PublicationService;
24 import org.splat.service.StepService;
25 import org.splat.service.technical.ProjectSettingsService;
26 import org.splat.service.technical.RepositoryService;
27 import org.splat.dal.bo.som.Publication;
28 import org.splat.dal.bo.som.DocumentType;
29 import org.splat.som.Revision;
30 import org.splat.som.Step;
32 public class ImportDocumentAction extends UploadBaseNextAction {
37 private static final long serialVersionUID = 2587822564883588556L;
39 private List<DocumentType> doctypes = null;
40 private long doctype = 0;
41 private String docref = null; // Reference extracted from the imported file, if exist
42 private String docver = ""; // Version number extracted from the imported file, if exist
43 private String date = ""; // Date extracted from the imported file, if exist
45 * Injected project settings service.
47 private ProjectSettingsService _projectSettingsService;
49 * Injected publication service.
51 private PublicationService _publicationService;
53 * Injected step service.
55 private StepService _stepService;
57 * Injected document service.
59 private DocumentService _documentService;
62 * Injected repository service.
64 private RepositoryService _repositoryService;
66 // ==============================================================================================================================
68 // ==============================================================================================================================
71 * Initialize the operation.
72 * @return SUCCESS in success, otherwise - ERROR
74 public String doInitialize() {
75 // -----------------------------
76 Session connex = Database.getSession();
77 Transaction transax = connex.beginTransaction();
78 User user = getConnectedUser();
79 File updir = getRepositoryService().getDownloadDirectory(user);
80 File upfile = new File(updir.getPath() + "/" + filename);
81 String[] table = filename.split("\\x2E");
82 String filext = table[table.length - 1].toLowerCase();
84 mystudy = getOpenStudy();
85 Step step = mystudy.getSelectedStep();
86 doctypes = step.getValidDocumentTypes();
87 deftype = ApplicationSettings.getDefaultDocumentType(step, filext);
88 defuses = new Vector<Document>();
89 state = ProgressState.inWORK;
91 Reader tool = Toolbox.getReader(upfile);
93 String fileref = tool.extractProperty("reference");
94 String filever = tool.extractProperty("version"); // Property kept even if the file is not referenced
95 String filetype = tool.extractProperty("type"); // Property kept even if the file is not referenced
96 for (Iterator<DocumentType> i = doctypes.iterator(); i.hasNext();) {
97 DocumentType type = i.next();
98 if (!type.getName().equals(filetype))
101 doctype = type.getIndex(); // Disables the document type field
104 if (fileref != null) {
105 Document slot = getDocumentService().selectDocument(fileref,
106 new Revision().toString());
108 setErrorCode("reference.undefined");
111 if (!slot.isUndefined()) {
112 setErrorCode("reference.duplicate");
115 docref = fileref; // Disables document name and state fields
116 deftype = slot.getType(); // Just in case
117 doctype = deftype.getIndex(); // Disables the document type field
122 Revision.Format get = new Revision.Format(
123 getProjectSettings().getRevisionPattern());
124 Revision version = get.parse(filever);
125 if (version.isNull())
126 throw new ParseException(filever, filever.length() - 1);
127 if (!version.isMinor())
128 state = ProgressState.inCHECK;
129 docver = version.toString();
130 } catch (ParseException e) {
131 setErrorCode("format.version");
134 docname = tool.extractProperty("title"); // Property kept even if the file is not referenced
135 date = tool.extractProperty("date");
137 ResourceBundle locale = ResourceBundle.getBundle("som",
138 ApplicationSettings.getCurrentLocale());
139 SimpleDateFormat check = new SimpleDateFormat(
140 locale.getString("date.format"));
143 } catch (ParseException e) {
144 setErrorCode("format.date");
149 } else if (filext.equals("pdf"))
150 state = ProgressState.EXTERN; // TODO: Should external extensions be configurable ?
151 if (docname == null) {
153 for (int i = 1; i < table.length - 1; i++)
154 docname = docname + "." + table[i];
157 setupDefaultUses(deftype);
159 DocumentType[] types = doctypes.toArray(new DocumentType[doctypes
161 DocumentTypeComparator compare = new DocumentTypeComparator();
162 Arrays.sort(types, compare);
163 doctypes = Arrays.asList(types);
170 * Perform import of a document.
171 * @return SUCCESS if ok, "cancel" - if canceled, ERROR - if error
173 public String doImport() {
174 // -------------------------
175 if (action == ToDo.cancel)
178 setErrorCode("import.type");
181 Session connex = Database.getSession();
182 Transaction transax = connex.beginTransaction();
184 // Getting user inputs
185 mystudy = getOpenStudy();
186 User user = getConnectedUser();
187 Step step = mystudy.getSelectedStep();
188 DocumentType type = Document.selectType((int)doctype);
189 File updir = getRepositoryService().getDownloadDirectory(user);
190 File upfile = new File(updir.getPath() + "/" + filename);
191 String[] table = filename.split("\\x2E");
193 // Creation of the document
194 Document.Properties dprop = new Document.Properties();
197 if (docref.length() == 0) { // Importation of a foreign document
198 // TODO: Extract property of supported documents (DOCX, ODT...)
199 addoc = getStepService().createDocument(step, dprop.setName(docname)
200 .setType(type).setFormat(table[table.length - 1])
202 updir = addoc.getSourceFile().asFile();
203 if (logger.isInfoEnabled())
204 logger.info("Moving \"" + upfile.getName() + "\" to \""
205 + updir.getPath() + "\".");
206 upfile.renameTo(updir);
208 getPublicationService().saveAs(addoc, state); // May throw FileNotFound if rename was not done
209 } catch (FileNotFoundException saverror) {
211 logger.info("Waiting for the file.");
212 upfile.renameTo(updir);
213 getPublicationService().saveAs(addoc, state); // Forget it if throw again FileNotFound
215 } else { // Importation of a previously created template-based document
216 if (date.length() > 0) {
217 ResourceBundle locale = ResourceBundle.getBundle("som",
218 ApplicationSettings.getCurrentLocale());
219 SimpleDateFormat get = new SimpleDateFormat(
220 locale.getString("date.format"));
221 dprop.setDate(get.parse(date));
223 addoc = getStepService().assignDocument(step, dprop.setReference(docref).setName(
225 updir = addoc.getSourceFile().asFile();
226 if (logger.isInfoEnabled())
227 logger.info("Moving \"" + upfile.getName() + "\" to \""
228 + updir.getPath() + "\".");
229 upfile.renameTo(updir);
231 if (docver.length() > 0)
232 getPublicationService().saveAs(addoc,
233 new Revision(docver));
235 getPublicationService().saveAs(addoc, state);
236 } catch (FileNotFoundException saverror) {
238 logger.info("Waiting for the file.");
239 upfile.renameTo(updir);
240 if (docver.length() > 0)
241 getPublicationService().saveAs(addoc,
242 new Revision(docver));
244 getPublicationService().saveAs(addoc, state);
246 mystudy.updateSimulationContexts(); // In case of simulation contexts extracted from the imported document
248 // Creation of uses relations
249 if (docuses != null) {
250 String[] list = docuses.split(",");
251 for (int i = 0; i < list.length; i++) {
252 Integer index = Integer.valueOf(list[i].trim());
253 Publication used = getPublication(index);
254 addoc.addDependency(used);
257 // Creation of derived the document formats
258 // Document ndoc = addoc.value();
259 // Converter send = ApplicationSettings.getConverter(ndoc.getType(), ndoc.getFormat());
261 // if (send != null) send.converts(addoc); // Asynchronous process
264 mystudy.add(addoc); // Updates the presentation
266 } catch (FileNotFoundException error) {
267 logger.error("Reason:", error);
268 setErrorCode("import.file");
269 } catch (Exception error) {
270 logger.error("Reason:", error);
271 setErrorCode("internal");
273 if (transax != null && transax.isActive()) { // Probably useless test
274 // Second try-catch as the rollback could fail as well
277 } catch (HibernateException backerror) {
278 logger.debug("Error rolling back transaction", backerror);
284 // ==============================================================================================================================
285 // Getters and setters
286 // ==============================================================================================================================
288 public String getDocumentDate() {
289 // --------------------------------
293 public List<DocumentType> getDocumentTypes() {
294 // ---------------------------------------------
298 public long getDocumentType() {
299 // -----------------------------
303 public String getReference() {
304 // -----------------------------
308 public String getVersion() {
309 // ---------------------------
313 public void setDocumentDate(String date) {
314 // -----------------------------------------
318 public void setDocumentName(String name) {
319 // -----------------------------------------
320 this.docname = name; // Name entered by the user if enabled
323 public void setDocumentTitle(String name) { // Called even if DocumentName is enabled
324 // -----------------------------------------
325 if (this.docname == null)
329 public void setDocumentType(String value) {
330 // ------------------------------------------
331 this.doctype = Integer.valueOf(value);
334 public void setDefaultDocumentState(String state) { // Called even if DocumentState is enabled
335 // --------------------------------------------------
336 if (this.state == null)
337 this.state = ProgressState.valueOf(state);
340 public void setDefaultDocumentType(String value) { // Called even if DocumentType is enabled
341 // --------------------------------------------------
342 if (this.doctype == 0)
343 this.doctype = Integer.valueOf(value);
346 public void setReference(String value) {
347 // ---------------------------------------
351 public void setVersion(String value) {
352 // -------------------------------------
357 * Get project settings.
359 * @return Project settings service
361 private ProjectSettingsService getProjectSettings() {
362 return _projectSettingsService;
366 * Set project settings service.
368 * @param projectSettingsService
369 * project settings service
371 public void setProjectSettings(ProjectSettingsService projectSettingsService) {
372 _projectSettingsService = projectSettingsService;
376 * Get the publicationService.
378 * @return the publicationService
380 public PublicationService getPublicationService() {
381 return _publicationService;
385 * Set the publicationService.
387 * @param publicationService
388 * the publicationService to set
390 public void setPublicationService(PublicationService publicationService) {
391 _publicationService = publicationService;
395 * Get the stepService.
396 * @return the stepService
398 public StepService getStepService() {
403 * Set the stepService.
404 * @param stepService the stepService to set
406 public void setStepService(StepService stepService) {
407 _stepService = stepService;
411 * Get the documentService.
412 * @return the documentService
414 public DocumentService getDocumentService() {
415 return _documentService;
419 * Set the documentService.
420 * @param documentService the documentService to set
422 public void setDocumentService(DocumentService documentService) {
423 _documentService = documentService;
427 * Get the repositoryService.
428 * @return the repositoryService
430 public RepositoryService getRepositoryService() {
431 return _repositoryService;
435 * Set the repositoryService.
436 * @param repositoryService the repositoryService to set
438 public void setRepositoryService(RepositoryService repositoryService) {
439 _repositoryService = repositoryService;