Salome HOME
Modifications done to respect PMD rules. Versioning a document is fixed. Validation...
[tools/siman.git] / Workspace / Siman / src / org / splat / simer / VersionDocumentAction.java
index 529d48aa84a351f007dd0819f2bff18ac769d3ff..5c0830bd8548c30e2b8e6377acff1ff1634ff0d6 100644 (file)
@@ -4,21 +4,17 @@ import java.io.File;
 import java.io.FileNotFoundException;
 import java.text.ParseException;
 import java.text.SimpleDateFormat;
-import java.util.HashSet;
+import java.util.Date;
 import java.util.Iterator;
 import java.util.List;
 import java.util.ResourceBundle;
 import java.util.Vector;
 
-import org.hibernate.HibernateException;
-import org.hibernate.Session;
-import org.hibernate.Transaction;
 import org.splat.kernel.InvalidPropertyException;
 import org.splat.dal.bo.kernel.Relation;
 import org.splat.dal.bo.kernel.User;
 import org.splat.manox.Reader;
 import org.splat.manox.Toolbox;
-import org.splat.dal.dao.som.Database;
 import org.splat.dal.bo.som.Document;
 import org.splat.dal.bo.som.ProgressState;
 import org.splat.service.PublicationService;
@@ -31,16 +27,51 @@ import org.splat.som.Step;
 import org.splat.dal.bo.som.UsedByRelation;
 import org.splat.dal.bo.som.UsesRelation;
 
+/**
+ * Action for creating a new version of a document.
+ */
 public class VersionDocumentAction extends UploadBaseNextAction {
 
-       private String index = null; // Versioned document index
+       /**
+        * Serial version ID.
+        */
+       private static final long serialVersionUID = -5702264003232132168L;
+
+       /**
+        * Versioned document index.
+        */
+       private String index = null;
+       /**
+        * List of publications which use the selected document.
+        */
        private List<Publication> usedby = null;
-       private String docusedby = null;
-       private String summary = null; // Summary of changes in the new version
-       private String docver = ""; // Version number extracted from the imported file, if exist
-       private String date = ""; // Date extracted from the imported file, if exist
+       /**
+        * List of selected impacted documents ids.
+        */
+       private long[] docusedby = null;
+       /**
+        * Summary of changes in the new version.
+        */
+       private String summary = null;
+       /**
+        * Version number extracted from the imported file, if exist.
+        */
+       private String docver = "";
+       /**
+        * Date extracted from the imported file, if exist.
+        */
+       private String date = "";
+       /**
+        * Injected project settings service.
+        */
        private ProjectSettingsService _projectSettingsService;
+       /**
+        * Injected publication service.
+        */
        private PublicationService _publicationService;
+       /**
+        * Injected step service.
+        */
        private StepService _stepService;
        /**
         * Injected repository service.
@@ -51,13 +82,25 @@ public class VersionDocumentAction extends UploadBaseNextAction {
         * It can be: none, create, open, study, knowledge, sysadmin, help.
         */
        private String _menuProperty;
-       
+
        /**
         * Value of the title bar property. 
         * It can be: study, knowledge.
         */
        private String _titleProperty;
+
+       /**
+        * Value of the tool bar property. 
+        * It can be: none, standard, study, back.
+        */
+       private String _toolProperty;
        
+       /**
+        * Value of the left menu property. 
+        * It can be: open, study, knowledge, scenario.
+        */
+       private String _leftMenuProperty;
+
        /**
         * Property that indicates whether the current open study is editable or not.
         * On the screen it looks like pen on the status icon, pop-up menu also can be called.
@@ -65,25 +108,28 @@ public class VersionDocumentAction extends UploadBaseNextAction {
         */
        private String _editDisabledProperty = "false";
 
-       /**
-        * Serial version ID.
-        */
-       private static final long serialVersionUID = -5702264003232132168L;
-
        // ==============================================================================================================================
        // Action methods
        // ==============================================================================================================================
 
+       /**
+        * Initialize the action form.
+        * 
+        * @return SUCCESS if succeeded, ERROR if uploaded file is XML and we can't extract properties from it
+        */
        public String doInitialize() {
-               // -----------------------------
-               
+
                setMenuProperty("study");
                setTitleProperty("study");
                setEditDisabledProperty("true");
-        initializationScreenContext(_menuProperty, _titleProperty, _editDisabledProperty);
+               if ("true".equals(getWriteAccess())) {
+                       setToolProperty("study");
+               } else {
+                       setToolProperty("none");
+               }
+               setLeftMenuProperty("study");
+        initializationFullScreenContext(_menuProperty, _titleProperty, _editDisabledProperty, _toolProperty, _leftMenuProperty);
            
-               Session connex = Database.getCurSession();
-               Transaction transax = connex.beginTransaction();
                User user = getConnectedUser();
                File updir = getRepositoryService().getDownloadDirectory(user);
                File upfile = new File(updir.getPath() + "/" + filename);
@@ -98,46 +144,13 @@ public class VersionDocumentAction extends UploadBaseNextAction {
                defuses = new Vector<Document>();
                usedby = new Vector<Publication>();
 
-               Reader tool = Toolbox.getReader(upfile);
-               if (tool != null) {
-                       String fileref = tool.extractProperty("reference");
-                       String filever = tool.extractProperty("version");
-                       if (fileref != null && !doc.getReference().equals(fileref)) {
-                               setErrorCode("reference.mismatch");
-                               return ERROR;
+               if (!extractProperties(upfile, doc)) {
+                       if (!("none".equals(_toolProperty))) {
+                               setToolProperty("none");
+                               setLeftMenuProperty("study");
+                               initializationFullScreenContext(_menuProperty, _titleProperty, _editDisabledProperty, _toolProperty, _leftMenuProperty);
                        }
-                       if (filever != null)
-                               try {
-                                       Revision.Format get = new Revision.Format(
-                                                       getProjectSettings().getRevisionPattern());
-                                       Revision newver = get.parse(filever);
-                                       Revision oldver = new Revision(doc.getVersion());
-                                       if (!newver.isGraterThan(oldver))
-                                               throw new InvalidPropertyException("version");
-                                       if (newver.isMinor())
-                                               state = ProgressState.inWORK;
-                                       else
-                                               state = ProgressState.inDRAFT;
-                                       docver = newver.toString();
-                               } catch (Exception e) {
-                                       setErrorCode("version.mismatch");
-                                       return ERROR;
-                               }
-                       summary = tool.extractProperty("history");
-                       date = tool.extractProperty("date");
-                       if (date != null) {
-                               ResourceBundle locale = ResourceBundle.getBundle("som",
-                                               ApplicationSettings.getCurrentLocale());
-                               SimpleDateFormat check = new SimpleDateFormat(
-                                               locale.getString("date.format"));
-                               try {
-                                       check.parse(date);
-                               } catch (ParseException e) {
-                                       setErrorCode("format.date");
-                                       return ERROR;
-                               }
-                       } else
-                               date = "";
+                       return ERROR;
                }
                setupDefaultUses(deftype);
                // Add additional documents used by the current version
@@ -152,12 +165,77 @@ public class VersionDocumentAction extends UploadBaseNextAction {
                for (Iterator<Publication> i = relist.iterator(); i.hasNext();) {
                        usedby.add(i.next());
                }
-               transax.commit();
                return SUCCESS;
        }
 
+       /**
+        * Try to extract properties from the uploaded file if it is XML.
+        * 
+        * @param upfile
+        *            the file to parse
+        * @param doc
+        *            the document to version
+        * @return true if succeeded or if the file is not XML, otherwise return false
+        */
+       private boolean extractProperties(File upfile, Document doc) {
+               boolean res = true;
+               Reader tool = Toolbox.getReader(upfile);
+               if (tool != null) {
+                       String fileref = tool.extractProperty("reference");
+                       String filever = tool.extractProperty("version");
+                       if (fileref != null && !doc.getReference().equals(fileref)) {
+                               setErrorCode("reference.mismatch");
+                               res = false;
+                       } else {
+                               if (filever != null) {
+                                       try {
+                                               Revision.Format get = new Revision.Format(
+                                                               getProjectSettings().getRevisionPattern());
+                                               Revision newver = get.parse(filever);
+                                               Revision oldver = new Revision(doc.getVersion());
+                                               if (!newver.isGraterThan(oldver)) {
+                                                       throw new InvalidPropertyException("version");
+                                               }
+                                               if (newver.isMinor()) {
+                                                       state = ProgressState.inWORK;
+                                               } else {
+                                                       state = ProgressState.inDRAFT;
+                                               }
+                                               docver = newver.toString();
+                                       } catch (Exception e) {
+                                               setErrorCode("version.mismatch");
+                                               res = false;
+                                       }
+                               }
+                               if (res) {
+                                       summary = tool.extractProperty("history");
+                                       date = tool.extractProperty("date");
+                                       if (date != null) {
+                                               ResourceBundle locale = ResourceBundle.getBundle("som",
+                                                               getApplicationSettings().getCurrentLocale());
+                                               SimpleDateFormat check = new SimpleDateFormat(locale
+                                                               .getString("date.format"));
+                                               try {
+                                                       check.parse(date);
+                                               } catch (ParseException e) {
+                                                       setErrorCode("format.date");
+                                                       res = false;
+                                               }
+                                       } else {
+                                               date = "";
+                                       }
+                               }
+                       }
+               }
+               return res;
+       }
+
+       /**
+        * Create a new version of the selected document.
+        * 
+        * @return SUCCESS - if succeeded, "cancel" - if canceled, ERROR - if failed
+        */
        public String doVersion() {
-               // -------------------------
                setMenuProperty("study");
                setTitleProperty("study");
                setEditDisabledProperty("true");
@@ -166,91 +244,32 @@ public class VersionDocumentAction extends UploadBaseNextAction {
                if (action == ToDo.cancel)
                        return "cancel";
 
-               Session connex = Database.getCurSession();
-               Transaction transax = connex.beginTransaction();
                try {
                        // Getting user inputs
                        mystudy = getOpenStudy();
                        User user = getConnectedUser();
                        Step step = mystudy.getSelectedStep();
-                       File updir = getRepositoryService().getDownloadDirectory(user);
-                       File upfile = new File(updir.getPath() + "/" + filename);
-
-                       // Versioning of the document
-                       Document.Properties dprop = new Document.Properties();
-                       Publication current = step.getDocument(Integer.valueOf(index));
-                       Publication next;
-
-                       if (docver.length() == 0) { // Importation of a foreign document
-                               next = getStepService().versionDocument(step, current, dprop.setAuthor(user)
-                                               .setDescription(summary));
-                               updir = next.getSourceFile().asFile();
-                               if (logger.isInfoEnabled())
-                                       logger.info("Moving \"" + upfile.getName() + "\" to \""
-                                                       + updir.getPath() + "\".");
-                               upfile.renameTo(updir);
-                               try {
-                                       getPublicationService().saveAs(next, state); // May throw FileNotFound if rename was not done
-                               } catch (FileNotFoundException saverror) {
-                                       Thread.sleep(1000);
-                                       logger.info("Waiting for the file.");
-                                       upfile.renameTo(updir);
-                                       getPublicationService().saveAs(next, state); // Forget it if throw again FileNotFound
-                               }
-                       } else {
-                               if (date.length() > 0) {
-                                       ResourceBundle locale = ResourceBundle.getBundle("som",
-                                                       ApplicationSettings.getCurrentLocale());
-                                       SimpleDateFormat get = new SimpleDateFormat(
-                                                       locale.getString("date.format"));
-                                       dprop.setDate(get.parse(date));
-                               }
-                               next = getStepService().versionDocument(step, current, dprop.setAuthor(user)
-                                               .setDescription(summary));
-                               updir = next.getSourceFile().asFile();
-                               if (logger.isInfoEnabled())
-                                       logger.info("Moving \"" + upfile.getName() + "\" to \""
-                                                       + updir.getPath() + "\".");
-                               upfile.renameTo(updir);
-                               try {
-                                       getPublicationService().saveAs(next, new Revision(docver));
-                               } catch (FileNotFoundException saverror) {
-                                       Thread.sleep(1000);
-                                       logger.info("Waiting for the file.");
-                                       upfile.renameTo(updir);
-                                       getPublicationService().saveAs(next, state);
-                               }
+                       Date aDate = null;
+                       if (date.length() > 0) {
+                               ResourceBundle locale = ResourceBundle.getBundle("som",
+                                               getApplicationSettings().getCurrentLocale());
+                               SimpleDateFormat get = new SimpleDateFormat(locale
+                                               .getString("date.format"));
+                               aDate = get.parse(date);
                        }
-                       // TODO: Remove current document details from the contents of open study
 
-                       // Creation of uses relations
+                       String[] listDocuses = null;
                        if (docuses != null) {
-                               String[] list = docuses.split(",");
-                               for (int i = 0; i < list.length; i++) {
-                                       Integer index = Integer.valueOf(list[i].trim());
-                                       Publication used = getPublication(index);
-                                       next.addDependency(used);
-                               }
-                       }
-                       // Outdating impacted document
-                       HashSet<Integer> compatible = new HashSet<Integer>();
-                       if (docusedby != null) {
-                               String[] list = docusedby.split(",");
-                               for (int i = 0; i < list.length; i++)
-                                       compatible.add(Integer.valueOf(list[i].trim()));
-                       }
-                       List<Publication> relist = current
-                                       .getRelations(UsedByRelation.class);
-                       for (Iterator<Publication> i = relist.iterator(); i.hasNext();) {
-                               Publication using = i.next();
-                               if (!compatible.contains(using.getIndex()))
-                                       getPublicationService().outdate(using);
+                               listDocuses = docuses.split(",");
                        }
+                       getPublicationService().versionDocument(step, user, filename,
+                                       Integer.valueOf(index), docver, summary, state, aDate,
+                                       listDocuses, docusedby);
+
                        // Update of the open study
                        mystudy.setSelection(mystudy.getSelection()); // Rebuilds the presentation
                        // TODO: Look is an optimization is possible (for example by updating the presentation of versioned document)
 
-                       transax.commit();
                        return SUCCESS;
                } catch (FileNotFoundException error) {
                        logger.error("Reason:", error);
@@ -259,14 +278,12 @@ public class VersionDocumentAction extends UploadBaseNextAction {
                        logger.error("Reason:", error);
                        setErrorCode("internal");
                }
-               if (transax != null && transax.isActive()) {
-                       // Second try-catch as the rollback could fail as well
-                       try {
-                               transax.rollback();
-                       } catch (HibernateException backerror) {
-                               logger.debug("Error rolling back transaction", backerror);
-                       }
-               }
+               
+               setToolProperty("none");
+               
+               setLeftMenuProperty("study");
+               initializationFullScreenContext(_menuProperty, _titleProperty, _editDisabledProperty, _toolProperty, _leftMenuProperty);
+               
                return ERROR;
        }
 
@@ -275,58 +292,47 @@ public class VersionDocumentAction extends UploadBaseNextAction {
        // ==============================================================================================================================
 
        public String getDate() {
-               // ------------------------
                return date;
        }
 
        public List<Publication> getDependencies() {
-               // -------------------------------------------
                return usedby;
        }
 
        public String getDescription() {
-               // -------------------------------
                return summary;
        }
 
        public String getIndex() {
-               // -------------------------
                return index;
        }
 
        public String getVersion() {
-               // ---------------------------
                return docver;
        }
 
        public void setDate(String date) {
-               // ---------------------------------
                this.date = date;
        }
 
        public void setDefaultDescription(String summary) {
-               // --------------------------------------------------
                if (this.summary == null)
                        this.summary = summary;
        }
 
        public void setDescription(String summary) {
-               // -------------------------------------------
                this.summary = summary;
        }
 
        public void setIndex(String index) {
-               // -----------------------------------
                this.index = index;
        }
 
-       public void setUsedBy(String list) {
-               // -----------------------------------
+       public void setUsedBy(long[] list) {
                this.docusedby = list;
        }
 
        public void setVersion(String value) {
-               // -------------------------------------
                this.docver = value;
        }
 
@@ -370,6 +376,7 @@ public class VersionDocumentAction extends UploadBaseNextAction {
 
        /**
         * Get the stepService.
+        * 
         * @return the stepService
         */
        public StepService getStepService() {
@@ -378,7 +385,9 @@ public class VersionDocumentAction extends UploadBaseNextAction {
 
        /**
         * Set the stepService.
-        * @param stepService the stepService to set
+        * 
+        * @param stepService
+        *            the stepService to set
         */
        public void setStepService(StepService stepService) {
                _stepService = stepService;
@@ -386,6 +395,7 @@ public class VersionDocumentAction extends UploadBaseNextAction {
 
        /**
         * Get the repositoryService.
+        * 
         * @return the repositoryService
         */
        public RepositoryService getRepositoryService() {
@@ -394,14 +404,17 @@ public class VersionDocumentAction extends UploadBaseNextAction {
 
        /**
         * Set the repositoryService.
-        * @param repositoryService the repositoryService to set
+        * 
+        * @param repositoryService
+        *            the repositoryService to set
         */
        public void setRepositoryService(RepositoryService repositoryService) {
                _repositoryService = repositoryService;
        }
-       
+
        /**
         * Get the menuProperty.
+        * 
         * @return the menuProperty
         */
        public String getMenuProperty() {
@@ -410,14 +423,17 @@ public class VersionDocumentAction extends UploadBaseNextAction {
 
        /**
         * Set the menuProperty.
-        * @param menuProperty the menuProperty to set
+        * 
+        * @param menuProperty
+        *            the menuProperty to set
         */
        public void setMenuProperty(String menuProperty) {
                this._menuProperty = menuProperty;
        }
-       
+
        /**
         * Get the _titleProperty.
+        * 
         * @return the _titleProperty
         */
        public String getTitleProperty() {
@@ -426,7 +442,9 @@ public class VersionDocumentAction extends UploadBaseNextAction {
 
        /**
         * Set the _titleProperty.
-        * @param _titleProperty the titleProperty to set
+        * 
+        * @param titleProperty
+        *            the titleProperty to set
         */
        public void setTitleProperty(String titleProperty) {
                _titleProperty = titleProperty;
@@ -434,6 +452,7 @@ public class VersionDocumentAction extends UploadBaseNextAction {
 
        /**
         * Get the _editDisabledProperty.
+        * 
         * @return the _editDisabledProperty
         */
        public String getEditDisabledProperty() {
@@ -442,9 +461,43 @@ public class VersionDocumentAction extends UploadBaseNextAction {
 
        /**
         * Set the _editDisabledProperty.
-        * @param _editDisabledProperty the _editDisabledProperty to set
+        * 
+        * @param _editDisabledProperty
+        *            the _editDisabledProperty to set
         */
        public void setEditDisabledProperty(String _editDisabledProperty) {
                this._editDisabledProperty = _editDisabledProperty;
        }
+       
+       /**
+        * Get the toolProperty.
+        * @return the toolProperty
+        */
+       public String getToolProperty() {
+               return _toolProperty;
+       }
+
+       /**
+        * Set the toolProperty.
+        * @param toolProperty the toolProperty to set
+        */
+       public void setToolProperty(final String toolProperty) {
+               _toolProperty = toolProperty;
+       }
+       
+       /**
+        * Get the leftMenuProperty.
+        * @return the leftMenuProperty
+        */
+       public String getLeftMenuProperty() {
+               return _leftMenuProperty;
+       }
+
+       /**
+        * Set the leftMenuProperty.
+        * @param leftMenuProperty the leftMenuProperty to set
+        */
+       public void setLeftMenuProperty(final String leftMenuProperty) {
+               _leftMenuProperty = leftMenuProperty;
+       }
 }
\ No newline at end of file