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.DocumentTypeService;
24 import org.splat.service.PublicationService;
25 import org.splat.service.StepService;
26 import org.splat.service.technical.ProjectSettingsService;
27 import org.splat.service.technical.RepositoryService;
28 import org.splat.dal.bo.som.Publication;
29 import org.splat.dal.bo.som.DocumentType;
30 import org.splat.som.Revision;
31 import org.splat.som.Step;
33 public class ImportDocumentAction extends UploadBaseNextAction {
38 private static final long serialVersionUID = 2587822564883588556L;
40 private List<DocumentType> doctypes = null;
41 private long doctype = 0;
42 private String docref = null; // Reference extracted from the imported file, if exist
43 private String docver = ""; // Version number extracted from the imported file, if exist
44 private String date = ""; // Date extracted from the imported file, if exist
46 * Injected project settings service.
48 private ProjectSettingsService _projectSettingsService;
50 * Injected publication service.
52 private PublicationService _publicationService;
54 * Injected step service.
56 private StepService _stepService;
58 * Injected document service.
60 private DocumentService _documentService;
62 * Injected document type service.
64 private DocumentTypeService _documentTypeService;
66 * Injected repository service.
68 private RepositoryService _repositoryService;
70 // ==============================================================================================================================
72 // ==============================================================================================================================
75 * Initialize the operation.
76 * @return SUCCESS in success, otherwise - ERROR
78 public String doInitialize() {
79 // -----------------------------
80 Session connex = Database.getSession();
81 Transaction transax = connex.beginTransaction();
82 User user = getConnectedUser();
83 File updir = getRepositoryService().getDownloadDirectory(user);
84 File upfile = new File(updir.getPath() + "/" + filename);
85 String[] table = filename.split("\\x2E");
86 String filext = table[table.length - 1].toLowerCase();
88 mystudy = getOpenStudy();
89 Step step = mystudy.getSelectedStep();
90 doctypes = getStepService().getValidDocumentTypes(step);
91 deftype = ApplicationSettings.getDefaultDocumentType(step, filext);
92 defuses = new Vector<Document>();
93 state = ProgressState.inWORK;
95 Reader tool = Toolbox.getReader(upfile);
97 String fileref = tool.extractProperty("reference");
98 String filever = tool.extractProperty("version"); // Property kept even if the file is not referenced
99 String filetype = tool.extractProperty("type"); // Property kept even if the file is not referenced
100 for (Iterator<DocumentType> i = doctypes.iterator(); i.hasNext();) {
101 DocumentType type = i.next();
102 if (!type.getName().equals(filetype))
105 doctype = type.getIndex(); // Disables the document type field
108 if (fileref != null) {
109 Document slot = getDocumentService().selectDocument(fileref,
110 new Revision().toString());
112 setErrorCode("reference.undefined");
115 if (!slot.isUndefined()) {
116 setErrorCode("reference.duplicate");
119 docref = fileref; // Disables document name and state fields
120 deftype = slot.getType(); // Just in case
121 doctype = deftype.getIndex(); // Disables the document type field
126 Revision.Format get = new Revision.Format(
127 getProjectSettings().getRevisionPattern());
128 Revision version = get.parse(filever);
129 if (version.isNull())
130 throw new ParseException(filever, filever.length() - 1);
131 if (!version.isMinor())
132 state = ProgressState.inCHECK;
133 docver = version.toString();
134 } catch (ParseException e) {
135 setErrorCode("format.version");
138 docname = tool.extractProperty("title"); // Property kept even if the file is not referenced
139 date = tool.extractProperty("date");
141 ResourceBundle locale = ResourceBundle.getBundle("som",
142 ApplicationSettings.getCurrentLocale());
143 SimpleDateFormat check = new SimpleDateFormat(
144 locale.getString("date.format"));
147 } catch (ParseException e) {
148 setErrorCode("format.date");
153 } else if (filext.equals("pdf"))
154 state = ProgressState.EXTERN; // TODO: Should external extensions be configurable ?
155 if (docname == null) {
157 for (int i = 1; i < table.length - 1; i++)
158 docname = docname + "." + table[i];
161 setupDefaultUses(deftype);
163 DocumentType[] types = doctypes.toArray(new DocumentType[doctypes
165 DocumentTypeComparator compare = new DocumentTypeComparator();
166 Arrays.sort(types, compare);
167 doctypes = Arrays.asList(types);
174 * Perform import of a document.
175 * @return SUCCESS if ok, "cancel" - if canceled, ERROR - if error
177 public String doImport() {
178 // -------------------------
179 if (action == ToDo.cancel)
182 setErrorCode("import.type");
185 Session connex = Database.getSession();
186 Transaction transax = connex.beginTransaction();
188 // Getting user inputs
189 mystudy = getOpenStudy();
190 User user = getConnectedUser();
191 Step step = mystudy.getSelectedStep();
192 DocumentType type = getDocumentTypeService().selectType((int)doctype);
193 File updir = getRepositoryService().getDownloadDirectory(user);
194 File upfile = new File(updir.getPath() + "/" + filename);
195 String[] table = filename.split("\\x2E");
197 // Creation of the document
198 Document.Properties dprop = new Document.Properties();
201 if (docref.length() == 0) { // Importation of a foreign document
202 // TODO: Extract property of supported documents (DOCX, ODT...)
203 addoc = getStepService().createDocument(step, dprop.setName(docname)
204 .setType(type).setFormat(table[table.length - 1])
206 updir = addoc.getSourceFile().asFile();
207 if (logger.isInfoEnabled())
208 logger.info("Moving \"" + upfile.getName() + "\" to \""
209 + updir.getPath() + "\".");
210 upfile.renameTo(updir);
212 getPublicationService().saveAs(addoc, state); // May throw FileNotFound if rename was not done
213 } catch (FileNotFoundException saverror) {
215 logger.info("Waiting for the file.");
216 upfile.renameTo(updir);
217 getPublicationService().saveAs(addoc, state); // Forget it if throw again FileNotFound
219 } else { // Importation of a previously created template-based document
220 if (date.length() > 0) {
221 ResourceBundle locale = ResourceBundle.getBundle("som",
222 ApplicationSettings.getCurrentLocale());
223 SimpleDateFormat get = new SimpleDateFormat(
224 locale.getString("date.format"));
225 dprop.setDate(get.parse(date));
227 addoc = getStepService().assignDocument(step, dprop.setReference(docref).setName(
229 updir = addoc.getSourceFile().asFile();
230 if (logger.isInfoEnabled())
231 logger.info("Moving \"" + upfile.getName() + "\" to \""
232 + updir.getPath() + "\".");
233 upfile.renameTo(updir);
235 if (docver.length() > 0)
236 getPublicationService().saveAs(addoc,
237 new Revision(docver));
239 getPublicationService().saveAs(addoc, state);
240 } catch (FileNotFoundException saverror) {
242 logger.info("Waiting for the file.");
243 upfile.renameTo(updir);
244 if (docver.length() > 0)
245 getPublicationService().saveAs(addoc,
246 new Revision(docver));
248 getPublicationService().saveAs(addoc, state);
250 mystudy.updateSimulationContexts(); // In case of simulation contexts extracted from the imported document
252 // Creation of uses relations
253 if (docuses != null) {
254 String[] list = docuses.split(",");
255 for (int i = 0; i < list.length; i++) {
256 Integer index = Integer.valueOf(list[i].trim());
257 Publication used = getPublication(index);
258 addoc.addDependency(used);
261 // Creation of derived the document formats
262 // Document ndoc = addoc.value();
263 // Converter send = ApplicationSettings.getConverter(ndoc.getType(), ndoc.getFormat());
265 // if (send != null) send.converts(addoc); // Asynchronous process
268 mystudy.add(addoc); // Updates the presentation
270 } catch (FileNotFoundException error) {
271 logger.error("Reason:", error);
272 setErrorCode("import.file");
273 } catch (Exception error) {
274 logger.error("Reason:", error);
275 setErrorCode("internal");
277 if (transax != null && transax.isActive()) { // Probably useless test
278 // Second try-catch as the rollback could fail as well
281 } catch (HibernateException backerror) {
282 logger.debug("Error rolling back transaction", backerror);
288 // ==============================================================================================================================
289 // Getters and setters
290 // ==============================================================================================================================
292 public String getDocumentDate() {
293 // --------------------------------
297 public List<DocumentType> getDocumentTypes() {
298 // ---------------------------------------------
302 public long getDocumentType() {
303 // -----------------------------
307 public String getReference() {
308 // -----------------------------
312 public String getVersion() {
313 // ---------------------------
317 public void setDocumentDate(String date) {
318 // -----------------------------------------
322 public void setDocumentName(String name) {
323 // -----------------------------------------
324 this.docname = name; // Name entered by the user if enabled
327 public void setDocumentTitle(String name) { // Called even if DocumentName is enabled
328 // -----------------------------------------
329 if (this.docname == null)
333 public void setDocumentType(String value) {
334 // ------------------------------------------
335 this.doctype = Integer.valueOf(value);
338 public void setDefaultDocumentState(String state) { // Called even if DocumentState is enabled
339 // --------------------------------------------------
340 if (this.state == null)
341 this.state = ProgressState.valueOf(state);
344 public void setDefaultDocumentType(String value) { // Called even if DocumentType is enabled
345 // --------------------------------------------------
346 if (this.doctype == 0)
347 this.doctype = Integer.valueOf(value);
350 public void setReference(String value) {
351 // ---------------------------------------
355 public void setVersion(String value) {
356 // -------------------------------------
361 * Get project settings.
363 * @return Project settings service
365 private ProjectSettingsService getProjectSettings() {
366 return _projectSettingsService;
370 * Set project settings service.
372 * @param projectSettingsService
373 * project settings service
375 public void setProjectSettings(ProjectSettingsService projectSettingsService) {
376 _projectSettingsService = projectSettingsService;
380 * Get the publicationService.
382 * @return the publicationService
384 public PublicationService getPublicationService() {
385 return _publicationService;
389 * Set the publicationService.
391 * @param publicationService
392 * the publicationService to set
394 public void setPublicationService(PublicationService publicationService) {
395 _publicationService = publicationService;
399 * Get the stepService.
400 * @return the stepService
402 public StepService getStepService() {
407 * Set the stepService.
408 * @param stepService the stepService to set
410 public void setStepService(StepService stepService) {
411 _stepService = stepService;
415 * Get the documentService.
416 * @return the documentService
418 public DocumentService getDocumentService() {
419 return _documentService;
423 * Set the documentService.
424 * @param documentService the documentService to set
426 public void setDocumentService(DocumentService documentService) {
427 _documentService = documentService;
431 * Get the repositoryService.
432 * @return the repositoryService
434 public RepositoryService getRepositoryService() {
435 return _repositoryService;
439 * Set the repositoryService.
440 * @param repositoryService the repositoryService to set
442 public void setRepositoryService(RepositoryService repositoryService) {
443 _repositoryService = repositoryService;
447 * Get the documentTypeService.
448 * @return the documentTypeService
450 public DocumentTypeService getDocumentTypeService() {
451 return _documentTypeService;
455 * Set the documentTypeService.
456 * @param documentTypeService the documentTypeService to set
458 public void setDocumentTypeService(DocumentTypeService documentTypeService) {
459 _documentTypeService = documentTypeService;