]> SALOME platform Git repositories - tools/siman.git/commitdiff
Salome HOME
Default document types mappings are moved from application settings (my.xml) to proje...
authorrkv <rkv@opencascade.com>
Wed, 21 Nov 2012 13:30:32 +0000 (13:30 +0000)
committerrkv <rkv@opencascade.com>
Wed, 21 Nov 2012 13:30:32 +0000 (13:30 +0000)
28 files changed:
Workspace/Siman-Common/src/conf/log-messages.properties
Workspace/Siman-Common/src/org/splat/common/properties/MessageKeyEnum.java
Workspace/Siman-Common/src/org/splat/dal/bo/som/ProgressState.java
Workspace/Siman-Common/src/org/splat/dal/bo/som/Study.java
Workspace/Siman-Common/src/org/splat/kernel/InvalidPropertyException.java
Workspace/Siman-Common/src/org/splat/service/DocumentServiceImpl.java
Workspace/Siman-Common/src/org/splat/service/PublicationService.java
Workspace/Siman-Common/src/org/splat/service/ScenarioService.java
Workspace/Siman-Common/src/org/splat/service/ScenarioServiceImpl.java
Workspace/Siman-Common/src/org/splat/service/StepServiceImpl.java
Workspace/Siman-Common/src/org/splat/service/dto/DocumentDTO.java
Workspace/Siman-Common/src/org/splat/service/dto/FileDTO.java
Workspace/Siman-Common/src/org/splat/service/dto/StepDTO.java
Workspace/Siman-Common/src/org/splat/service/technical/ProjectSettingsService.java
Workspace/Siman-Common/src/org/splat/service/technical/ProjectSettingsServiceImpl.java
Workspace/Siman-Common/src/spring/businessServiceContext.xml
Workspace/Siman-Common/src/test/siman.properties
Workspace/Siman-Common/src/test/som.xml
Workspace/Siman-Common/src/test/splat/service/TestProjectSettingsService.java
Workspace/Siman-Common/src/test/splat/service/TestScenarioService.java
Workspace/Siman/WebContent/conf/my.xml
Workspace/Siman/WebContent/conf/som.xml
Workspace/Siman/src/org/splat/simer/ApplicationSettings.java
Workspace/Siman/src/org/splat/simer/ImportDocumentAction.java
Workspace/Siman/src/org/splat/simer/UploadAction.java
Workspace/Siman/src/org/splat/simer/UploadBaseNextAction.java
Workspace/Siman/src/org/splat/simer/VersionDocumentAction.java
Workspace/Siman/src/org/splat/wapp/Constants.java

index 708f15d0d378bed3c627115b43ff27cb1a979da4..05739d5ea46d5d9174cecd49d44adb5459c9edce 100644 (file)
@@ -3,4 +3,6 @@ LCK-000001=Lock reference already exists for user {2}.
 LCK-000002=Lock reference does not exists.
 LCK-000003=Lock reference protected and can be only deleted or updated by user {2}.
 LCK-000004=Lock reference is timeout and could have been modified by user {2}.
-STD-000001="Unable to re-index the study #{1}, reason: {2}"
\ No newline at end of file
+STD-000001=Unable to re-index the study #{1}, reason: {2}
+SCN-000001=Scenario doesn't contain the step number #{1}
+SCN-000002=Scenario doesn't contain the document #{1}
\ No newline at end of file
index b7c29211133d4beeb625f21a88f7776cf27877c6..12409ae54a90efa19f584383bd9062b6347c318e 100644 (file)
@@ -32,7 +32,19 @@ public enum MessageKeyEnum {
        /**
         * Lock reference is timeout and could have been modified by user {2}.
         */
-       LCK_000004("LCK-000004");
+       LCK_000004("LCK-000004"),
+       /**
+        * Unable to re-index the study #{1}, reason: {2}.
+        */
+       STD_000001("STD-000001"),
+       /**
+        * Scenario doesn't contain the step number #{1}.
+        */
+       SCN_000001("SCN-000001"),
+       /**
+        * Scenario doesn't contain the document #{1}.
+        */
+       SCN_000002("SCN-000002");
        
        /**
        * Value.
index 78f131177547cfa2eb0faa66bd5cc61811f93409..9a80331b241744de196cdfe7a01bf0f43415ec75 100644 (file)
@@ -1,7 +1,9 @@
 package org.splat.dal.bo.som;
+
 /**
+ * Study, scenario or document progress state enumeration.
  * 
- * @author    Daniel Brunier-Coulin
+ * @author Daniel Brunier-Coulin
  * @copyright OPEN CASCADE 2012
  */
 
@@ -9,17 +11,29 @@ public enum ProgressState {
        /**
         * Represents inWORK, inDRAFT and inCHECK states for search purpose.
         */
-    inPROGRESS,
-    inWORK, 
-    inDRAFT, 
-    inCHECK, 
-    APPROVED,
-    /**
-     * Document-specific state representing documents produced outside studies.
-     */
-    EXTERN,
-    /**
-     * Study-specific state qualifying typical reference studies.
-     */
-    TEMPLATE;
+       inPROGRESS,
+       /**
+        * The first possible state in a validation cycle.
+        */
+       inWORK,
+       /**
+        * The state after promoting from inWORK state.
+        */
+       inDRAFT,
+       /**
+        * The state after validating from inDRAFT or inWORK state.
+        */
+       inCHECK,
+       /**
+        * The state after approving from inCHECK state.
+        */
+       APPROVED,
+       /**
+        * Document-specific state representing documents produced outside studies.
+        */
+       EXTERN,
+       /**
+        * Study-specific state qualifying typical reference studies.
+        */
+       TEMPLATE;
 }
\ No newline at end of file
index 3af40f510235100300fb0e56211c0485208d0826..bcb760c5c7ea9ebdc8ff79909d8c33d04e244a99 100644 (file)
@@ -10,17 +10,17 @@ import java.util.Calendar;
 import java.util.Date;
 import java.util.HashMap;
 import java.util.HashSet;
-import java.util.List;
 import java.util.LinkedList;
+import java.util.List;
 import java.util.Map;
 import java.util.Set;
 import java.util.Vector;
 
 import org.splat.dal.bo.kernel.Persistent;
 import org.splat.dal.bo.kernel.User;
-import org.splat.kernel.MultiplyDefinedException;
 import org.splat.kernel.InvalidPropertyException;
 import org.splat.kernel.MissedPropertyException;
+import org.splat.kernel.MultiplyDefinedException;
 import org.splat.som.Revision;
 
 /**
@@ -50,9 +50,9 @@ public class Study extends ProjectElement {
         */
        private Visibility visibility;
        /**
-        * Persistent list of study scenarii.
+        * Persistent list of study scenarios.
         */
-       private List<Scenario> scenarii = new LinkedList<Scenario>();
+       private final List<Scenario> scenarii = new LinkedList<Scenario>();
        private String version;
        /**
         * Persistent history property. It is a number of studies versioning this one, if any.
@@ -63,15 +63,15 @@ public class Study extends ProjectElement {
        /**
         * Transient list of contributors.
         */
-       private transient List<User> contributor = new Vector<User>(); // Shortcut to contributors
+       private transient final List<User> contributor = new Vector<User>();
        /**
         * Transient map of document types to validation cycles.
         */
-       private transient Map<String, ValidationCycle> validactor = new HashMap<String, ValidationCycle>(); // Shortcut to validation cycles
+       private transient final Map<String, ValidationCycle> validactor = new HashMap<String, ValidationCycle>(); 
        /**
         * Transient set of all actors of the study, i.d. contributors and validation cycles participants.
         */
-       private transient Set<User> actor = new HashSet<User>(); // Summary of above actors
+       private transient final Set<User> actor = new HashSet<User>();
 
        // ==============================================================================================================================
        // Construction
@@ -81,7 +81,6 @@ public class Study extends ProjectElement {
         * Fields initialization class.
         */
        public static class Properties extends Persistent.Properties {
-               // ------------------------------------------------------------
                private String sid = null; // Search criterion only
                private String title = null;
                private String summary = null;
@@ -94,6 +93,7 @@ public class Study extends ProjectElement {
 
                // - Public services
 
+               @Override
                public void clear() {
                        super.clear();
                        sid = null;
@@ -158,58 +158,62 @@ public class Study extends ProjectElement {
                // - Property setters
 
                // For building a search query
-               public Properties setActor(User actor) {
+               public Properties setActor(final User actor) {
                        this.actor = actor;
                        return this;
                }
 
-               public Properties setDate(Date date) {
+               public Properties setDate(final Date date) {
                        this.date = date;
                        return this;
                }
 
-               public Properties setDescription(String summary) {
-                       if (summary.length() > 0)
+               public Properties setDescription(final String summary) {
+                       if (summary.length() > 0) {
                                this.summary = summary;
+                       }
                        return this;
                }
 
-               public Properties setManager(User user) {
+               public Properties setManager(final User user) {
                        this.manager = user;
                        return this;
                }
 
                // For building a search query
-               public Properties setReference(String sid)
+               public Properties setReference(final String sid)
                                throws InvalidPropertyException {
-                       if (sid.length() == 0)
+                       if (sid.length() == 0) {
                                throw new InvalidPropertyException("reference");
+                       }
                        this.sid = sid;
                        return this;
                }
 
                // For building a search query
-               public Properties setSimulationContexts(List<SimulationContext> context) {
+               public Properties setSimulationContexts(
+                               final List<SimulationContext> context) {
                        this.context = context;
                        return this;
                }
 
                // For building a search query
-               public Properties setState(ProgressState state) {
+               public Properties setState(final ProgressState state) {
                        this.state = state;
                        return this;
                }
 
-               public Properties setTitle(String title)
+               public Properties setTitle(final String title)
                                throws InvalidPropertyException {
-                       if (title.length() == 0)
+                       if (title.length() == 0) {
                                throw new InvalidPropertyException("title");
+                       }
                        this.title = title;
                        return this;
                }
 
                // For building a search query
-               public Properties setVisibility(Visibility area) {
+               public Properties setVisibility(final Visibility area) {
                        this.visibility = area;
                        return this;
                }
@@ -218,31 +222,46 @@ public class Study extends ProjectElement {
 
                public void checkValidity() throws MissedPropertyException,
                                InvalidPropertyException, MultiplyDefinedException {
-                       if (title == null)
+                       if (title == null) {
                                throw new MissedPropertyException("title");
-                       if (manager == null)
+                       }
+                       if (manager == null) {
                                throw new MissedPropertyException("manager");
+                       }
                }
        }
 
-       // Database fetch constructor
+       /**
+        * Database fetch constructor.
+        */
        protected Study() {
+               super();
                contributor.clear();
                validactor.clear();
                actor.clear();
        }
 
-       // Internal constructor
-       public Study(Properties sprop) throws MissedPropertyException,
+       /**
+        * Constructor from properties.
+        * 
+        * @param sprop
+        *            study properties
+        * @throws MissedPropertyException
+        *             if some mandatory property is missed
+        * @throws InvalidPropertyException
+        *             if some property has invalid value
+        * @throws MultiplyDefinedException
+        *             if some property is defined several times
+        */
+       public Study(final Properties sprop) throws MissedPropertyException,
                        InvalidPropertyException, MultiplyDefinedException {
-               // ----------------------------------
                super(sprop); // Throws one of the above exception if not valid
                sid = sprop.sid; // Reset after save
                title = sprop.title; // Inherited attribute
                manager = sprop.manager;
                docount = 0;
                history = 0;
-//RKV          scenarii = new LinkedList<Scenario>();
+               // RKV scenarii = new LinkedList<Scenario>();
                visibility = Visibility.PRIVATE;
                state = ProgressState.inWORK;
 
@@ -254,8 +273,9 @@ public class Study extends ProjectElement {
                lasdate = credate; // Inherited attribute
                version = new Revision().incrementAs(state).toString();
 
-               if (sprop.summary != null)
+               if (sprop.summary != null) {
                        this.setAttribute(new DescriptionAttribute(this, sprop.summary));
+               }
 
                contributor.clear();
                validactor.clear();
@@ -275,27 +295,33 @@ public class Study extends ProjectElement {
                return sid;
        }
 
-       public void setReference(String aReference) {
+       public void setReference(final String aReference) {
                sid = aReference;
        }
 
+       /**
+        * Get persistent list of study scenarios as an array.
+        * 
+        * @return array of scenarios
+        */
        public Scenario[] getScenarii() {
-               // --------------------------------
                return scenarii.toArray(new Scenario[scenarii.size()]);
        }
 
+       /**
+        * Get persistent list of study scenarios.
+        * 
+        * @return the list of scenarios
+        */
        public List<Scenario> getScenariiList() {
-               // --------------------------------
                return scenarii;
        }
 
        public String getVersion() {
-               // ---------------------------
                return version;
        }
 
        public Visibility getVisibility() {
-               // ----------------------------------
                return visibility;
        }
 
@@ -307,32 +333,38 @@ public class Study extends ProjectElement {
         * @see #moveToReference()
         */
        public boolean isPublic() {
-               // --------------------------
                return (visibility != Visibility.PRIVATE);
        }
 
        public boolean isVersioned() {
-               // -----------------------------
                return (history > 0);
        }
 
-       public boolean shares(Document doc) {
-               // ------------------------------------
+       /**
+        * Check if the document is shared by scenarios of the study.
+        * 
+        * @param doc
+        *            the document to check
+        * @return true if the document is published in more then one scenario of the study
+        */
+       public boolean shares(final Document doc) {
                Scenario[] scene = this.getScenarii(); // If shared from within the study, the document is shared by the scenarios
                int counter = 0;
+               boolean res = false;
 
                for (int i = 0; i < scene.length; i++) {
-                       if (!scene[i].publishes(doc))
-                               continue;
-                       if (counter == 1)
-                               return true;
-                       counter += 1;
+                       if (scene[i].publishes(doc)) {
+                               if (counter == 1) {
+                                       res = true;
+                                       break;
+                               }
+                               counter += 1;
+                       }
                }
-               return false;
+               return res;
        }
 
        public int getLastLocalIndex() {
-               // ----------------------------------
                return docount;
        }
 
@@ -340,7 +372,7 @@ public class Study extends ProjectElement {
         * @param aVisibility
         *            a study visibility to set
         */
-       public void setVisibility(Visibility aVisibility) {
+       public void setVisibility(final Visibility aVisibility) {
                visibility = aVisibility;
        }
 
@@ -348,14 +380,14 @@ public class Study extends ProjectElement {
         * @param aState
         *            a study progress state to set
         */
-       public void setProgressState(ProgressState aState) {
+       public void setProgressState(final ProgressState aState) {
                state = aState;
        }
 
        /**
         * @param aVersion
         */
-       public void setVersion(String aVersion) {
+       public void setVersion(final String aVersion) {
                version = aVersion;
        }
 
@@ -365,7 +397,7 @@ public class Study extends ProjectElement {
         * @param anIndex
         *            a number of study documents
         */
-       public void setLastLocalIndex(int anIndex) {
+       public void setLastLocalIndex(final int anIndex) {
                docount = anIndex;
        }
 
index 660940e9fe7c725bc100e3e05143fb5a32438cd5..68b60be4f07925269c099cc14316181d7a774194 100644 (file)
@@ -4,7 +4,8 @@ import org.splat.exception.BusinessException;
 
 /**
  * Exception thrown when the property is invalid.
- * @author    Daniel Brunier-Coulin
+ * 
+ * @author Daniel Brunier-Coulin
  * @copyright OPEN CASCADE 2012
  */
 
@@ -16,10 +17,41 @@ public class InvalidPropertyException extends BusinessException {
        private static final long serialVersionUID = -3988379180445723963L;
 
        /**
-        * Create a InvalidPropertyException. 
-        * @param message the error message. 
+        * Create a InvalidPropertyException.
+        * 
+        * @param message
+        *            the error message.
         */
-    public InvalidPropertyException (final String message) {
-        super(message);
-      }
+       public InvalidPropertyException(final String message) {
+               super(message);
+       }
+
+       /**
+        * Create a InvalidPropertyException.
+        * 
+        * @param messageKey
+        *            error message key
+        * @param context
+        *            parameters
+        */
+       public InvalidPropertyException(final String messageKey,
+                       final Object... context) {
+               super(messageKey, context);
+               // TODO auto-generated constructor
+       }
+
+       /**
+        * Create a InvalidPropertyException.
+        * 
+        * @param messageKey
+        *            error message key
+        * @param throwable
+        *            the original exception
+        * @param context
+        *            parameters
+        */
+       public InvalidPropertyException(final String messageKey,
+                       final Throwable throwable, final Object... context) {
+               super(messageKey, throwable, context);
+       }
 }
\ No newline at end of file
index 7e6947d99d9affa9f25af9c7ee1ef3f5b392d9dd..cfa49834adb4b1804f9d6a430c2c856924e4ce91 100644 (file)
@@ -542,11 +542,10 @@ public class DocumentServiceImpl implements DocumentService {
                                for (Iterator<Relation> i = aDoc.getAllRelations().iterator(); i
                                                .hasNext();) {
                                        Relation link = i.next();
-                                       if (!link.getClass().equals(VersionsRelation.class)) {
-                                               continue;
+                                       if (link.getClass().equals(VersionsRelation.class)) {
+                                               previous = (Document) link.getTo(); // Versioned document
+                                               break;
                                        }
-                                       previous = (Document) link.getTo(); // Versioned document
-                                       break;
                                }
                        }
                        if (aDoc.getProgressState() != null) {
index 9abcf754aa078c50a6faaf70b5d0383e409d9fb4..e30099e270186f67a14f9e5068abd6d62edd30d3 100644 (file)
@@ -50,30 +50,47 @@ public interface PublicationService {
 
        /**
         * Create a new version of the document.
-        * @param step the study step where the document is published
-        * @param user the current user
-        * @param filename the new version file name
-        * @param docIndex the publication id
-        * @param docver new document version string, empty for external documents
-        * @param summary the version comment
-        * @param state the new state of the document
-        * @param date the new modification date
-        * @param docuses the array of documents ids used by the versioned document
-        * @param docusedby the array of impacted documents ids
-        * @throws MissedPropertyException if some mandatory property is missed 
-        * @throws InvalidPropertyException if some property has invalid value
-        * @throws MultiplyDefinedException if some property occurs several times
-        * @throws IOException if file moving is failed
-        * @throws MismatchException if step number in properties doesn't match to the given step
-        * @throws NotApplicableException if publication's document is undefined
-        * @throws InterruptedException by Thread.sleep if interrupted
+        * 
+        * @param step
+        *            the study step where the document is published
+        * @param user
+        *            the current user
+        * @param filename
+        *            the new version file name
+        * @param docIndex
+        *            the publication id
+        * @param docver
+        *            new document version string, empty for external documents
+        * @param summary
+        *            the version comment
+        * @param state
+        *            the new state of the document
+        * @param date
+        *            the new modification date
+        * @param docuses
+        *            the array of documents ids used by the versioned document
+        * @param docusedby
+        *            the array of impacted documents ids
+        * @throws MissedPropertyException
+        *             if some mandatory property is missed
+        * @throws InvalidPropertyException
+        *             if some property has invalid value
+        * @throws MultiplyDefinedException
+        *             if some property occurs several times
+        * @throws IOException
+        *             if file moving is failed
+        * @throws MismatchException
+        *             if step number in properties doesn't match to the given step
+        * @throws NotApplicableException
+        *             if publication's document is undefined
+        * @throws InterruptedException
+        *             by Thread.sleep if interrupted
         */
-       void versionDocument(Step step, User user, String filename,
-                       long docIndex, String docver, String summary, ProgressState state,
-                       Date date, String[] docuses, long[] docusedby)
-                       throws MissedPropertyException, InvalidPropertyException,
-                       MultiplyDefinedException, IOException, MismatchException,
-                       NotApplicableException, InterruptedException;
+       void versionDocument(Step step, User user, String filename, long docIndex,
+                       String docver, String summary, ProgressState state, Date date,
+                       String[] docuses, long[] docusedby) throws MissedPropertyException,
+                       InvalidPropertyException, MultiplyDefinedException, IOException,
+                       MismatchException, NotApplicableException, InterruptedException;
 
        /**
         * Returns the study Step into which the document version referenced by this publication has been published.
@@ -173,7 +190,7 @@ public interface PublicationService {
        /**
         * Publishes the document referenced by this publication into the owner Project Element under the given state, the revision number of
         * the document being automatically set accordingly. If the given state is In-Draft and the document is final result of the owner study,
-        * this automatically promotes the study to In-Draft.
+        * this automatically promotes the study to In-Draft. The old publication is removed from the scenario.
         * 
         * @param aPublication
         *            the document publication
@@ -192,7 +209,7 @@ public interface PublicationService {
         * of the referenced document is supposed being automatically set according to the given revision number, but, due to the versioning
         * scheme, as it is not possible to differentiate In-Work and In-Draft states, this function has been deprecated (it is currently used
         * only for the need of integration of Microsoft Office which anyway has to be redesigned). <br/> Note: in the context of branch
-        * versioning, the given revision may be modified by an update of the branch name.
+        * versioning, the given revision may be modified by an update of the branch name. The old publication is removed from the scenario.
         * 
         * @param aPublication
         *            the document publication
index 150cd1fb638b18996539c2f89312c6482291b97a..de0ed295f66c71d36c6464c724df39e04d56e30c 100644 (file)
@@ -9,6 +9,7 @@
 
 package org.splat.service;
 
+import java.io.IOException;
 import java.util.List;
 
 import org.splat.dal.bo.kernel.User;
@@ -17,8 +18,10 @@ import org.splat.dal.bo.som.Scenario;
 import org.splat.dal.bo.som.SimulationContext;
 import org.splat.dal.bo.som.Study;
 import org.splat.kernel.InvalidPropertyException;
+import org.splat.kernel.MismatchException;
 import org.splat.kernel.MissedPropertyException;
 import org.splat.kernel.MultiplyDefinedException;
+import org.splat.kernel.NotApplicableException;
 import org.splat.service.dto.StepDTO;
 import org.splat.som.Step;
 
@@ -98,7 +101,15 @@ public interface ScenarioService {
                        InvalidPropertyException, MultiplyDefinedException;
 
        /**
-        * Check-in the scenario after SALOME session.
+        * Check-in the scenario after SALOME session. If a document to be checked in already exists then create a new version of it. Otherwise
+        * create a new document of the appropriate step result type.
+        * <ul>
+        * <li>For each new created document version we copy Uses relations from the previous document version. If used document has been also
+        * versioned during this check-in operation then refer to its new version.</li>
+        * <li>For each new document create uses relation to the last versions of results of a previous step.</li>
+        * </ul>
+        * <b>NOTE:</b> Only the first attached file is processed for each document. <br/>All new documents/versions are created in inWORK
+        * state.
         * 
         * @param scenId
         *            the scenario id
@@ -106,9 +117,23 @@ public interface ScenarioService {
         *            the id of the user who modified documents
         * @param scInfo
         *            the list of scenario steps DTO
+        * @throws InvalidPropertyException
+        *             if the scenario hasn't some of given steps or documents
+        * @throws IOException
+        *             if a file can't be moved into the vault
+        * @throws MismatchException
+        *             if version creation in some of steps is failed
+        * @throws MissedPropertyException
+        *             if some mandatory property is missed when new document or new document version is created
+        * @throws MultiplyDefinedException
+        *             if some property is defined several times when new document or new document version is created
+        * @throws NotApplicableException
+        *             if failed saving of a new publication with a given state
         */
        void checkin(final long scenId, final long userId,
-                       final List<StepDTO> scInfo);
+                       final List<StepDTO> scInfo) throws InvalidPropertyException,
+                       MissedPropertyException, MultiplyDefinedException,
+                       MismatchException, IOException, NotApplicableException;
 
        /**
         * Check in the scenario.
index b722a6e7f7c20164d43bf40cfac91433da44b399..4dc064893d08da5f68ac4c445de8e7c894372a9d 100644 (file)
@@ -12,29 +12,40 @@ package org.splat.service;
 import java.io.IOException;
 import java.util.ArrayList;
 import java.util.Calendar;
+import java.util.Date;
+import java.util.HashMap;
 import java.util.Iterator;
 import java.util.List;
+import java.util.Map;
 
 import org.apache.log4j.Logger;
+import org.splat.common.properties.MessageKeyEnum;
 import org.splat.dal.bo.kernel.Relation;
 import org.splat.dal.bo.kernel.User;
 import org.splat.dal.bo.som.ConvertsRelation;
+import org.splat.dal.bo.som.Document;
+import org.splat.dal.bo.som.DocumentType;
 import org.splat.dal.bo.som.File;
 import org.splat.dal.bo.som.KnowledgeElement;
 import org.splat.dal.bo.som.KnowledgeElementType;
+import org.splat.dal.bo.som.ProgressState;
 import org.splat.dal.bo.som.Publication;
 import org.splat.dal.bo.som.Scenario;
 import org.splat.dal.bo.som.SimulationContext;
 import org.splat.dal.bo.som.Study;
+import org.splat.dal.bo.som.UsesRelation;
 import org.splat.dal.dao.kernel.UserDAO;
 import org.splat.dal.dao.som.KnowledgeElementDAO;
 import org.splat.dal.dao.som.KnowledgeElementTypeDAO;
 import org.splat.dal.dao.som.ScenarioDAO;
 import org.splat.dal.dao.som.StudyDAO;
 import org.splat.kernel.InvalidPropertyException;
+import org.splat.kernel.MismatchException;
 import org.splat.kernel.MissedPropertyException;
 import org.splat.kernel.MultiplyDefinedException;
+import org.splat.kernel.NotApplicableException;
 import org.splat.service.dto.DocumentDTO;
+import org.splat.service.dto.FileDTO;
 import org.splat.service.dto.StepDTO;
 import org.splat.service.technical.IndexService;
 import org.splat.service.technical.ProjectSettingsService;
@@ -119,6 +130,11 @@ public class ScenarioServiceImpl implements ScenarioService {
         */
        private ProjectSettingsService _projectSettings;
 
+       /**
+        * Injected document type service.
+        */
+       private DocumentTypeService _documentTypeService;
+
        /**
         * Get the projectElementService.
         * 
@@ -183,7 +199,7 @@ public class ScenarioServiceImpl implements ScenarioService {
         * 
         * @see org.splat.service.ScenarioService#getScenarioInfo(long)
         */
-       @Transactional
+       @Transactional(readOnly = true)
        public List<StepDTO> getScenarioInfo(final long scenarioId) {
                List<StepDTO> res = new ArrayList<StepDTO>();
                // Get the scenario from the database by id
@@ -362,9 +378,179 @@ public class ScenarioServiceImpl implements ScenarioService {
         * 
         * @see org.splat.service.ScenarioService#checkin(long, long, java.util.List)
         */
+       @Transactional
        public void checkin(final long scenId, final long userId,
-                       final List<StepDTO> scInfo) {
+                       final List<StepDTO> scInfo) throws InvalidPropertyException,
+                       MissedPropertyException, MultiplyDefinedException,
+                       MismatchException, IOException, NotApplicableException {
+               // Get the scenario from the database by id
+               Scenario aScenario = getScenarioDAO().get(scenId);
+               // Get the user who perform this check-in operation
+               User aUser = getUserService().selectUser(userId);
+               // Get activities of the scenario
+               Step[] steps = getProjectElementService().getSteps(aScenario);
+               // Find result document types
+               List<DocumentType> resTypes = getDocumentTypeService()
+                               .selectResultTypes();
+
+               // For each processed existing document keep its new version
+               Map<Document, Document> newVersion = new HashMap<Document, Document>();
+               // For each processed existing document keep its previous version
+               Map<Publication, Document> prevVersion = new HashMap<Publication, Document>();
+               // Keep newly created documents to create uses relations to results of a previous step.
+               List<Publication> newVers = new ArrayList<Publication>();
+               List<Publication> newDocs = new ArrayList<Publication>();
+               // For each step DTO
+               DocumentType resType;
+               java.io.File updir;
+               Document.Properties dprop = new Document.Properties();
+               Date aDate = new Date();
+               for (StepDTO stepDTO : scInfo) {
+                       // Find a result document type of the step
+                       int i = 0;
+                       resType = null;
+                       do {
+                               if (resTypes.get(i).isResultOf(
+                                               getProjectSettings().getStep(stepDTO.getNumber()))) {
+                                       resType = resTypes.get(i);
+                               }
+                               i++;
+                       } while ((resType == null) && (i < resTypes.size()));
+
+                       // Find the appropriate scenario step
+                       Step step = findStep(stepDTO, steps);
+
+                       // Process documents of the step
+                       for (DocumentDTO doc : stepDTO.getDocs()) {
+                               if (doc.getFiles().size() > 0) {
+                                       // NOTE: Process only the first attached file for each document
+                                       FileDTO file = doc.getFiles().get(0);
+
+                                       // Get document title as the file name
+                                       java.io.File upfile = new java.io.File(file.getPath());
+                                       String fileFormat = upfile.getName().substring(
+                                                       upfile.getName().lastIndexOf('.') + 1);
+                                       String docname = upfile.getName().substring(0,
+                                                       upfile.getName().lastIndexOf('.'));
+
+                                       // Create a new document or a new version of the document
+                                       dprop.clear();
+                                       dprop.setAuthor(aUser).setDate(aDate);
+                                       Publication pub, newPub;
+
+                                       if (doc.getId() > 0) {
+                                               // If the document already exists then create a new version of it
+                                               // Find the document publication
+                                               pub = step.getDocument(doc.getId());
+                                               if (pub == null) {
+                                                       throw new InvalidPropertyException(
+                                                                       MessageKeyEnum.SCN_000002.toString(), doc
+                                                                                       .getId());
+                                               }
+                                               newPub = getStepService().versionDocument(step, pub,
+                                                               dprop);
+                                               // Remeber the link from the old document to the new document version
+                                               newVersion.put(pub.value(), newPub.value());
+                                               // Remember the new version publication
+                                               newVers.add(newPub);
+                                               // Remember the previouse document version for the new publication
+                                               prevVersion.put(newPub, pub.value());
+                                       } else {
+
+                                               // Otherwise create a new document of the result type
+                                               // If result type is not found try to get type by file extension
+                                               if (resType == null) {
+                                                       dprop.setType(getProjectSettings()
+                                                                       .getDefaultDocumentType(step.getStep(),
+                                                                                       fileFormat));
+                                               } else {
+                                                       dprop.setType(resType);
+                                               }
+                                               dprop.setDescription("Checked in").setName(docname)
+                                                               .setFormat(fileFormat);
+                                               newPub = getStepService().createDocument(step, dprop);
+
+                                               // Remeber the new document
+                                               newDocs.add(newPub);
+                                       }
+
+                                       // Attach the file to the created document
+                                       updir = newPub.getSourceFile().asFile();
+                                       if (LOG.isInfoEnabled()) {
+                                               LOG.info("Moving \"" + upfile.getName() + "\" to \""
+                                                               + updir.getPath() + "\".");
+                                       }
+                                       if (upfile.renameTo(updir)) {
+                                               // Save the new publication in the scenario.
+                                               // The old publication is removed from the scenario here.
+                                               getPublicationService().saveAs(newPub,
+                                                               ProgressState.inWORK); // May throw FileNotFound if rename was not done
+                                       }
+                               }
+                       }
+               }
+
+               // Set uses/used relations
+
+               // For each new version copy uses relations from the previous version.
+               for (Publication newVer : newVers) {
+                       // For each Uses relation of the previous version
+                       for (Relation rel : prevVersion.get(newVer).getRelations(
+                                       UsesRelation.class)) {
+                               // If used document has been also versioned then refer to its new version.
+                               Document usedDoc = ((UsesRelation) rel).getTo();
+                               if (newVersion.containsKey(usedDoc)) {
+                                       usedDoc = newVersion.get(usedDoc);
+                               }
+                               // Build the appropriate relation for the new version.
+                               newVer.addDependency(usedDoc);
+                       }
+                       // TODO: Outdate documents which depend from the previous version and were not checked in during this operation.
+
+               }
+
+               // For each new document create uses relation to the last versions of
+               // results of the previous step.
+               for (Publication newDoc : newDocs) {
+                       // Find used document type according to the configuration.
+                       // Find documents of used type in the previous study step.
+                       
+                       // Create uses relation from the new document 
+                       // to the found document in the previous step.
+                       //newDoc.addDependency(to);
+               }
 
+               // Mark the scenario as checked in
+               checkin(aScenario);
+       }
+
+       /**
+        * Find appropriate step in the array of scenario steps according to the given step DTO.
+        * 
+        * @param stepDTO
+        *            the stepDTO
+        * @param steps
+        *            scenario steps
+        * @return appropriate scenario step
+        * @throws InvalidPropertyException
+        *             if appropriate step is not found
+        */
+       private Step findStep(final StepDTO stepDTO, final Step[] steps)
+                       throws InvalidPropertyException {
+               int i = 0;
+               Step step = null;
+               do {
+                       if (steps[i].getNumber() == stepDTO.getNumber()) {
+                               step = steps[i];
+                       }
+                       i++;
+               } while ((step == null) && (i < steps.length));
+
+               if (step == null) {
+                       throw new InvalidPropertyException(MessageKeyEnum.SCN_000001
+                                       .toString(), stepDTO.getNumber());
+               }
+               return step;
        }
 
        /**
@@ -748,4 +934,24 @@ public class ScenarioServiceImpl implements ScenarioService {
                _projectSettings = projectSettingsService;
        }
 
+       /**
+        * Get the documentTypeService.
+        * 
+        * @return the documentTypeService
+        */
+       public DocumentTypeService getDocumentTypeService() {
+               return _documentTypeService;
+       }
+
+       /**
+        * Set the documentTypeService.
+        * 
+        * @param documentTypeService
+        *            the documentTypeService to set
+        */
+       public void setDocumentTypeService(
+                       final DocumentTypeService documentTypeService) {
+               _documentTypeService = documentTypeService;
+       }
+
 }
index fbbcb088fca0ec6e905b45abfa80cfbd0a7f97ff..281d57c341852330b919b6402c32cbeb2208f630 100644 (file)
@@ -24,7 +24,6 @@ import org.splat.dal.bo.som.KnowledgeElement;
 import org.splat.dal.bo.som.Publication;
 import org.splat.dal.bo.som.Scenario;
 import org.splat.dal.bo.som.SimulationContext;
-import org.splat.dal.bo.som.Study;
 import org.splat.dal.bo.som.UsedByRelation;
 import org.splat.dal.bo.som.UsesRelation;
 import org.splat.dal.bo.som.VersionsRelation;
@@ -378,7 +377,9 @@ public class StepServiceImpl implements StepService {
                newdoc.addRelation(aRel);
                
                // Update of usedby relations, if exist
-               List<Relation> relist = previous.getRelations(UsedByRelation.class);
+/* RKV: Consider the new version as not used by old dependent documents. 
+ * So these documents must be marked as outdated then.
+               List<Relation> relist = previous.getRelations(UsedByRelation.class);
                Study scope = aStep.getOwnerStudy();
                for (Iterator<Relation> i = relist.iterator(); i.hasNext();) {
                        UsedByRelation relation = (UsedByRelation) i.next();
@@ -389,6 +390,7 @@ public class StepServiceImpl implements StepService {
                                relation.moveTo(newdoc);
                        }
                }
+*/
                return new Publication(newdoc, aStep.getOwner());
        }
 
index 1f3b3f3c3f43926b6173ece198106bc78592fa66..c411370dcbae7eee618c0b00fb7591ff4c6052f7 100644 (file)
@@ -44,7 +44,7 @@ public class DocumentDTO {
        }
        
        /**
-        * Constructor with initialization.
+        * Default constructor.
         */
        public DocumentDTO() {
        }
index e7e5c1410102e73f8893ae82c50208d3a8c222bb..99405b640ab0855492febe49fd421aa30f8715b1 100644 (file)
@@ -53,7 +53,7 @@ public class FileDTO {
        }
        
        /**
-        * Constructor with initialization.
+        * Constructor with partial initialization.
         * 
         * @param relativePath
         *            relative file path
index 0f1326af67e4762683ffd312326ec3c0c8e869bd..6fad6ec51b1c872807d974f6ce6f9fb38ec58e0e 100644 (file)
@@ -102,7 +102,7 @@ public class StepDTO {
         * 
         * @return the number
         */
-       public int getNumber() {
+       public Integer getNumber() {
                return _number;
        }
 
index 576fd67ff3f102cd817d936cd34c1c440f328491..16a446c1579e72bebfc7fe26f5623e65df8bd9c4 100644 (file)
@@ -15,6 +15,7 @@ import java.util.HashSet;
 import java.util.List;
 import java.util.Set;
 
+import org.splat.dal.bo.som.DocumentType;
 import org.splat.dal.bo.som.ProjectElement;
 import org.splat.service.technical.ProjectSettingsServiceImpl.FileNaming;
 import org.splat.service.technical.ProjectSettingsServiceImpl.ProjectSettingsValidationCycle;
@@ -27,7 +28,7 @@ public interface ProjectSettingsService {
        /**
         * Transient study step data.
         */
-    class Step {
+       class Step {
                /**
                 * The sequential number of the step.
                 */
@@ -149,6 +150,7 @@ public interface ProjectSettingsService {
 
                /**
                 * Get the module.
+                * 
                 * @return the module
                 */
                public String getModule() {
@@ -157,7 +159,9 @@ public interface ProjectSettingsService {
 
                /**
                 * Set the module.
-                * @param module the module to set
+                * 
+                * @param module
+                *            the module to set
                 */
                public void setModule(final String module) {
                        _module = module;
@@ -165,6 +169,7 @@ public interface ProjectSettingsService {
 
                /**
                 * Get the key.
+                * 
                 * @return the key
                 */
                public String getKey() {
@@ -173,7 +178,9 @@ public interface ProjectSettingsService {
 
                /**
                 * Set the key.
-                * @param key the key to set
+                * 
+                * @param key
+                *            the key to set
                 */
                public void setKey(final String key) {
                        _key = key;
@@ -247,7 +254,7 @@ public interface ProjectSettingsService {
         */
        List<ProjectSettingsService.Step> getStepsOf(
                        Class<? extends ProjectElement> level);
-       
+
        /**
         * Check if a file of the given format should be imported during check-in of a document of the given type.
         * 
@@ -257,5 +264,25 @@ public interface ProjectSettingsService {
         *            file format
         * @return true if file should be imported
         */
-       public boolean doImport(final String type, final String format);
+       boolean doImport(final String type, final String format);
+
+       /**
+        * Get default document type for the given file format on the given study step.
+        * 
+        * @param step
+        *            the study step
+        * @param format
+        *            the file format (extension)
+        * @return document type
+        */
+       DocumentType getDefaultDocumentType(final Step step, final String format);
+
+       /**
+        * Get the list of default formats for the given study step.
+        * 
+        * @param step
+        *            the study step
+        * @return list of formats (file extensions)
+        */
+       List<String> getDefaultFormats(final Step step);
 }
index 49f84de4a7dcbc795925dfddb64ec6ab5655eb71..c9498f5135faf538d6b0270257892a4a192cda01 100644 (file)
@@ -53,6 +53,11 @@ public class ProjectSettingsServiceImpl implements ProjectSettingsService {
        protected final static Logger LOG = Logger
                        .getLogger(ProjectSettingsServiceImpl.class);
 
+       /**
+        * Type attribute name.
+        */
+       private final static String TYPE_ATTR = "type";
+
        // Non persistent configuration information
        /**
         * Repository settings.
@@ -77,11 +82,11 @@ public class ProjectSettingsServiceImpl implements ProjectSettingsService {
        /**
         * Configuration document validation cycles.
         */
-       private transient List<ProjectSettingsValidationCycle> _concycles;
+       private transient final List<ProjectSettingsValidationCycle> _concycles = new ArrayList<ProjectSettingsValidationCycle>();
        /**
         * Document type mappings to file formats which should be imported into SALOME during check-out.
         */
-       private transient Map<String, List<String>> _mapimport;
+       private transient final Map<String, List<String>> _mapimport = new HashMap<String, List<String>>();
 
        // Temporary attributes initialized from the configuration file for populating the database with object types
        /**
@@ -123,8 +128,27 @@ public class ProjectSettingsServiceImpl implements ProjectSettingsService {
         */
        private DocumentTypeService _documentTypeService;
 
+       /**
+        * Default document types structured by step.formats.
+        */
+       private transient final Map<String, DocumentType> _defdoctype = new LinkedHashMap<String, DocumentType>();
+
+       /**
+        * File naming strategy enumeration.
+        */
        public enum FileNaming {
-               title, encoded, asis
+               /**
+                * Name by document title.
+                */
+               title,
+               /**
+                * Generate encoded name.
+                */
+               encoded,
+               /**
+                * Keep original file name.
+                */
+               asis
        }
 
        /**
@@ -318,6 +342,44 @@ public class ProjectSettingsServiceImpl implements ProjectSettingsService {
                                format));
        }
 
+       /**
+        * Get default document type for the given file format on the given study step.
+        * 
+        * @param step
+        *            the study step
+        * @param format
+        *            the file format (extension)
+        * @return document type
+        */
+       public DocumentType getDefaultDocumentType(final Step step,
+                       final String format) {
+               String[] table = format.split("\\x2E");
+               return _defdoctype
+                               .get(step.getNumber() + "." + table[table.length - 1]); // May be null
+       }
+
+       /**
+        * Get the list of default formats for the given study step.
+        * 
+        * @param step
+        *            the study step
+        * @return list of formats (file extensions)
+        */
+       public List<String> getDefaultFormats(final Step step) {
+               Integer stepNumber = step.getNumber();
+               List<String> result = new ArrayList<String>();
+
+               for (String i : _defdoctype.keySet()) {
+                       String[] key = i.split("\\x2E");
+                       // PDF is not an authoring format
+                       if (stepNumber.equals(Integer.valueOf(key[0]))
+                                       && (!key[1].equals("pdf"))) {
+                               result.add(key[1]); // Formats are unique
+                       }
+               }
+               return result;
+       }
+
        /**
         * Initialize the database: create all necessary default staff defined in the configuration file.
         */
@@ -394,10 +456,13 @@ public class ProjectSettingsServiceImpl implements ProjectSettingsService {
                                                        resultype);
                                }
                        }
-                       // Validations tag
-                       _concycles = loadValidationCycles(children, resultype);
 
-                       _mapimport = loadFormatMappings(children);
+                       // Validations tag
+                       loadValidationCycles(children, resultype);
+                       // Load steps result document types mapped to file formats
+                       loadFormatMappings(children);
+                       // Load default mapping of file formats to document types for each step
+                       loadDefaultDocTypes(children);
 
                        if (!getDatabase().getCheckedDB().isInitialized()) {
                                // Load object type definitions
@@ -412,7 +477,8 @@ public class ProjectSettingsServiceImpl implements ProjectSettingsService {
                                        child = nlist.item(i);
                                        if ("article".equals(child.getNodeName())) {
                                                natr = child.getAttributes();
-                                               String type = natr.getNamedItem("type").getNodeValue();
+                                               String type = natr.getNamedItem(TYPE_ATTR)
+                                                               .getNodeValue();
                                                String uses = null;
                                                child = natr.getNamedItem("uses");
                                                if (child != null) {
@@ -436,11 +502,9 @@ public class ProjectSettingsServiceImpl implements ProjectSettingsService {
         * 
         * @param children
         *            XML nodes
-        * @return map of document type names to lists of file formats
         */
-       private Map<String, List<String>> loadFormatMappings(
-                       final Map<String, Node> children) {
-               Map<String, List<String>> res = new HashMap<String, List<String>>();
+       private void loadFormatMappings(final Map<String, Node> children) {
+               _mapimport.clear();
                Element maps = (Element) children.get("mappings");
                Element doc, imp;
                String type, format;
@@ -451,7 +515,7 @@ public class ProjectSettingsServiceImpl implements ProjectSettingsService {
                        docs = maps.getElementsByTagName("document");
                        for (int i = 0; i < docs.getLength(); i++) {
                                doc = (Element) docs.item(i);
-                               type = doc.getAttribute("type");
+                               type = doc.getAttribute(TYPE_ATTR);
                                if (!type.isEmpty()) {
                                        // Read file formats for the document type
                                        imports = doc.getElementsByTagName("import");
@@ -464,12 +528,50 @@ public class ProjectSettingsServiceImpl implements ProjectSettingsService {
                                                }
                                        }
                                        if (!formats.isEmpty()) {
-                                               res.put(type, formats);
+                                               _mapimport.put(type, formats);
                                        }
                                }
                        }
                }
-               return res;
+       }
+
+       /**
+        * Load default document types from XML configuration.
+        * 
+        * @param children
+        *            XML nodes
+        */
+       private void loadDefaultDocTypes(final Map<String, Node> children) {
+               _defdoctype.clear();
+               Node child = children.get("default-doctypes");
+               NodeList nlist = child.getChildNodes();
+
+               List<DocumentType> listype = getDocumentTypeService().selectAllTypes();
+               Map<String, DocumentType> maptype = new HashMap<String, DocumentType>();
+               for (Iterator<DocumentType> i = listype.iterator(); i.hasNext();) {
+                       DocumentType type = i.next();
+                       maptype.put(type.getName(), type);
+               }
+               for (int i = 0; i < nlist.getLength(); i++) {
+                       child = nlist.item(i);
+                       if (!child.getNodeName().equals("step")) {
+                               continue;
+                       }
+
+                       String nstep = child.getAttributes().getNamedItem("number")
+                                       .getNodeValue();
+                       NodeList map = child.getChildNodes();
+                       for (int j = 0; j < map.getLength(); j++) {
+                               child = map.item(j);
+                               if (!child.getNodeName().equals("mapping")) {
+                                       continue;
+                               }
+                               NamedNodeMap natr = child.getAttributes();
+                               String dext = natr.getNamedItem("extension").getNodeValue();
+                               String type = natr.getNamedItem(TYPE_ATTR).getNodeValue();
+                               _defdoctype.put(nstep + "." + dext, maptype.get(type));
+                       }
+               }
        }
 
        /**
@@ -550,12 +652,11 @@ public class ProjectSettingsServiceImpl implements ProjectSettingsService {
         *            XML nodes
         * @param resultype
         *            list of result types
-        * @return return list of validation cycles
         */
-       private List<ProjectSettingsValidationCycle> loadValidationCycles(
-                       final Map<String, Node> children, final List<String> resultype) {
+       private void loadValidationCycles(final Map<String, Node> children,
+                       final List<String> resultype) {
+               _concycles.clear();
                Node child = children.get("validations");
-               List<ProjectSettingsValidationCycle> cycles = new ArrayList<ProjectSettingsValidationCycle>();
                Map<String, Node> datag = XDOM.getNamedChildNodes(child);
                NamedNodeMap natr;
 
@@ -574,11 +675,10 @@ public class ProjectSettingsServiceImpl implements ProjectSettingsService {
                                                actor[j] = Actor.valueOf(child.getNodeValue()); // Validation step is required
                                        }
                                }
-                               cycles.add(new ProjectSettingsValidationCycle(name, actor));
+                               _concycles.add(new ProjectSettingsValidationCycle(name, actor));
                        }
                }
-               cycles.add(new ProjectSettingsValidationCycle()); // Adds the built-in validation cycle
-               return cycles;
+               _concycles.add(new ProjectSettingsValidationCycle()); // Adds the built-in validation cycle
        }
 
        /**
@@ -599,7 +699,7 @@ public class ProjectSettingsServiceImpl implements ProjectSettingsService {
                for (int i = 0; i < nlist.getLength(); i++) {
                        child = nlist.item(i);
                        if (child.getNodeName().equals("article")) {
-                               articles.add(child.getAttributes().getNamedItem("type")
+                               articles.add(child.getAttributes().getNamedItem(TYPE_ATTR)
                                                .getNodeValue());
                        }
                }
index 8fb2dbb8063f461c1b8e49cdf9e26166c2bf3801..13293474b28c32c51103cc784cb133fd3d511370 100644 (file)
@@ -48,8 +48,8 @@ http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
                <property name="indexService" ref="indexService" />
                <property name="knowledgeElementDAO" ref="knowledgeElementDAO" />
                <property name="studyService" ref="studyService" />
-        <property name="projectElementService"
-            ref="projectElementService" />
+               <property name="projectElementService"
+                       ref="projectElementService" />
        </bean>
 
        <bean id="knowledgeElementTypeService"
@@ -68,15 +68,16 @@ http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
                <property name="publicationDAO" ref="publicationDAO" />
                <property name="projectElementDAO" ref="projectElementDAO" />
                <property name="repositoryService" ref="repositoryService" />
-        <property name="timestampDAO" ref="timestampDAO" />
+               <property name="timestampDAO" ref="timestampDAO" />
        </bean>
 
        <bean id="scenarioService"
                class="org.splat.service.ScenarioServiceImpl">
+               <property name="documentTypeService" ref="documentTypeService" />
                <property name="indexService" ref="indexService" />
                <property name="projectElementService"
                        ref="projectElementService" />
-        <property name="projectSettings" ref="projectSettings" />
+               <property name="projectSettings" ref="projectSettings" />
                <property name="publicationService" ref="publicationService" />
                <property name="stepService" ref="stepService" />
                <property name="studyService" ref="studyService" />
@@ -112,13 +113,13 @@ http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
                <property name="simulationContextDAO"
                        ref="simulationContextDAO" />
                <property name="projectElementDAO" ref="projectElementDAO" />
-        <property name="projectSettings" ref="projectSettings" />
+               <property name="projectSettings" ref="projectSettings" />
                <property name="versionsRelationDAO" ref="versionsRelationDAO" />
        </bean>
 
        <bean id="simulationContextService"
                class="org.splat.service.SimulationContextServiceImpl">
-        <property name="projectSettings" ref="projectSettings" />
+               <property name="projectSettings" ref="projectSettings" />
                <property name="simulationContextDAO"
                        ref="simulationContextDAO" />
                <property name="simulationContextTypeDAO"
index 41ca64cd0f7b84c0fe74c0f16b713ac0893a11df..057b3b56b85ce4613463f489025cb70e5d757584 100644 (file)
@@ -1,7 +1,6 @@
 schema.version     = D-0.3
 
 wapp.version       = D-0.5
-wapp.root          = D:/users/rkv/SIMAN/SIMAN_SRC/Workspace/Siman/WebContent/
 wapp.login         = conf/login.conf
 wapp.configuration = som.xml
 wapp.customization = conf/my.xml
index 1e36c05fd7f3141924bc3cebcb9594cd01692b33..64bcd7c8fa779cdb155f99fffc1aca8c58c99fc9 100644 (file)
         </document>
     </mappings>
 
+    <default-doctypes>
+        <step number="1">
+            <mapping extension="pdf"    type="requirements"/>
+            <mapping extension="doc"    type="specification"/>     <!-- Microsoft Word 2003 and earlier -->
+            <mapping extension="docx"   type="specification"/>     <!-- Microsoft Word 2007 and later   -->
+            <mapping extension="xml"    type="specification"/>     <!-- Microsoft Word 2007 Open XML    -->
+        </step>
+        <step number="2">
+            <mapping extension="doc"    type="design"/>
+            <mapping extension="docx"   type="design"/>
+            <mapping extension="xml"    type="design"/>
+        </step>
+        <step number="3">
+            <mapping extension="doc"    type="memorandum"/>
+            <mapping extension="docx"   type="memorandum"/>
+            <mapping extension="xml"    type="memorandum"/>
+            <mapping extension="sldprt" type="geometry"/>          <!-- SolidWorks Part                 -->
+            <mapping extension="sldasm" type="geometry"/>          <!-- SolidWorks Assembly             -->
+            <mapping extension="part"   type="geometry"/>          <!-- GEOM Part                       -->
+            <mapping extension="py"     type="geometry"/>          <!-- GEOM Python script              -->
+        </step>
+        <step number="4">
+            <mapping extension="doc"    type="memorandum"/>
+            <mapping extension="docx"   type="memorandum"/>
+            <mapping extension="xml"    type="memorandum"/>
+            <mapping extension="med"    type="model"/>
+            <mapping extension="py"     type="model"/>             <!-- SMESH Python script             -->
+        </step>
+    </default-doctypes>
+
 </project-structure>
\ No newline at end of file
index f5f27f004ebd48a611e723c4805ef30d151d9332..da005b31909a577e1a3231c89480ad41fa3c584e 100644 (file)
@@ -62,9 +62,9 @@ public class TestProjectSettingsService extends BaseTest {
         * <i>2. call the method for a xml without mappings.</i><BR>
         * <i>3. call the method for a not existing file.</i><BR>
         * <B>Test data : </B><BR>
-        * <i>no input parameters</i><BR>
-        * <i>no input parameters</i><BR>
-        * <i>no input parameters</i><BR>
+        * <i>test/som.xml</i><BR>
+        * <i>test/som-without-mappings.xml</i><BR>
+        * <i>not existing xxx.xml</i><BR>
         * 
         * <B>Outcome results:</B><BR>
         * <i>
@@ -90,6 +90,7 @@ public class TestProjectSettingsService extends BaseTest {
                /*
                 * geometry: brep model: med loads: c3m results: med
                 */
+               _projectSettings.getAllSteps().clear(); // Clear config to be able to load it again
                try {
                        _projectSettings.configure(ClassLoader.getSystemResource(
                                        "test/som.xml").getPath());
@@ -133,4 +134,286 @@ public class TestProjectSettingsService extends BaseTest {
                LOG.debug(">>>>> END testGetScenarioInfo()");
        }
 
+       /**
+        * Test of loading file formats mappings to document types from customization XML file.<BR>
+        * <B>Description :</B> <BR>
+        * <i>Load customization and check the result.</i><BR>
+        * <B>Action : </B><BR>
+        * <i>1. call the method for som.xml</i><BR>
+        * <i>2. call the method for a xml without mappings.</i><BR>
+        * <i>3. call the method for a not existing file.</i><BR>
+        * <B>Test data : </B><BR>
+        * <i>test/som.xml</i><BR>
+        * <i>test/som-without-mappings.xml</i><BR>
+        * <i>not existing xxx.xml</i><BR>
+        * 
+        * <B>Outcome results:</B><BR>
+        * <i>
+        * <ul>
+        * <li>Following mappings must be loaded:<BR/>
+        * <ul>
+        * <li>step 1
+        * <ul>
+        * <li>pdf: requirements</li>
+        * <li>doc: specification</li>
+        * <!-- Microsoft Word 2003 and earlier -->
+        * <li>docx: specification</li>
+        * <!-- Microsoft Word 2007 and later -->
+        * <li>xml: specification</li>
+        * <!-- Microsoft Word 2007 Open XML -->
+        * </ul>
+        * </li>
+        * <li>step 2
+        * <ul>
+        * <li>doc: design</li>
+        * <li>docx: design</li>
+        * <li>xml: design</li>
+        * </ul>
+        * </li>
+        * <li>step 3
+        * <ul>
+        * <li>doc: memorandum</li>
+        * <li>docx: memorandum</li>
+        * <li>xml: memorandum</li>
+        * <li>sldprt: geometry</li>
+        * <!-- SolidWorks Part -->
+        * <li>sldasm: geometry</li>
+        * <!-- SolidWorks Assembly -->
+        * <li>part: geometry</li>
+        * <!-- GEOM Part -->
+        * <li>py: geometry</li>
+        * <!-- GEOM Python script -->
+        * </ul>
+        * </li>
+        * <li>step 4
+        * <ul>
+        * <li>doc: memorandum</li>
+        * <li>docx: memorandum</li>
+        * <li>xml: memorandum</li>
+        * <li>med: model</li>
+        * <li>py: model</li>
+        * <!-- SMESH Python script -->
+        * </ul>
+        * </li>
+        * </ul>
+        * </li>
+        * <li>getDefaultDocumentType must always return null<BR>
+        * </li>
+        * <li>Exception is thrown<BR>
+        * </li>
+        * </ul>
+        * </i>
+        * 
+        * @throws IOException
+        *             if configuration loading is failed
+        * @throws SQLException
+        *             if configuration loading is failed
+        */
+       @Test
+       public void testLoadDefaultDocTypes() throws IOException, SQLException {
+               LOG.debug(">>>>> BEGIN testLoadDefaultDocTypes()");
+               // ////// Load good workflow customization
+               /*
+                * geometry: brep model: med loads: c3m results: med
+                */
+               _projectSettings.getAllSteps().clear(); // Clear config to be able to load it again
+               try {
+                       _projectSettings.configure(ClassLoader.getSystemResource(
+                                       "test/som.xml").getPath());
+               } catch (FileNotFoundException e) {
+                       Assert.fail("Can't find configuration file: ", e);
+               }
+               List<Step> steps = _projectSettings.getStepsOf(Scenario.class);
+               Assert.assertTrue(steps.size() > 0, "No steps are created.");
+
+               for (Step step : steps) {
+                       List<String> defTypes = _projectSettings.getDefaultFormats(step);
+                       Assert.assertNotNull(defTypes,
+                                       "getDefaultFormats must always return not null list:");
+                       switch (step.getNumber()) {
+                               case 1:
+                                       Assert.assertEquals(defTypes.size(), 4);
+                                       Assert.assertNotNull(_projectSettings
+                                                       .getDefaultDocumentType(step, "pdf"));
+                                       Assert.assertEquals(_projectSettings
+                                                       .getDefaultDocumentType(step, "pdf").getName(),
+                                                       "requirements");
+                                       Assert.assertNotNull(_projectSettings
+                                                       .getDefaultDocumentType(step, "doc"));
+                                       Assert.assertEquals(_projectSettings
+                                                       .getDefaultDocumentType(step, "doc").getName(),
+                                                       "specification");
+                                       Assert.assertNotNull(_projectSettings
+                                                       .getDefaultDocumentType(step, "docx"));
+                                       Assert.assertEquals(_projectSettings
+                                                       .getDefaultDocumentType(step, "docx").getName(),
+                                                       "specification");
+                                       Assert.assertNotNull(_projectSettings
+                                                       .getDefaultDocumentType(step, "xml"));
+                                       Assert.assertEquals(_projectSettings
+                                                       .getDefaultDocumentType(step, "xml").getName(),
+                                                       "specification");
+                                       break;
+                               case 2:
+                                       Assert.assertEquals(defTypes.size(), 3);
+                                       Assert.assertNull(_projectSettings.getDefaultDocumentType(
+                                                       step, "pdf"));
+                                       Assert.assertNotNull(_projectSettings
+                                                       .getDefaultDocumentType(step, "xml"));
+                                       Assert.assertEquals(_projectSettings
+                                                       .getDefaultDocumentType(step, "xml").getName(),
+                                                       "design");
+                                       Assert.assertNotNull(_projectSettings
+                                                       .getDefaultDocumentType(step, "doc"));
+                                       Assert.assertEquals(_projectSettings
+                                                       .getDefaultDocumentType(step, "doc").getName(),
+                                                       "design");
+                                       Assert.assertNotNull(_projectSettings
+                                                       .getDefaultDocumentType(step, "docx"));
+                                       Assert.assertEquals(_projectSettings
+                                                       .getDefaultDocumentType(step, "docx").getName(),
+                                                       "design");
+                                       break;
+                               case 3:
+                                       Assert.assertEquals(defTypes.size(), 7);
+                                       Assert.assertNull(_projectSettings.getDefaultDocumentType(
+                                                       step, "pdf"));
+                                       Assert.assertNotNull(_projectSettings
+                                                       .getDefaultDocumentType(step, "sldprt"));
+                                       Assert.assertEquals(_projectSettings
+                                                       .getDefaultDocumentType(step, "sldprt").getName(),
+                                                       "geometry");
+                                       Assert.assertNotNull(_projectSettings
+                                                       .getDefaultDocumentType(step, "sldasm"));
+                                       Assert.assertEquals(_projectSettings
+                                                       .getDefaultDocumentType(step, "sldasm").getName(),
+                                                       "geometry");
+                                       Assert.assertNotNull(_projectSettings
+                                                       .getDefaultDocumentType(step, "part"));
+                                       Assert.assertEquals(_projectSettings
+                                                       .getDefaultDocumentType(step, "part").getName(),
+                                                       "geometry");
+                                       Assert.assertNotNull(_projectSettings
+                                                       .getDefaultDocumentType(step, "py"));
+                                       Assert.assertEquals(_projectSettings
+                                                       .getDefaultDocumentType(step, "py").getName(),
+                                                       "geometry");
+                                       Assert.assertNotNull(_projectSettings
+                                                       .getDefaultDocumentType(step, "doc"));
+                                       Assert.assertEquals(_projectSettings
+                                                       .getDefaultDocumentType(step, "doc").getName(),
+                                                       "memorandum");
+                                       Assert.assertNotNull(_projectSettings
+                                                       .getDefaultDocumentType(step, "docx"));
+                                       Assert.assertEquals(_projectSettings
+                                                       .getDefaultDocumentType(step, "docx").getName(),
+                                                       "memorandum");
+                                       Assert.assertNotNull(_projectSettings
+                                                       .getDefaultDocumentType(step, "xml"));
+                                       Assert.assertEquals(_projectSettings
+                                                       .getDefaultDocumentType(step, "xml").getName(),
+                                                       "memorandum");
+                                       break;
+                               case 4:
+                                       Assert.assertEquals(defTypes.size(), 5);
+                                       Assert.assertNull(_projectSettings.getDefaultDocumentType(
+                                                       step, "pdf"));
+                                       Assert.assertNotNull(_projectSettings
+                                                       .getDefaultDocumentType(step, "med"));
+                                       Assert.assertEquals(_projectSettings
+                                                       .getDefaultDocumentType(step, "med").getName(),
+                                                       "model");
+                                       Assert.assertNotNull(_projectSettings
+                                                       .getDefaultDocumentType(step, "py"));
+                                       Assert.assertEquals(_projectSettings
+                                                       .getDefaultDocumentType(step, "py").getName(),
+                                                       "model");
+                                       Assert.assertNotNull(_projectSettings
+                                                       .getDefaultDocumentType(step, "doc"));
+                                       Assert.assertEquals(_projectSettings
+                                                       .getDefaultDocumentType(step, "doc").getName(),
+                                                       "memorandum");
+                                       Assert.assertNotNull(_projectSettings
+                                                       .getDefaultDocumentType(step, "docx"));
+                                       Assert.assertEquals(_projectSettings
+                                                       .getDefaultDocumentType(step, "docx").getName(),
+                                                       "memorandum");
+                                       Assert.assertNotNull(_projectSettings
+                                                       .getDefaultDocumentType(step, "xml"));
+                                       Assert.assertEquals(_projectSettings
+                                                       .getDefaultDocumentType(step, "xml").getName(),
+                                                       "memorandum");
+                                       break;
+                               default:
+                                       Assert.assertEquals(defTypes.size(), 0);
+                                       Assert.assertNull(_projectSettings.getDefaultDocumentType(
+                                                       step, "pdf"));
+                                       Assert.assertNull(_projectSettings.getDefaultDocumentType(
+                                                       step, "doc"));
+                                       Assert.assertNull(_projectSettings.getDefaultDocumentType(
+                                                       step, "docx"));
+                                       Assert.assertNull(_projectSettings.getDefaultDocumentType(
+                                                       step, "xml"));
+                                       Assert.assertNull(_projectSettings.getDefaultDocumentType(
+                                                       step, "sldprt"));
+                                       Assert.assertNull(_projectSettings.getDefaultDocumentType(
+                                                       step, "sldasm"));
+                                       Assert.assertNull(_projectSettings.getDefaultDocumentType(
+                                                       step, "part"));
+                                       Assert.assertNull(_projectSettings.getDefaultDocumentType(
+                                                       step, "py"));
+                                       Assert.assertNull(_projectSettings.getDefaultDocumentType(
+                                                       step, "med"));
+                       }
+               }
+
+               // ////// Load workflow customization with empty mappings
+               _projectSettings.getAllSteps().clear(); // Clear config to be able to load it again
+               try {
+                       _projectSettings.configure(ClassLoader.getSystemResource(
+                                       "test/som-without-mappings.xml").getPath());
+               } catch (FileNotFoundException e) {
+                       Assert.fail("Can't find configuration file: ", e);
+               }
+               steps = _projectSettings.getStepsOf(Scenario.class);
+               Assert.assertTrue(steps.size() > 0, "No steps are created.");
+               for (Step step : steps) {
+                       List<String> defTypes = _projectSettings.getDefaultFormats(step);
+                       Assert.assertNotNull(defTypes,
+                                       "getDefaultFormats must always return not null list:");
+                       Assert.assertEquals(defTypes.size(), 0);
+                       Assert.assertNull(_projectSettings.getDefaultDocumentType(step,
+                                       "pdf"));
+                       Assert.assertNull(_projectSettings.getDefaultDocumentType(step,
+                                       "doc"));
+                       Assert.assertNull(_projectSettings.getDefaultDocumentType(step,
+                                       "docx"));
+                       Assert.assertNull(_projectSettings.getDefaultDocumentType(step,
+                                       "xml"));
+                       Assert.assertNull(_projectSettings.getDefaultDocumentType(step,
+                                       "sldprt"));
+                       Assert.assertNull(_projectSettings.getDefaultDocumentType(step,
+                                       "sldasm"));
+                       Assert.assertNull(_projectSettings.getDefaultDocumentType(step,
+                                       "part"));
+                       Assert.assertNull(_projectSettings.getDefaultDocumentType(step,
+                                       "py"));
+                       Assert.assertNull(_projectSettings.getDefaultDocumentType(step,
+                                       "med"));
+               }
+
+               // ////// Load workflow customization from not existing file
+               _projectSettings.getAllSteps().clear(); // Clear config to be able to load it again
+               try {
+                       _projectSettings.configure(ClassLoader.getSystemResource("/")
+                                       .getPath()
+                                       + "test/xxx.xml");
+                       Assert
+                                       .fail("Customization loading must fail for not existing configuration file.");
+               } catch (FileNotFoundException e) {
+                       LOG.debug("Configuration file must not be found.", e);
+               }
+
+               LOG.debug(">>>>> END testLoadDefaultDocTypes()");
+       }
 }
index 364e55f2511865c3f11be1fbb22ebbbac9adcf0e..cb12d2b3e767e901b0906bf25956368af8a803c2 100644 (file)
@@ -11,6 +11,7 @@ package test.splat.service;
 import java.io.FileNotFoundException;
 import java.io.IOException;
 import java.sql.SQLException;
+import java.util.ArrayList;
 import java.util.Date;
 import java.util.List;
 
@@ -20,13 +21,14 @@ import org.splat.dal.bo.som.DocumentType;
 import org.splat.dal.bo.som.Publication;
 import org.splat.dal.bo.som.Scenario;
 import org.splat.dal.bo.som.Study;
+import org.splat.dal.dao.som.ScenarioDAO;
 import org.splat.kernel.InvalidPropertyException;
+import org.splat.kernel.MismatchException;
 import org.splat.kernel.MissedPropertyException;
 import org.splat.kernel.MultiplyDefinedException;
+import org.splat.kernel.NotApplicableException;
 import org.splat.log.AppLogger;
-import org.splat.service.DocumentService;
 import org.splat.service.DocumentTypeService;
-import org.splat.service.ProjectElementService;
 import org.splat.service.PublicationService;
 import org.splat.service.ScenarioService;
 import org.splat.service.StepService;
@@ -65,11 +67,11 @@ public class TestScenarioService extends BaseTest {
        private transient ScenarioService _scenarioService;
 
        /**
-        * The DocumentService. Later injected by Spring.
+        * The Scenario DAO. Later injected by Spring.
         */
        @Autowired
-       @Qualifier("documentService")
-       private transient DocumentService _documentService;
+       @Qualifier("scenarioDAO")
+       private transient ScenarioDAO _scenarioDAO;
 
        /**
         * The PublicationService. Later injected by Spring.
@@ -85,13 +87,6 @@ public class TestScenarioService extends BaseTest {
        @Qualifier("stepService")
        private transient StepService _stepService;
 
-       /**
-        * The ProjectElementService. Later injected by Spring.
-        */
-       @Autowired
-       @Qualifier("projectElementService")
-       private transient ProjectElementService _projectElementService;
-
        /**
         * The ProjectSettingsService. Later injected by Spring.
         */
@@ -109,7 +104,7 @@ public class TestScenarioService extends BaseTest {
        /**
         * Test of getting a scenario content for building siman-salome.conf.<BR>
         * <B>Description :</B> <BR>
-        * <i>Create a scenario try to get an info for it.</i><BR>
+        * <i>Create a scenario and try to get an info for it.</i><BR>
         * <B>Action : </B><BR>
         * <i>1. call the method for an existing scenario id.</i><BR>
         * <i>2. call the method for a not existing scenario id.</i><BR>
@@ -185,42 +180,28 @@ public class TestScenarioService extends BaseTest {
                                                Assert.assertEquals(doc.getTitle(), docName);
                                                Assert.assertNotNull(doc.getFiles(),
                                                                "Document files list must not be null.");
-                                               Assert.assertTrue(doc.getFiles().size() > 1,
-                                                               "Document must have more then 1 attached file.");
-       
+                                               Assert
+                                                               .assertTrue(doc.getFiles().size() > 1,
+                                                                               "Document must have more then 1 attached file.");
+
                                                for (FileDTO file : doc.getFiles()) {
                                                        Assert.assertNotNull(file.getPath(),
                                                                        "File path must not be null.");
                                                        Assert.assertFalse(file.getPath().isEmpty(),
                                                                        "File path must not be empty.");
-                                                       /*                                                      
-                                                   <mappings>
-                                                       <document type="geometry">
-                                                           <import format="brep"/>     <!-- Result Shape                             -->
-                                                       </document>
-                                                       <document type="model">
-                                                           <import format="med"/>      <!-- Result mesh without input parameters     -->
-                                                       </document>
-                                                       <document type="loads">
-                                                           <import format="c3m"/>      <!-- Input data created interactively         -->
-                                                       </document>
-                                                       <document type="results">
-                                                           <import format="med"/>      <!-- Calculation results source file          -->
-                                                       </document>
-                                               </mappings>
+                                                       /*
+                                                        * <mappings> <document type="geometry"> <import format="brep"/> <!-- Result Shape --> </document> <document
+                                                        * type="model"> <import format="med"/> <!-- Result mesh without input parameters --> </document> <document
+                                                        * type="loads"> <import format="c3m"/> <!-- Input data created interactively --> </document> <document
+                                                        * type="results"> <import format="med"/> <!-- Calculation results source file --> </document> </mappings>
                                                         */
                                                        // Check state and processing instruction
                                                        String fileFormat = file.getPath().substring(
                                                                        file.getPath().lastIndexOf('.') + 1);
-/*                                                     if (_projectSettings.doImport(dtype.getName(),
-                                                                       fileFormat)) {
-                                                               Assert.assertTrue(file.isResult(),
-                                                                               "The file must be a result file.");
-                                                       } else {
-                                                               Assert.assertFalse(file.isResult(),
-                                                                               "The file must be a source file.");
-                                                       }
-*/                                                     if ((docIndex % 2) == 0) { // New
+                                                       /*
+                                                        * if (_projectSettings.doImport(dtype.getName(), fileFormat)) { Assert.assertTrue(file.isResult(), "The file
+                                                        * must be a result file."); } else { Assert.assertFalse(file.isResult(), "The file must be a source file."); }
+                                                        */if ((docIndex % 2) == 0) { // New
                                                                Assert.assertEquals(file.getState(), 'Y',
                                                                                "File state must be actual ('Y').");
                                                                if (_projectSettings.doImport(dtype.getName(),
@@ -262,9 +243,74 @@ public class TestScenarioService extends BaseTest {
        }
 
        /**
-        * Create a transient KnowledgeElement for tests.
+        * Test check-in scenario operation to be performed after SALOME session.<BR>
+        * <B>Description :</B> <BR>
+        * <i>Create a scenario and try to check-in it with some simulated SALOME results data.</i><BR>
+        * <B>Action : </B><BR>
+        * <i>1. call the method for an existing scenario id.</i><BR>
+        * <i>2. call the method for a not existing scenario id.</i><BR>
+        * <B>Test data : </B><BR>
+        * <i>no input parameters</i><BR>
+        * <i>no input parameters</i><BR>
+        * 
+        * <B>Outcome results:</B><BR>
+        * <i>
+        * <ul>
+        * <li>New version of existing documents must be created and new documents must be imported for documents with zero id. Correct
+        * relations must be created.<BR>
+        * </li>
+        * <li>Exception is thrown<BR>
+        * </li>
+        * </ul>
+        * </i>
+        * 
+        * @throws InvalidPropertyException
+        *             if an invalid property is used when creating objects
+        * @throws MultiplyDefinedException
+        *             when trying to create an object with already existing id
+        * @throws MissedPropertyException
+        *             if a mandatory property is not defined for an object to be created
+        * @throws IOException
+        *             if scenario creation is failed
+        * @throws SQLException
+        *             if scenario creation is failed
+        * @throws NotApplicableException
+        *             if checkin failed
+        * @throws MismatchException
+        *             if checkin failed
+        */
+       @Test
+       public void testCheckin() throws InvalidPropertyException,
+                       MissedPropertyException, MultiplyDefinedException, IOException,
+                       SQLException, MismatchException, NotApplicableException {
+               LOG.debug(">>>>> BEGIN testCheckin()");
+               _projectSettings.configure(ClassLoader
+                               .getSystemResource("test/som.xml").getPath());
+               long scenarioId = createScenario();
+               Scenario aScen = _scenarioDAO.get(scenarioId);
+               User user = aScen.getAuthor();
+               long userId = user.getIndex(); // TODO: get id of a test user
+               // Call DAO's create method for a good transient knowledge element.
+               List<StepDTO> steps = new ArrayList<StepDTO>();
+
+               _scenarioService.checkin(scenarioId, userId, steps);
+
+               // Call DAO's get method for a not existing id.
+               try {
+                       _scenarioService.checkin(-1, userId, steps);
+                       Assert
+                                       .fail("Check in for scenario with not existing id must be failed.");
+               } catch (Exception e) {
+                       LOG.debug("Expected exception is thrown: "
+                                       + e.getClass().getSimpleName() + ": " + e.getMessage());
+               }
+               LOG.debug(">>>>> END testCheckin()");
+       }
+
+       /**
+        * Create a persistent scenario for tests.
         * 
-        * @return a transient KnowledgeElement
+        * @return a persistent scenario
         * @throws InvalidPropertyException
         *             if an invalid property is used when creating objects
         * @throws MultiplyDefinedException
@@ -284,7 +330,8 @@ public class TestScenarioService extends BaseTest {
 
                // Load workflow customization
                try {
-                       _projectSettings.configure(ClassLoader.getSystemResource("test/som.xml").getPath());
+                       _projectSettings.configure(ClassLoader.getSystemResource(
+                                       "test/som.xml").getPath());
                } catch (FileNotFoundException e) {
                        Assert.fail("Can't find som.xml: ", e);
                }
@@ -327,12 +374,12 @@ public class TestScenarioService extends BaseTest {
                        List<DocumentType> dtypes = _documentTypeService
                                        .selectTypesOf(step);
                        for (DocumentType dtype : dtypes) {
-                               dprop.setName("document" + i++).setType(dtype).setFormat(
-                                               "brep");
+                               dprop.setName("document" + i++).setType(dtype)
+                                               .setFormat("brep");
                                // Create a document published in the scenario
                                // document<i>: document type[0] - first type used on the step
-                               //      <source-file>.brep
-                               //      <attached-file>.med
+                               // <source-file>.brep
+                               // <attached-file>.med
                                Publication pub = _stepService.createDocument(aScStep, dprop);
                                Assert.assertNotNull(pub.getOwner(),
                                                "The publication must be attached to the scenario.");
@@ -346,29 +393,29 @@ public class TestScenarioService extends BaseTest {
                                // Attach a file
                                ht.saveOrUpdate(pub.value());
                                ht.saveOrUpdate(_publicationService.attach(pub, "med"));
-                               
+
                                // Create a document with outdated publication
-                               dprop.setName("document" + i++).setType(dtype).setFormat(
-                               "brep");
+                               dprop.setName("document" + i++).setType(dtype)
+                                               .setFormat("brep");
                                // Create a document published in the scenario
                                // document<i>: document type[0] - first type used on the step
-                               //      <source-file>.brep
-                               //      <attached-file>.med
+                               // <source-file>.brep
+                               // <attached-file>.med
                                pub = _stepService.createDocument(aScStep, dprop);
                                Assert.assertNotNull(pub.getOwner(),
                                                "The publication must be attached to the scenario.");
                                Assert.assertEquals(pub.getOwner().getIndex(), aScenario
                                                .getIndex(),
                                                "The publication was not attached to the scenario.");
-               
+
                                pub.setIsnew('O');
                                aScenario.add(pub);
                                ht.saveOrUpdate(pub);
-               
+
                                // Attach a file
                                ht.saveOrUpdate(pub.value());
                                ht.saveOrUpdate(_publicationService.attach(pub, "med"));
-                                               
+
                        }
                        if (dtypes.size() <= 0) {
                                LOG.debug("No document types are found for scenario step " + i);
index 6697d1742cc2959941d20b350eda3f49cde19805..38f8d2cf1e37c999e30f265102ecf810977a7db6 100644 (file)
@@ -2,36 +2,6 @@
 
 <application>
 
-    <default-doctypes>
-        <step number="1">
-            <mapping extension="pdf"    type="requirements"/>
-            <mapping extension="doc"    type="specification"/>     <!-- Microsoft Word 2003 and earlier -->
-            <mapping extension="docx"   type="specification"/>     <!-- Microsoft Word 2007 and later   -->
-            <mapping extension="xml"    type="specification"/>     <!-- Microsoft Word 2007 Open XML    -->
-        </step>
-        <step number="2">
-            <mapping extension="doc"    type="design"/>
-            <mapping extension="docx"   type="design"/>
-            <mapping extension="xml"    type="design"/>
-        </step>
-        <step number="3">
-            <mapping extension="doc"    type="memorandum"/>
-            <mapping extension="docx"   type="memorandum"/>
-            <mapping extension="xml"    type="memorandum"/>
-            <mapping extension="sldprt" type="geometry"/>          <!-- SolidWorks Part                 -->
-            <mapping extension="sldasm" type="geometry"/>          <!-- SolidWorks Assembly             -->
-            <mapping extension="part"   type="geometry"/>          <!-- GEOM Part                       -->
-            <mapping extension="py"     type="geometry"/>          <!-- GEOM Python script              -->
-        </step>
-        <step number="4">
-            <mapping extension="doc"    type="memorandum"/>
-            <mapping extension="docx"   type="memorandum"/>
-            <mapping extension="xml"    type="memorandum"/>
-            <mapping extension="med"    type="model"/>
-            <mapping extension="py"     type="model"/>             <!-- SMESH Python script             -->
-        </step>
-    </default-doctypes>
-
     <modules>
         <mapping extension="doc"    executable="winword.exe"/>
         <mapping extension="docx"   executable="winword.exe"/>
index a8cb18e48b7b37ed76f7e0d4179f20e2dc52077f..af7c4a66361d7ddeb5cced6337455bf9992fad3d 100644 (file)
             <import format="med"/>      <!-- Calculation results source file          -->
         </document>
     </mappings>
+    
+    <default-doctypes>
+        <step number="1">
+            <mapping extension="pdf"    type="requirements"/>
+            <mapping extension="doc"    type="specification"/>     <!-- Microsoft Word 2003 and earlier -->
+            <mapping extension="docx"   type="specification"/>     <!-- Microsoft Word 2007 and later   -->
+            <mapping extension="xml"    type="specification"/>     <!-- Microsoft Word 2007 Open XML    -->
+        </step>
+        <step number="2">
+            <mapping extension="doc"    type="design"/>
+            <mapping extension="docx"   type="design"/>
+            <mapping extension="xml"    type="design"/>
+        </step>
+        <step number="3">
+            <mapping extension="doc"    type="memorandum"/>
+            <mapping extension="docx"   type="memorandum"/>
+            <mapping extension="xml"    type="memorandum"/>
+            <mapping extension="sldprt" type="geometry"/>          <!-- SolidWorks Part                 -->
+            <mapping extension="sldasm" type="geometry"/>          <!-- SolidWorks Assembly             -->
+            <mapping extension="part"   type="geometry"/>          <!-- GEOM Part                       -->
+            <mapping extension="py"     type="geometry"/>          <!-- GEOM Python script              -->
+        </step>
+        <step number="4">
+            <mapping extension="doc"    type="memorandum"/>
+            <mapping extension="docx"   type="memorandum"/>
+            <mapping extension="xml"    type="memorandum"/>
+            <mapping extension="med"    type="model"/>
+            <mapping extension="py"     type="model"/>             <!-- SMESH Python script             -->
+        </step>
+    </default-doctypes>
+    
 </project-structure>
\ No newline at end of file
index a95b58b4b36ecd93244e3ecfa5d3d6afceba529d..9309647d848b3ac104acdb74b7b0b426056c1a48 100644 (file)
@@ -6,7 +6,6 @@ import java.util.ArrayList;
 import java.util.HashMap;
 import java.util.HashSet;
 import java.util.Iterator;
-import java.util.LinkedHashMap;
 import java.util.List;
 import java.util.Locale;
 import java.util.Map;
@@ -208,10 +207,6 @@ public class ApplicationSettings implements ServletContextAware {
         * Named search filters.
         */
        private transient Map<String, Map<String, Object>> _filter = null;
-       /**
-        * Default document types structured by step.formats.
-        */
-       private transient Map<String, DocumentType> _defdoctype = null;
        /**
         * Available template files.
         */
@@ -862,14 +857,14 @@ public class ApplicationSettings implements ServletContextAware {
                gprop.put("title", "");
                gprop.put("context", new ArrayList<SimulationContext>());
 
-               _defdoctype = new LinkedHashMap<String, DocumentType>();
-               _tempfile = new HashMap<String, String>();
-               _viewermap = new String[0];
-               _convertmap = new HashMap<String, Converter>();
                _filter = new HashMap<String, Map<String, Object>>();
                _filter.put("study", fprop);
                _filter.put("knowledge", gprop);
 
+               _tempfile = new HashMap<String, String>();
+               _viewermap = new String[0];
+               _convertmap = new HashMap<String, Converter>();
+
                // Customization (must be done after above default settings)
                File config = new File(filename);
                if (config.exists()) {
@@ -879,8 +874,6 @@ public class ApplicationSettings implements ServletContextAware {
                                        + config.getAbsolutePath() + "\", using default settings");
                }
                // Settings based on the customization
-               _bars = new HashMap<Integer, ToolBar>(); // May be empty if no module installed
-
                configureToolbars();
        }
 
@@ -888,12 +881,14 @@ public class ApplicationSettings implements ServletContextAware {
         * Configure toolbars for steps.
         */
        private void configureToolbars() {
+               _bars = new HashMap<Integer, ToolBar>(); // May be empty if no module installed
+
                List<ProjectSettingsService.Step> steps = getProjectSettings()
                                .getAllSteps();
                for (Iterator<ProjectSettingsService.Step> i = steps.iterator(); i
                                .hasNext();) {
                        ProjectSettingsService.Step step = i.next();
-                       List<String> formats = getDefaultFormats(step);
+                       List<String> formats = getProjectSettings().getDefaultFormats(step);
                        if (formats.isEmpty()) {
                                continue;
                        }
@@ -912,8 +907,8 @@ public class ApplicationSettings implements ServletContextAware {
                                module.add(command);
                                String[] parsed = command.split("/");
                                String[] name = parsed[parsed.length - 1].split("\\x2E");
-                               DocumentType dtype = MY_APP._defdoctype.get(step.getNumber()
-                                               + "." + format);
+                               DocumentType dtype = getProjectSettings()
+                                               .getDefaultDocumentType(step, format);
                                String docname = "";
                                if (dtype != null) {
                                        docname = dtype.getName();
@@ -1000,11 +995,10 @@ public class ApplicationSettings implements ServletContextAware {
                return MY_APP._convertmap.get(format + type.getName()); // May be null;
        }
 
-       public static DocumentType getDefaultDocumentType(final Step step,
+       public DocumentType getDefaultDocumentType(final Step step,
                        final String format) {
-               String[] table = format.split("\\x2E");
-               return MY_APP._defdoctype.get(step.getNumber() + "."
-                               + table[table.length - 1]); // May be null
+               return getProjectSettings().getDefaultDocumentType(step.getStep(),
+                               format); // May be null
        }
 
        public static String getDownloadURL(final User user) {
@@ -1058,28 +1052,11 @@ public class ApplicationSettings implements ServletContextAware {
        // Private services
        // ==============================================================================================================================
 
-       private List<String> getDefaultFormats(
-                       final ProjectSettingsService.Step step) {
-               Set<String> keys = _defdoctype.keySet();
-               int number = step.getNumber();
-               List<String> result = new ArrayList<String>();
-
-               for (Iterator<String> i = keys.iterator(); i.hasNext();) {
-                       String[] key = i.next().split("\\x2E");
-                       if (Integer.valueOf(key[0]) != number) {
-                               continue;
-                       }
-                       if (key[1].equals("pdf")) {
-                               continue; // PDF is not an authoring format
-                       }
-                       result.add(key[1]); // Formats are unique
-               }
-               return result;
-       }
-
        /**
         * Load customization of workflow from the given XML file.
-        * @param config the XML configuration file
+        * 
+        * @param config
+        *            the XML configuration file
         */
        private void loadCustomization(final File config) {
                try {
@@ -1091,9 +1068,6 @@ public class ApplicationSettings implements ServletContextAware {
                        HashMap<String, Node> children = XDOM.getNamedChildNodes(conf
                                        .getDocumentElement());
 
-                       // Load default document types.
-                       loadDocTypes(children);
-
                        // Modules tag
                        loadModules(children);
 
@@ -1178,44 +1152,6 @@ public class ApplicationSettings implements ServletContextAware {
                }
        }
 
-       /**
-        * Load default document types from XML configuration.
-        * 
-        * @param children
-        *            XML nodes
-        */
-       private void loadDocTypes(final Map<String, Node> children) {
-               Node child = children.get("default-doctypes");
-               NodeList nlist = child.getChildNodes();
-
-               List<DocumentType> listype = getDocumentTypeService().selectAllTypes();
-               Map<String, DocumentType> maptype = new HashMap<String, DocumentType>();
-               for (Iterator<DocumentType> i = listype.iterator(); i.hasNext();) {
-                       DocumentType type = i.next();
-                       maptype.put(type.getName(), type);
-               }
-               for (int i = 0; i < nlist.getLength(); i++) {
-                       child = nlist.item(i);
-                       if (!child.getNodeName().equals("step")) {
-                               continue;
-                       }
-
-                       String nstep = child.getAttributes().getNamedItem("number")
-                                       .getNodeValue();
-                       NodeList map = child.getChildNodes();
-                       for (int j = 0; j < map.getLength(); j++) {
-                               child = map.item(j);
-                               if (!child.getNodeName().equals("mapping")) {
-                                       continue;
-                               }
-                               NamedNodeMap natr = child.getAttributes();
-                               String dext = natr.getNamedItem("extension").getNodeValue();
-                               String type = natr.getNamedItem("type").getNodeValue();
-                               _defdoctype.put(nstep + "." + dext, maptype.get(type));
-                       }
-               }
-       }
-
        /**
         * Get the documentTypeService.
         * 
index beabeaaf6baea04979d66df29598ed0487903d54..c86a7d54783b978081ab3429762353661bc2eb33 100644 (file)
@@ -4,27 +4,28 @@ import java.io.File;
 import java.io.FileNotFoundException;
 import java.text.ParseException;
 import java.text.SimpleDateFormat;
+import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.Iterator;
 import java.util.List;
 import java.util.ResourceBundle;
-import java.util.Vector;
 
 import org.splat.dal.bo.kernel.User;
-import org.splat.manox.Reader;
-import org.splat.manox.Toolbox;
 import org.splat.dal.bo.som.Document;
+import org.splat.dal.bo.som.DocumentType;
 import org.splat.dal.bo.som.ProgressState;
+import org.splat.dal.bo.som.Publication;
+import org.splat.manox.Reader;
+import org.splat.manox.Toolbox;
 import org.splat.service.DocumentService;
 import org.splat.service.DocumentTypeService;
 import org.splat.service.PublicationService;
 import org.splat.service.StepService;
 import org.splat.service.technical.ProjectSettingsService;
 import org.splat.service.technical.RepositoryService;
-import org.splat.dal.bo.som.Publication;
-import org.splat.dal.bo.som.DocumentType;
 import org.splat.som.Revision;
 import org.splat.som.Step;
+import org.splat.wapp.Constants;
 
 /**
  * Action for adding a document into a study step.
@@ -36,15 +37,24 @@ public class ImportDocumentAction extends UploadBaseNextAction {
         */
        private static final long serialVersionUID = 2587822564883588556L;
 
-       private List<DocumentType> doctypes = null;
-       private long doctype = 0;
-       private String docref = null; // Reference extracted from the imported file, if exist
-       private String docver = ""; // Version number extracted from the imported file, if exist
-       private String date = ""; // Date extracted from the imported file, if exist
+       private transient List<DocumentType> _documentTypes = null;
+       private long _documentType = 0;
+       /**
+        * Reference extracted from the imported file, if exist.
+        */
+       private String _reference = null;
+       /**
+        * Version number extracted from the imported file, if exist.
+        */
+       private String _version = "";
+       /**
+        * Date extracted from the imported file, if exist.
+        */
+       private String _documentDate = "";
        /**
         * Injected project settings service.
         */
-       private ProjectSettingsService _projectSettingsService;
+       private ProjectSettingsService _projectSettings;
        /**
         * Injected publication service.
         */
@@ -64,35 +74,30 @@ public class ImportDocumentAction extends UploadBaseNextAction {
        /**
         * Injected repository service.
         */
-       private RepositoryService _repositoryService;   
+       private RepositoryService _repositoryService;
        /**
-        * Value of the menu property. 
-        * It can be: none, create, open, study, knowledge, sysadmin, help.
+        * Value of the menu property. It can be: none, create, open, study, knowledge, sysadmin, help.
         */
        private String _menuProperty;
-       
+
        /**
-        * Value of the title bar property. 
-        * It can be: study, knowledge.
+        * 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.
+        * 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.
+        * 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.
-        * It is necessary for correct building the title bar.
+        * 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. It is necessary for correct building the title bar.
         */
        private String _editDisabledProperty = "false";
 
@@ -102,21 +107,23 @@ public class ImportDocumentAction extends UploadBaseNextAction {
 
        /**
         * Initialize the operation.
+        * 
         * @return SUCCESS in success, otherwise - ERROR
         */
        public String doInitialize() {
-               
-               setMenuProperty("study");
-               setTitleProperty("study");
+
+               setMenuProperty(Constants.STUDY_MENU);
+               setTitleProperty(Constants.STUDY_MENU);
                setEditDisabledProperty("true");
                if ("true".equals(getWriteAccess())) {
-                       setToolProperty("study");
+                       setToolProperty(Constants.STUDY_MENU);
                } else {
-                       setToolProperty("none");
+                       setToolProperty(Constants.NONE);
                }
-               setLeftMenuProperty("study");
-        initializationFullScreenContext(_menuProperty, _titleProperty, _editDisabledProperty, _toolProperty, _leftMenuProperty);
-             
+               setLeftMenuProperty(Constants.STUDY_MENU);
+               initializationFullScreenContext(_menuProperty, _titleProperty,
+                               _editDisabledProperty, _toolProperty, _leftMenuProperty);
+
                User user = getConnectedUser();
                File updir = getRepositoryService().getDownloadDirectory(user);
                File upfile = new File(updir.getPath() + "/" + filename);
@@ -125,125 +132,172 @@ public class ImportDocumentAction extends UploadBaseNextAction {
 
                mystudy = getOpenStudy();
                Step step = mystudy.getSelectedStep();
-               doctypes = getStepService().getValidDocumentTypes(step);
+               _documentTypes = getStepService().getValidDocumentTypes(step);
                deftype = getApplicationSettings().getDefaultDocumentType(step, filext);
-               defuses = new Vector<Document>();
+               defuses = new ArrayList<Document>();
                state = ProgressState.inWORK;
 
+               String res = ERROR;
+               if (extractProperties(upfile, filext)) {
+                       if (docname == null) {
+                               docname = table[0];
+                               for (int i = 1; i < table.length - 1; i++) {
+                                       docname = docname + "." + table[i];
+                               }
+                       }
+                       if (deftype != null) {
+                               setupDefaultUses(deftype);
+                       }
+
+                       DocumentType[] types = _documentTypes
+                                       .toArray(new DocumentType[_documentTypes.size()]);
+                       DocumentTypeComparator compare = new DocumentTypeComparator();
+                       Arrays.sort(types, compare);
+                       _documentTypes = Arrays.asList(types);
+                       res = SUCCESS;
+               }
+               return res;
+       }
+
+       /**
+        * Extract properties from the uploaded file.
+        * 
+        * @param upfile
+        *            the file to parse
+        * @param filext
+        *            the file extension
+        * @return true if succeeded, false if error
+        */
+       private boolean extractProperties(final File upfile, final String filext) {
+               boolean isOk = true;
                Reader tool = Toolbox.getReader(upfile);
-               if (tool != null) {
+               if (tool == null) {
+                       if ("pdf".equals(filext)) {
+                               state = ProgressState.EXTERN; // TODO: Should external extensions be configurable ?
+                       }
+               } else {
                        String fileref = tool.extractProperty("reference");
                        String filever = tool.extractProperty("version"); // Property kept even if the file is not referenced
                        String filetype = tool.extractProperty("type"); // Property kept even if the file is not referenced
-                       for (Iterator<DocumentType> i = doctypes.iterator(); i.hasNext();) {
+                       for (Iterator<DocumentType> i = _documentTypes.iterator(); i
+                                       .hasNext();) {
                                DocumentType type = i.next();
-                               if (!type.getName().equals(filetype))
-                                       continue;
-                               deftype = type;
-                               doctype = type.getIndex(); // Disables the document type field
-                               break;
+                               if (type.getName().equals(filetype)) {
+                                       deftype = type;
+                                       _documentType = type.getIndex(); // Disables the document type field
+                                       break;
+                               }
                        }
                        if (fileref != null) {
-                               Document slot = getDocumentService().selectDocument(fileref,
-                                               new Revision().toString());
-                               if (slot == null) {
-                                       setErrorCode("message.error.reference.undefined");
-                                       
-                                       setToolProperty("none");
-                                       initializationFullScreenContext(_menuProperty, _titleProperty, _editDisabledProperty, _toolProperty, _leftMenuProperty);
-                                       
-                                       return ERROR;
-                               } else {
-                                       if (!slot.isUndefined()) {
-                                               setErrorCode("message.error.reference.duplicate");
-                                               
-                                               setToolProperty("none");
-                                               initializationFullScreenContext(_menuProperty, _titleProperty, _editDisabledProperty, _toolProperty, _leftMenuProperty);
-                                               
-                                               return ERROR;
-                                       }
-                                       docref = fileref; // Disables document name and state fields
-                                       deftype = slot.getType(); // Just in case
-                                       doctype = deftype.getIndex(); // Disables the document type field
-                               }
+                               isOk = findTypeByDocRef(fileref);
                        }
-                       if (filever != null)
-                               try {
-                                       Revision.Format get = new Revision.Format(
-                                                       getProjectSettings().getRevisionPattern());
-                                       Revision version = get.parse(filever);
-                                       if (version.isNull())
-                                               throw new ParseException(filever, filever.length() - 1);
-                                       if (!version.isMinor())
-                                               state = ProgressState.inCHECK;
-                                       docver = version.toString();
-                               } catch (ParseException e) {
-                                       setErrorCode("message.error.format.version");
-                                       
-                                       setToolProperty("none");
-                                       initializationFullScreenContext(_menuProperty, _titleProperty, _editDisabledProperty, _toolProperty, _leftMenuProperty);
-                                       
-                                       return ERROR;
+                       if (isOk) {
+                               if (filever != null) {
+                                       try {
+                                               Revision.Format get = new Revision.Format(
+                                                               getProjectSettings().getRevisionPattern());
+                                               Revision version = get.parse(filever);
+                                               if (version.isNull()) {
+                                                       throw new ParseException(filever,
+                                                                       filever.length() - 1);
+                                               }
+                                               if (!version.isMinor()) {
+                                                       state = ProgressState.inCHECK;
+                                               }
+                                               _version = version.toString();
+                                       } catch (ParseException e) {
+                                               setError("message.error.format.version");
+                                               isOk = false;
+                                       }
                                }
-                       docname = tool.extractProperty("title"); // Property kept even if the file is not referenced
-                       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("message.error.format.date");
-                                       
-                                       setToolProperty("none");
-                                       initializationFullScreenContext(_menuProperty, _titleProperty, _editDisabledProperty, _toolProperty, _leftMenuProperty);
-                                       
-                                       return ERROR;
+                               if (isOk) {
+                                       docname = tool.extractProperty("title"); // Property kept even if the file is not referenced
+                                       _documentDate = tool.extractProperty("date");
+                                       if (_documentDate == null) {
+                                               _documentDate = "";
+                                       } else {
+                                               ResourceBundle locale = ResourceBundle.getBundle("som",
+                                                               getApplicationSettings().getCurrentLocale());
+                                               SimpleDateFormat check = new SimpleDateFormat(locale
+                                                               .getString("date.format"));
+                                               try {
+                                                       check.parse(_documentDate);
+                                               } catch (ParseException e) {
+                                                       setError("message.error.format.date");
+                                                       isOk = false;
+                                               }
+                                       }
                                }
-                       } else
-                               date = "";
-               } else if (filext.equals("pdf"))
-                       state = ProgressState.EXTERN; // TODO: Should external extensions be configurable ?
-               if (docname == null) {
-                       docname = table[0];
-                       for (int i = 1; i < table.length - 1; i++)
-                               docname = docname + "." + table[i];
+                       }
+               }
+               return isOk;
+       }
+
+       /**
+        * Find document type by document reference.
+        * 
+        * @param fileref
+        *            the document reference
+        * @return true if succeeded, false if error
+        */
+       private boolean findTypeByDocRef(final String fileref) {
+               boolean isOk = true;
+               Document slot = getDocumentService().selectDocument(fileref,
+                               new Revision().toString());
+               if (slot == null) {
+                       setError("message.error.reference.undefined");
+                       isOk = false;
+               } else {
+                       if (slot.isUndefined()) {
+                               _reference = fileref; // Disables document name and state fields
+                               deftype = slot.getType(); // Just in case
+                               _documentType = deftype.getIndex(); // Disables the document type field
+                       } else {
+                               setError("message.error.reference.duplicate");
+                               isOk = false;
+                       }
                }
-               if (deftype != null)
-                       setupDefaultUses(deftype);
+               return isOk;
+       }
 
-               DocumentType[] types = doctypes.toArray(new DocumentType[doctypes
-                               .size()]);
-               DocumentTypeComparator compare = new DocumentTypeComparator();
-               Arrays.sort(types, compare);
-               doctypes = Arrays.asList(types);
+       /**
+        * Set error message and menus.
+        * 
+        * @param errorCode
+        *            error message key
+        */
+       private void setError(final String errorCode) {
+               setErrorCode(errorCode);
 
-               return SUCCESS;
+               setToolProperty(Constants.NONE);
+               initializationFullScreenContext(_menuProperty, _titleProperty,
+                               _editDisabledProperty, _toolProperty, _leftMenuProperty);
        }
 
        /**
         * Perform import of a document.
+        * 
         * @return SUCCESS if ok, "cancel" - if canceled, ERROR - if error
         */
        public String doImport() {
-               // -------------------------
-               
-               setMenuProperty("study");
-               setTitleProperty("study");
+
+               setMenuProperty(Constants.STUDY_MENU);
+               setTitleProperty(Constants.STUDY_MENU);
                setEditDisabledProperty("true");
-        initializationScreenContext(_menuProperty, _titleProperty, _editDisabledProperty);
-           
-               if (action == ToDo.cancel)
+               initializationScreenContext(_menuProperty, _titleProperty,
+                               _editDisabledProperty);
+
+               if (action == ToDo.cancel) {
                        return "cancel";
-               if (doctype == 0) {
+               }
+               if (_documentType == 0) {
                        setErrorCode("message.error.import.type");
-                       
-                       setToolProperty("none");
-                       setLeftMenuProperty("study");
-                       initializationFullScreenContext(_menuProperty, _titleProperty, _editDisabledProperty, _toolProperty, _leftMenuProperty);
-                       
+
+                       setToolProperty(Constants.NONE);
+                       setLeftMenuProperty(Constants.STUDY_MENU);
+                       initializationFullScreenContext(_menuProperty, _titleProperty,
+                                       _editDisabledProperty, _toolProperty, _leftMenuProperty);
+
                        return ERROR;
                }
                try {
@@ -251,7 +305,8 @@ public class ImportDocumentAction extends UploadBaseNextAction {
                        mystudy = getOpenStudy();
                        User user = getConnectedUser();
                        Step step = mystudy.getSelectedStep();
-                       DocumentType type = getDocumentTypeService().selectType((int)doctype);
+                       DocumentType type = getDocumentTypeService().selectType(
+                                       (int) _documentType);
                        File updir = getRepositoryService().getDownloadDirectory(user);
                        File upfile = new File(updir.getPath() + "/" + filename);
                        String[] table = filename.split("\\x2E");
@@ -260,15 +315,17 @@ public class ImportDocumentAction extends UploadBaseNextAction {
                        Document.Properties dprop = new Document.Properties();
                        Publication addoc;
 
-                       if (docref.length() == 0) { // Importation of a foreign document
-                       // TODO: Extract property of supported documents (DOCX, ODT...)
-                               addoc = getStepService().createDocument(step, dprop.setName(docname)
-                                               .setType(type).setFormat(table[table.length - 1])
-                                               .setAuthor(user));
+                       if (_reference.length() == 0) { // Importation of a foreign document
+                               // TODO: Extract property of supported documents (DOCX, ODT...)
+                               addoc = getStepService().createDocument(
+                                               step,
+                                               dprop.setName(docname).setType(type).setFormat(
+                                                               table[table.length - 1]).setAuthor(user));
                                updir = addoc.getSourceFile().asFile();
-                               if (LOG.isInfoEnabled())
+                               if (LOG.isInfoEnabled()) {
                                        LOG.info("Moving \"" + upfile.getName() + "\" to \""
                                                        + updir.getPath() + "\".");
+                               }
                                upfile.renameTo(updir);
                                try {
                                        getPublicationService().saveAs(addoc, state); // May throw FileNotFound if rename was not done
@@ -279,35 +336,38 @@ public class ImportDocumentAction extends UploadBaseNextAction {
                                        getPublicationService().saveAs(addoc, state); // Forget it if throw again FileNotFound
                                }
                        } else { // Importation of a previously created template-based document
-                               if (date.length() > 0) {
+                               if (_documentDate.length() > 0) {
                                        ResourceBundle locale = ResourceBundle.getBundle("som",
                                                        getApplicationSettings().getCurrentLocale());
-                                       SimpleDateFormat get = new SimpleDateFormat(
-                                                       locale.getString("date.format"));
-                                       dprop.setDate(get.parse(date));
+                                       SimpleDateFormat get = new SimpleDateFormat(locale
+                                                       .getString("date.format"));
+                                       dprop.setDate(get.parse(_documentDate));
                                }
-                               addoc = getStepService().assignDocument(step, dprop.setReference(docref).setName(
-                                               docname));
+                               addoc = getStepService().assignDocument(step,
+                                               dprop.setReference(_reference).setName(docname));
                                updir = addoc.getSourceFile().asFile();
-                               if (LOG.isInfoEnabled())
+                               if (LOG.isInfoEnabled()) {
                                        LOG.info("Moving \"" + upfile.getName() + "\" to \""
                                                        + updir.getPath() + "\".");
+                               }
                                upfile.renameTo(updir);
                                try {
-                                       if (docver.length() > 0)
+                                       if (_version.length() > 0) {
                                                getPublicationService().saveAs(addoc,
-                                                               new Revision(docver));
-                                       else
+                                                               new Revision(_version));
+                                       } else {
                                                getPublicationService().saveAs(addoc, state);
+                                       }
                                } catch (FileNotFoundException saverror) {
                                        Thread.sleep(1000);
                                        LOG.info("Waiting for the file.");
                                        upfile.renameTo(updir);
-                                       if (docver.length() > 0)
+                                       if (_version.length() > 0) {
                                                getPublicationService().saveAs(addoc,
-                                                               new Revision(docver));
-                                       else
+                                                               new Revision(_version));
+                                       } else {
                                                getPublicationService().saveAs(addoc, state);
+                                       }
                                }
                                mystudy.updateSimulationContexts(); // In case of simulation contexts extracted from the imported document
                        }
@@ -335,11 +395,12 @@ public class ImportDocumentAction extends UploadBaseNextAction {
                        LOG.error("Reason:", error);
                        setErrorCode("message.error.internal");
                }
-               
-               setToolProperty("none");
-               setLeftMenuProperty("study");
-               initializationFullScreenContext(_menuProperty, _titleProperty, _editDisabledProperty, _toolProperty, _leftMenuProperty);
-               
+
+               setToolProperty(Constants.NONE);
+               setLeftMenuProperty(Constants.STUDY_MENU);
+               initializationFullScreenContext(_menuProperty, _titleProperty,
+                               _editDisabledProperty, _toolProperty, _leftMenuProperty);
+
                return ERROR;
        }
 
@@ -347,72 +408,112 @@ public class ImportDocumentAction extends UploadBaseNextAction {
        // Getters and setters
        // ==============================================================================================================================
 
+       /**
+        * Date extracted from the imported file, if exist.
+        * 
+        * @return the file date
+        */
        public String getDocumentDate() {
-               // --------------------------------
-               return date;
+               return _documentDate;
        }
 
        public List<DocumentType> getDocumentTypes() {
-               // ---------------------------------------------
-               return doctypes;
+               return _documentTypes;
        }
 
+       /**
+        * Get document type id.
+        * 
+        * @return document type id
+        */
        public long getDocumentType() {
-               // -----------------------------
-               return doctype;
+               return _documentType;
        }
 
+       /**
+        * Get reference extracted from the imported file, if exist.
+        * 
+        * @return the document reference
+        */
        public String getReference() {
-               // -----------------------------
-               return docref;
+               return _reference;
        }
 
+       /**
+        * Get version number extracted from the imported file, if exist.
+        * 
+        * @return the document version
+        */
        public String getVersion() {
-               // ---------------------------
-               return docver;
+               return _version;
        }
 
+       /**
+        * Set date extracted from the imported file.
+        * 
+        * @param date
+        *            the date to set
+        */
        public void setDocumentDate(final String date) {
-               // -----------------------------------------
-               this.date = date;
+               this._documentDate = date;
        }
 
+       /**
+        * Set document name entered by the user if enabled.
+        * 
+        * @param name
+        *            the document name
+        */
        public void setDocumentName(final String name) {
-               // -----------------------------------------
                this.docname = name; // Name entered by the user if enabled
        }
 
        public void setDocumentTitle(final String name) { // Called even if DocumentName is enabled
-       // -----------------------------------------
-               if (this.docname == null)
+               if (this.docname == null) {
                        this.docname = name;
+               }
        }
 
+       /**
+        * Set document type id.
+        * 
+        * @param value
+        *            the id as string
+        */
        public void setDocumentType(final String value) {
-               // ------------------------------------------
-               this.doctype = Integer.valueOf(value);
+               this._documentType = Integer.valueOf(value);
        }
 
        public void setDefaultDocumentState(final String state) { // Called even if DocumentState is enabled
-       // --------------------------------------------------
-               if (this.state == null)
+               if (this.state == null) {
                        this.state = ProgressState.valueOf(state);
+               }
        }
 
        public void setDefaultDocumentType(final String value) { // Called even if DocumentType is enabled
-       // --------------------------------------------------
-               if (this.doctype == 0)
-                       this.doctype = Integer.valueOf(value);
+               if (this._documentType == 0) {
+                       this._documentType = Integer.valueOf(value);
+               }
        }
 
+       /**
+        * Set document reference extracted from the imported file, if exist.
+        * 
+        * @param value
+        *            the reference
+        */
        public void setReference(final String value) {
-               // ---------------------------------------
-               this.docref = value;
+               this._reference = value;
        }
 
+       /**
+        * Set version number extracted from the imported file, if exist.
+        * 
+        * @param value
+        *            the version
+        */
        public void setVersion(final String value) {
-               // -------------------------------------
-               this.docver = value;
+               this._version = value;
        }
 
        /**
@@ -421,7 +522,7 @@ public class ImportDocumentAction extends UploadBaseNextAction {
         * @return Project settings service
         */
        private ProjectSettingsService getProjectSettings() {
-               return _projectSettingsService;
+               return _projectSettings;
        }
 
        /**
@@ -430,8 +531,9 @@ public class ImportDocumentAction extends UploadBaseNextAction {
         * @param projectSettingsService
         *            project settings service
         */
-       public void setProjectSettings(final ProjectSettingsService projectSettingsService) {
-               _projectSettingsService = projectSettingsService;
+       public void setProjectSettings(
+                       final ProjectSettingsService projectSettingsService) {
+               _projectSettings = projectSettingsService;
        }
 
        /**
@@ -449,12 +551,14 @@ public class ImportDocumentAction extends UploadBaseNextAction {
         * @param publicationService
         *            the publicationService to set
         */
-       public void setPublicationService(final PublicationService publicationService) {
+       public void setPublicationService(
+                       final PublicationService publicationService) {
                _publicationService = publicationService;
        }
 
        /**
         * Get the stepService.
+        * 
         * @return the stepService
         */
        public StepService getStepService() {
@@ -463,7 +567,9 @@ public class ImportDocumentAction extends UploadBaseNextAction {
 
        /**
         * Set the stepService.
-        * @param stepService the stepService to set
+        * 
+        * @param stepService
+        *            the stepService to set
         */
        public void setStepService(final StepService stepService) {
                _stepService = stepService;
@@ -471,6 +577,7 @@ public class ImportDocumentAction extends UploadBaseNextAction {
 
        /**
         * Get the documentService.
+        * 
         * @return the documentService
         */
        public DocumentService getDocumentService() {
@@ -479,7 +586,9 @@ public class ImportDocumentAction extends UploadBaseNextAction {
 
        /**
         * Set the documentService.
-        * @param documentService the documentService to set
+        * 
+        * @param documentService
+        *            the documentService to set
         */
        public void setDocumentService(final DocumentService documentService) {
                _documentService = documentService;
@@ -487,6 +596,7 @@ public class ImportDocumentAction extends UploadBaseNextAction {
 
        /**
         * Get the repositoryService.
+        * 
         * @return the repositoryService
         */
        public RepositoryService getRepositoryService() {
@@ -495,7 +605,9 @@ public class ImportDocumentAction extends UploadBaseNextAction {
 
        /**
         * Set the repositoryService.
-        * @param repositoryService the repositoryService to set
+        * 
+        * @param repositoryService
+        *            the repositoryService to set
         */
        public void setRepositoryService(final RepositoryService repositoryService) {
                _repositoryService = repositoryService;
@@ -503,6 +615,7 @@ public class ImportDocumentAction extends UploadBaseNextAction {
 
        /**
         * Get the documentTypeService.
+        * 
         * @return the documentTypeService
         */
        public DocumentTypeService getDocumentTypeService() {
@@ -511,14 +624,18 @@ public class ImportDocumentAction extends UploadBaseNextAction {
 
        /**
         * Set the documentTypeService.
-        * @param documentTypeService the documentTypeService to set
+        * 
+        * @param documentTypeService
+        *            the documentTypeService to set
         */
-       public void setDocumentTypeService(final DocumentTypeService documentTypeService) {
+       public void setDocumentTypeService(
+                       final DocumentTypeService documentTypeService) {
                _documentTypeService = documentTypeService;
        }
-       
+
        /**
         * Get the menuProperty.
+        * 
         * @return the menuProperty
         */
        public String getMenuProperty() {
@@ -527,14 +644,17 @@ public class ImportDocumentAction extends UploadBaseNextAction {
 
        /**
         * Set the menuProperty.
-        * @param menuProperty the menuProperty to set
+        * 
+        * @param menuProperty
+        *            the menuProperty to set
         */
        public void setMenuProperty(final String menuProperty) {
                this._menuProperty = menuProperty;
        }
-       
+
        /**
         * Get the _titleProperty.
+        * 
         * @return the _titleProperty
         */
        public String getTitleProperty() {
@@ -542,8 +662,10 @@ public class ImportDocumentAction extends UploadBaseNextAction {
        }
 
        /**
-        * Set the _titleProperty.
-        * @param _titleProperty the titleProperty to set
+        * Set the titleProperty.
+        * 
+        * @param titleProperty
+        *            the titleProperty to set
         */
        public void setTitleProperty(final String titleProperty) {
                _titleProperty = titleProperty;
@@ -551,6 +673,7 @@ public class ImportDocumentAction extends UploadBaseNextAction {
 
        /**
         * Get the editDisabledProperty.
+        * 
         * @return the editDisabledProperty
         */
        public final String getEditDisabledProperty() {
@@ -559,7 +682,9 @@ public class ImportDocumentAction extends UploadBaseNextAction {
 
        /**
         * Set the editDisabledProperty.
-        * @param editDisabledProperty the editDisabledProperty to set
+        * 
+        * @param editDisabledProperty
+        *            the editDisabledProperty to set
         */
        public final void setEditDisabledProperty(final String editDisabledProperty) {
                _editDisabledProperty = editDisabledProperty;
@@ -567,6 +692,7 @@ public class ImportDocumentAction extends UploadBaseNextAction {
 
        /**
         * Get the toolProperty.
+        * 
         * @return the toolProperty
         */
        public String getToolProperty() {
@@ -575,14 +701,17 @@ public class ImportDocumentAction extends UploadBaseNextAction {
 
        /**
         * Set the toolProperty.
-        * @param toolProperty the toolProperty to set
+        * 
+        * @param toolProperty
+        *            the toolProperty to set
         */
        public void setToolProperty(final String toolProperty) {
                _toolProperty = toolProperty;
        }
-       
+
        /**
         * Get the leftMenuProperty.
+        * 
         * @return the leftMenuProperty
         */
        public String getLeftMenuProperty() {
@@ -591,7 +720,9 @@ public class ImportDocumentAction extends UploadBaseNextAction {
 
        /**
         * Set the leftMenuProperty.
-        * @param leftMenuProperty the leftMenuProperty to set
+        * 
+        * @param leftMenuProperty
+        *            the leftMenuProperty to set
         */
        public void setLeftMenuProperty(final String leftMenuProperty) {
                _leftMenuProperty = leftMenuProperty;
index b9a6e6f6e4808366be6ae42726d8f8c135157364..4b9432bb8cb311bddbb00a3d3e873f3a85383e42 100644 (file)
@@ -4,161 +4,267 @@ import java.io.File;
 
 import org.splat.kernel.Do;
 import org.splat.service.technical.RepositoryService;
-import org.splat.dal.dao.som.Database;
-
+import org.splat.wapp.Constants;
 
+/**
+ * Action for uploading a file into the user's download directory.
+ */
 public class UploadAction extends Action {
 
-       private File    upload         = null;
-       private String  uploadMimeType = null;
-    private String  uploadFileName = null;
+       /**
+        * Serialization version id.
+        */
+       private static final long serialVersionUID = 6003880772275115923L;
+
+       /**
+        * Uploaded file.
+        */
+       private transient File _upload = null;
+       /**
+        * Mime type of the uploaded file.
+        */
+       private transient String _uploadMimeType = null;
+       /**
+        * Uploaded file name.
+        */
+       private transient String _uploadFileName = null;
 
-    private ToDo    action;                  // Action to do
-    private String  next           = null;   // Action to which the uploaded file is passed
-       private String  index          = null;   // Depending on the next action, document index to which the action applies
+       /**
+        * Action to do.
+        */
+       private transient ToDo _action;
+       /**
+        * Action to which the uploaded file is passed.
+        */
+       private String _nextAction = null;
+       /**
+        * Depending on the next action, document index to which the action applies.
+        */
+       private String _index = null;
        /**
         * Injected repository service.
         */
        private RepositoryService _repositoryService;
-       
+
        /**
-        * Value of the menu property. 
-        * It can be: none, create, open, study, knowledge, sysadmin, help.
+        * Value of the menu property. It can be: none, create, open, study, knowledge, sysadmin, help.
         */
        private String _menuProperty;
-       
+
        /**
-        * Value of the title bar property. 
-        * It can be: study, knowledge.
+        * 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.
+        * 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.
+        * 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.
-        * It is necessary for correct building the title bar.
+        * 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. It is necessary for correct building the title bar.
         */
        private String _editDisabledProperty = "false";
 
-       private static final long serialVersionUID = 6003880772275115923L;
+       /**
+        * Action modes enumeration.
+        */
+       private enum ToDo {
+               /**
+                * Cancel the operation.
+                */
+               cancel,
+               /**
+                * Perform uploading.
+                */
+               upload
+       };
+
+       // ==============================================================================================================================
+       // Action methods
+       // ==============================================================================================================================
+
+       /**
+        * Prepare form for the upload action.
+        * 
+        * @return SUCCESS
+        */
+       public String doInitialize() {
+               setMenuProperty(Constants.STUDY_MENU);
+               setToolProperty(Constants.NONE);
+               setLeftMenuProperty("open");
+               initializationFullScreenContext(_menuProperty, _toolProperty,
+                               _leftMenuProperty);
+
+               return SUCCESS;
+       }
+
+       /**
+        * Store uploaded file into the user's download directory.
+        * 
+        * @return next action if ok, "cancel" if the operation is cancelled by user, "outofmemory" if there is no enough memory to upload the
+        *         file or ERROR otherwise
+        */
+       public String doUpload() {
+               setMenuProperty(Constants.STUDY_MENU);
+               setTitleProperty(Constants.STUDY_MENU);
+               setEditDisabledProperty("true");
+               initializationScreenContext(_menuProperty, _titleProperty,
+                               _editDisabledProperty);
+
+               String res;
+               if (_action == ToDo.cancel) {
+                       res = "cancel";
+               } else {
+                       try {
+                               File udir = getRepositoryService().getDownloadDirectory(
+                                               getConnectedUser());
+                               String path = udir.getPath() + "/" + _uploadFileName;
+                               File file = new File(path);
+
+                               if (!udir.exists()) {
+                                       udir.mkdir();
+                               }
+                               if (file.exists()) {
+                                       file.delete();
+                               }
+                               Do.copy(_upload, file);
+                               LOG.info("Uploading \"" + _uploadFileName + "\" "
+                                               + _uploadMimeType + " file.");
+                               /*
+                                * if (next == null || next.isEmpty()) { next = "import"; }
+                                */
+
+                               res = _nextAction;
+                       } catch (OutOfMemoryError error) {
+
+                               setMenuProperty(Constants.NONE);
+                               setTitleProperty(Constants.STUDY_MENU);
+                               setEditDisabledProperty("true");
+                               setToolProperty(Constants.NONE);
+                               setLeftMenuProperty(Constants.STUDY_MENU);
+                               initializationFullScreenContext(_menuProperty, _titleProperty,
+                                               _editDisabledProperty, _toolProperty, _leftMenuProperty);
+
+                               setErrorCode("message.error.outofmemory");
+
+                               res = "outofmemory";
+                       } catch (Exception error) {
+                               LOG.error("Reason: ", error);
+                               res = ERROR;
+                       }
+               }
+               return res;
+       }
+
+       // ==============================================================================================================================
+       // Getters and setters
+       // ==============================================================================================================================
 
-    private enum ToDo { cancel, upload };
-
-//  ==============================================================================================================================
-//  Action methods
-//  ==============================================================================================================================
-
-    public String doInitialize () {
-//  -----------------------------
-       setMenuProperty("study");
-       setToolProperty("none");
-       setLeftMenuProperty("open");
-               initializationFullScreenContext(_menuProperty, _toolProperty, _leftMenuProperty);
-               
-      return SUCCESS;
-    }
-
-    public String doUpload () {
-//  -------------------------
-      setMenuProperty("study");
-      setTitleProperty("study");
-      setEditDisabledProperty("true");
-      initializationScreenContext(_menuProperty, _titleProperty, _editDisabledProperty);
-      
-      if (action == ToDo.cancel) return "cancel";
-      try {
-       File    udir = getRepositoryService().getDownloadDirectory(getConnectedUser());
-       String  path = udir.getPath() + "/" + uploadFileName;
-       File    file = new File(path);
-
-       if (!udir.exists()) udir.mkdir();
-       if (file.exists())  file.delete();
-       Do.copy(upload, file);
-        LOG.info("Uploading \"" + uploadFileName + "\" " + uploadMimeType + " file.");
-        /*if (next == null || next.isEmpty()) {
-               next = "import";
-        }*/
-        
-        return next;
-      }
-      catch (OutOfMemoryError error) {
-         
-       setMenuProperty("none");
-       setTitleProperty("study");
-       setEditDisabledProperty("true");
-       setToolProperty("none");
-       setLeftMenuProperty("study");
-        initializationFullScreenContext(_menuProperty, _titleProperty, _editDisabledProperty, _toolProperty, _leftMenuProperty);
-        
-        setErrorCode("message.error.outofmemory");
-               
-       return "outofmemory";
-      }
-      catch (Exception error) {
-       LOG.error("Reason: ", error);
-        return ERROR;
-      }
-    }
-//  ==============================================================================================================================
-//  Getters and setters
-//  ==============================================================================================================================
-
-    public String getIndex () {
-//  -------------------------
-      return index;
-    }
-    public String getFileName () {
-//  ----------------------------
-      return uploadFileName;
-    }
-    public String getNextAction () {
-//  ------------------------------
-      return next;
-    }
-
-    public void setCancel (final boolean back) {
-//  ------------------------------------
-      this.action = ToDo.cancel;
-    }
-    public void setDoIt (final boolean upload) {
-//  --------------------------------
-      this.action = ToDo.upload;
-    }
-    public void setIndex (final String index) {
-//  -----------------------------------
-      this.index = index;
-    }
-    public void setNextAction (final String next) {
-//  ---------------------------------------
-      this.next = next;
-    }
-    public void setUpload (final File upload) {
-//  -----------------------------------
-      this.upload = upload;
-    }
-    public void setUploadFileName (final String name) {
-//  -------------------------------------------
-      this.uploadFileName = name;
-    }
-    public void setUploadContentType (final String mime) {
-//  ----------------------------------------------
-      this.uploadMimeType = mime;
-    }
+       /**
+        * Get the document index to which the action applies.
+        * 
+        * @return the document index to which the action applies
+        */
+       public String getIndex() {
+               return _index;
+       }
+
+       /**
+        * Get the uploaded file name.
+        * 
+        * @return the uploaded file name
+        */
+       public String getFileName() {
+               return _uploadFileName;
+       }
+
+       /**
+        * Get the action to which the uploaded file is passed.
+        * 
+        * @return the action to which the uploaded file is passed.
+        */
+       public String getNextAction() {
+               return _nextAction;
+       }
+
+       /**
+        * Cancel the uploading.
+        * 
+        * @param back
+        */
+       public void setCancel(final boolean back) {
+               this._action = ToDo.cancel;
+       }
+
+       /**
+        * Set the flag to perform uploading.
+        * 
+        * @param upload
+        */
+       public void setDoIt(final boolean upload) {
+               this._action = ToDo.upload;
+       }
+
+       /**
+        * Set the document index to which the action applies.
+        * 
+        * @param index
+        *            the document index to which the action applies.
+        */
+       public void setIndex(final String index) {
+               this._index = index;
+       }
+
+       /**
+        * Set the action to which the uploaded file is passed.
+        * 
+        * @param next
+        *            the action to which the uploaded file is passed.
+        */
+       public void setNextAction(final String next) {
+               this._nextAction = next;
+       }
+
+       /**
+        * Set the uploaded file.
+        * 
+        * @param upload
+        *            the file
+        */
+       public void setUpload(final File upload) {
+               this._upload = upload;
+       }
+
+       /**
+        * Set the uploaded file name.
+        * 
+        * @param name
+        *            the uploaded file name
+        */
+       public void setUploadFileName(final String name) {
+               this._uploadFileName = name;
+       }
+
+       /**
+        * Set the mime type of the uploaded file.
+        * 
+        * @param mime
+        *            the mime type of the uploaded file
+        */
+       public void setUploadContentType(final String mime) {
+               this._uploadMimeType = mime;
+       }
 
        /**
         * Get the repositoryService.
+        * 
         * @return the repositoryService
         */
        public RepositoryService getRepositoryService() {
@@ -167,14 +273,17 @@ public class UploadAction extends Action {
 
        /**
         * Set the repositoryService.
-        * @param repositoryService the repositoryService to set
+        * 
+        * @param repositoryService
+        *            the repositoryService to set
         */
        public void setRepositoryService(final RepositoryService repositoryService) {
                _repositoryService = repositoryService;
        }
-       
+
        /**
         * Get the menuProperty.
+        * 
         * @return the menuProperty
         */
        public String getMenuProperty() {
@@ -183,14 +292,17 @@ public class UploadAction extends Action {
 
        /**
         * Set the menuProperty.
-        * @param menuProperty the menuProperty to set
+        * 
+        * @param menuProperty
+        *            the menuProperty to set
         */
        public void setMenuProperty(final String menuProperty) {
                this._menuProperty = menuProperty;
        }
-       
+
        /**
         * Get the _titleProperty.
+        * 
         * @return the _titleProperty
         */
        public String getTitleProperty() {
@@ -199,7 +311,9 @@ public class UploadAction extends Action {
 
        /**
         * Set the _titleProperty.
-        * @param titleProperty the titleProperty to set
+        * 
+        * @param titleProperty
+        *            the titleProperty to set
         */
        public void setTitleProperty(final String titleProperty) {
                _titleProperty = titleProperty;
@@ -207,6 +321,7 @@ public class UploadAction extends Action {
 
        /**
         * Get the _editDisabledProperty.
+        * 
         * @return the _editDisabledProperty
         */
        public String getEditDisabledProperty() {
@@ -214,15 +329,18 @@ public class UploadAction extends Action {
        }
 
        /**
-        * Set the _editDisabledProperty.
-        * @param _editDisabledProperty the _editDisabledProperty to set
+        * Set the editDisabledProperty.
+        * 
+        * @param editDisabledProperty
+        *            the editDisabledProperty to set
         */
-       public void setEditDisabledProperty(final String _editDisabledProperty) {
-               this._editDisabledProperty = _editDisabledProperty;
+       public void setEditDisabledProperty(final String editDisabledProperty) {
+               this._editDisabledProperty = editDisabledProperty;
        }
 
        /**
         * Get the toolProperty.
+        * 
         * @return the toolProperty
         */
        public String getToolProperty() {
@@ -231,14 +349,17 @@ public class UploadAction extends Action {
 
        /**
         * Set the toolProperty.
-        * @param toolProperty the toolProperty to set
+        * 
+        * @param toolProperty
+        *            the toolProperty to set
         */
        public void setToolProperty(final String toolProperty) {
                _toolProperty = toolProperty;
        }
-       
+
        /**
         * Get the leftMenuProperty.
+        * 
         * @return the leftMenuProperty
         */
        public String getLeftMenuProperty() {
@@ -247,7 +368,9 @@ public class UploadAction extends Action {
 
        /**
         * Set the leftMenuProperty.
-        * @param leftMenuProperty the leftMenuProperty to set
+        * 
+        * @param leftMenuProperty
+        *            the leftMenuProperty to set
         */
        public void setLeftMenuProperty(final String leftMenuProperty) {
                _leftMenuProperty = leftMenuProperty;
index f3e1b96af3c0be37a9ee528729b435dbe6047dcb..bdea14f849f55080380a821d0186c089ffffd784 100644 (file)
@@ -10,104 +10,109 @@ import org.splat.dal.bo.som.ProgressState;
 import org.splat.dal.bo.som.Publication;
 import org.splat.som.Step;
 
-
 public abstract class UploadBaseNextAction extends Action {
 
-    protected OpenStudy      mystudy  = null;
-    protected String         filename = null;   // Uploaded file name
-    protected DocumentType   deftype  = null;
-    protected List<Document> defuses  = null;
-    protected String         docname  = null;
-    protected ProgressState  state    = null;
-    protected String         docuses  = null;
-    protected ToDo           action   = null;
+       protected OpenStudy mystudy = null;
+       protected String filename = null; // Uploaded file name
+       protected DocumentType deftype = null;
+       protected List<Document> defuses = null;
+       protected String docname = null;
+       protected ProgressState state = null;
+       protected String docuses = null;
+       protected ToDo action = null;
 
        /**
         * Serial version ID.
         */
-    private static final long serialVersionUID = -6925961099244461039L;
-
-    protected enum  ToDo { cancel, save };
-
-//  ==============================================================================================================================
-//  Getters and setters
-//  ==============================================================================================================================
-
-    public DocumentType getDefaultDocumentType () {
-//  ---------------------------------------------
-      return deftype;
-    }
-    public List<Document> getDefaultDocumentUses () {
-//  -----------------------------------------------
-      return defuses;
-    }
-    public String getDocumentName () {
-//  --------------------------------
-      return docname;
-    }
-    public String getDocumentState () {
-//  ---------------------------------
-      return state.toString();
-    }
-    public String getFileName () {
-//  ----------------------------
-      return filename;
-    }
-
-    public void setCancel (boolean cancel) {
-//  --------------------------------------
-      this.action = ToDo.cancel;
-    }
-    public void setDocumentState (String state) {
-//  -------------------------------------------
-      this.state = ProgressState.valueOf(state);
-    }
-    public void setFileName (String path) {
-//  -------------------------------------
-      this.filename = path;
-    }
-    public void setUses (String list) {
-//  ---------------------------------
-      this.docuses = list;
-    }
-    public void setSave (boolean save) {
-//  ----------------------------------
-      this.action = ToDo.save;
-    }
-    
-    public String getWriteAccess() {
-       if (mystudy == null) {
-               return "false";
-       }
-               return String.valueOf(mystudy.isOpenForWriting());
+       private static final long serialVersionUID = -6925961099244461039L;
+
+       protected enum ToDo {
+               cancel, save
+       };
+
+       // ==============================================================================================================================
+       // Getters and setters
+       // ==============================================================================================================================
+
+       public DocumentType getDefaultDocumentType() {
+               return deftype;
+       }
+
+       public List<Document> getDefaultDocumentUses() {
+               return defuses;
+       }
+
+       public String getDocumentName() {
+               return docname;
+       }
+
+       public String getDocumentState() {
+               return state.toString();
+       }
+
+       public String getFileName() {
+               return filename;
+       }
+
+       public void setCancel(final boolean cancel) {
+               this.action = ToDo.cancel;
+       }
+
+       public void setDocumentState(final String state) {
+               this.state = ProgressState.valueOf(state);
+       }
+
+       public void setFileName(final String path) {
+               this.filename = path;
+       }
+
+       public void setUses(final String list) {
+               this.docuses = list;
+       }
+
+       public void setSave(final boolean save) {
+               this.action = ToDo.save;
+       }
+
+       public String getWriteAccess() {
+               Boolean res = (mystudy != null);
+               if (res) {
+                       res = mystudy.isOpenForWriting();
+               }
+               return res.toString();
+       }
+
+       // ==============================================================================================================================
+       // Protected services
+       // ==============================================================================================================================
+
+       protected void setupDefaultUses(final DocumentType type) {
+               Set<DocumentType> uses = type.getDefaultUses();
+
+               for (Iterator<DocumentType> i = uses.iterator(); i.hasNext();) {
+                       DocumentType usetype = i.next();
+                       List<Document> usedoc = mystudy.collectInvolvedDocuments(usetype);
+                       if (usedoc.isEmpty()) {
+                               setupDefaultUses(usetype);
+                       } else {
+                               defuses.addAll(usedoc);
+                       }
+               }
+       }
+
+       protected Publication getPublication(final int index) {
+               List<Step> steps = mystudy.getInvolvedSteps();
+               Publication found = null, pub;
+               for (Iterator<Step> i = steps.iterator(); i.hasNext();) {
+                       List<Publication> published = i.next().getAllDocuments();
+                       for (Iterator<Publication> j = published.iterator(); j.hasNext();) {
+                               pub = j.next(); // In a given study step,
+                               if (pub.value().getIndex() == index) {
+                                       found = pub; // there is only one publication of a given document
+                                       break;
+                               }
+                       }
+               }
+               return found;
        }
-//  ==============================================================================================================================
-//  Protected services
-//  ==============================================================================================================================
-
-    protected void setupDefaultUses (DocumentType type) {
-//  -------------------------------------------------
-      Set<DocumentType> uses = type.getDefaultUses();
-      
-      for (Iterator<DocumentType> i=uses.iterator(); i.hasNext();) {
-       DocumentType   usetype = i.next();
-       List<Document> usedoc  = mystudy.collectInvolvedDocuments(usetype);
-       if (usedoc.isEmpty()) setupDefaultUses(usetype);
-       else                  defuses.addAll(usedoc);
-      }
-    }
-
-    protected Publication getPublication (int index) {
-//  ------------------------------------------------
-      List<Step> steps = mystudy.getInvolvedSteps();
-      
-      for (Iterator<Step> i=steps.iterator(); i.hasNext(); ) {
-        List<Publication> published = i.next().getAllDocuments();
-        for (Iterator<Publication> j=published.iterator(); j.hasNext();) {
-          Publication found = j.next();                          // In a given study step,
-          if (found.value().getIndex() == index) return found;   // there is only one publication of a given document
-        }
-      }
-      return null;
-    }
 }
\ No newline at end of file
index ac94f1305ce72103d492e87cbaaa4a51afa864d0..9f975c0311c054d034c689c236ef2f0da43bdd88 100644 (file)
@@ -79,33 +79,28 @@ public class VersionDocumentAction extends UploadBaseNextAction {
         */
        private RepositoryService _repositoryService;
        /**
-        * Value of the menu property. 
-        * It can be: none, create, open, study, knowledge, sysadmin, help.
+        * Value of the menu property. It can be: none, create, open, study, knowledge, sysadmin, help.
         */
        private String _menuProperty;
 
        /**
-        * Value of the title bar property. 
-        * It can be: study, knowledge.
+        * 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.
+        * 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.
+        * 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.
-        * It is necessary for correct building the title bar.
+        * 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. It is necessary for correct building the title bar.
         */
        private String _editDisabledProperty = "false";
 
@@ -129,8 +124,9 @@ public class VersionDocumentAction extends UploadBaseNextAction {
                        setToolProperty(Constants.NONE);
                }
                setLeftMenuProperty(Constants.STUDY_MENU);
-        initializationFullScreenContext(_menuProperty, _titleProperty, _editDisabledProperty, _toolProperty, _leftMenuProperty);
-           
+               initializationFullScreenContext(_menuProperty, _titleProperty,
+                               _editDisabledProperty, _toolProperty, _leftMenuProperty);
+
                User user = getConnectedUser();
                File updir = getRepositoryService().getDownloadDirectory(user);
                File upfile = new File(updir.getPath() + "/" + filename);
@@ -162,7 +158,8 @@ public class VersionDocumentAction extends UploadBaseNextAction {
                        if (!(Constants.NONE.equals(_toolProperty))) {
                                setToolProperty(Constants.NONE);
                                setLeftMenuProperty(Constants.STUDY_MENU);
-                               initializationFullScreenContext(_menuProperty, _titleProperty, _editDisabledProperty, _toolProperty, _leftMenuProperty);
+                               initializationFullScreenContext(_menuProperty, _titleProperty,
+                                               _editDisabledProperty, _toolProperty, _leftMenuProperty);
                        }
                        res = ERROR;
                }
@@ -241,12 +238,13 @@ public class VersionDocumentAction extends UploadBaseNextAction {
                setMenuProperty(Constants.STUDY_MENU);
                setTitleProperty(Constants.STUDY_MENU);
                setEditDisabledProperty("true");
-        initializationScreenContext(_menuProperty, _titleProperty, _editDisabledProperty);
-           
+               initializationScreenContext(_menuProperty, _titleProperty,
+                               _editDisabledProperty);
+
                if (action == ToDo.cancel) {
                        res = "cancel";
                } else {
-       
+
                        try {
                                // Getting user inputs
                                mystudy = getOpenStudy();
@@ -260,19 +258,19 @@ public class VersionDocumentAction extends UploadBaseNextAction {
                                                        .getString("date.format"));
                                        aDate = get.parse(_date);
                                }
-       
+
                                String[] listDocuses = null;
                                if (docuses != null) {
                                        listDocuses = docuses.split(",");
                                }
                                getPublicationService().versionDocument(step, user, filename,
-                                               Integer.valueOf(_index), _version, _description, state, aDate,
-                                               listDocuses, _docusedby);
-       
+                                               Integer.valueOf(_index), _version, _description, 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)
-       
+
                                res = SUCCESS;
                        } catch (FileNotFoundException error) {
                                LOG.error("Reason:", error);
@@ -283,11 +281,12 @@ public class VersionDocumentAction extends UploadBaseNextAction {
                        }
                        if (!SUCCESS.equals(res)) {
                                setToolProperty(Constants.NONE);
-                               
+
                                setLeftMenuProperty(Constants.STUDY_MENU);
-                               initializationFullScreenContext(_menuProperty, _titleProperty, _editDisabledProperty, _toolProperty, _leftMenuProperty);
+                               initializationFullScreenContext(_menuProperty, _titleProperty,
+                                               _editDisabledProperty, _toolProperty, _leftMenuProperty);
                        }
-               }               
+               }
                return res;
        }
 
@@ -356,7 +355,8 @@ public class VersionDocumentAction extends UploadBaseNextAction {
         * @param projectSettingsService
         *            project settings service
         */
-       public void setProjectSettings(final ProjectSettingsService projectSettingsService) {
+       public void setProjectSettings(
+                       final ProjectSettingsService projectSettingsService) {
                _projectSettings = projectSettingsService;
        }
 
@@ -375,7 +375,8 @@ public class VersionDocumentAction extends UploadBaseNextAction {
         * @param publicationService
         *            the publicationService to set
         */
-       public void setPublicationService(final PublicationService publicationService) {
+       public void setPublicationService(
+                       final PublicationService publicationService) {
                _publicationService = publicationService;
        }
 
@@ -473,9 +474,10 @@ public class VersionDocumentAction extends UploadBaseNextAction {
        public void setEditDisabledProperty(final String editDisabledProperty) {
                this._editDisabledProperty = editDisabledProperty;
        }
-       
+
        /**
         * Get the toolProperty.
+        * 
         * @return the toolProperty
         */
        public String getToolProperty() {
@@ -484,14 +486,17 @@ public class VersionDocumentAction extends UploadBaseNextAction {
 
        /**
         * Set the toolProperty.
-        * @param toolProperty the toolProperty to set
+        * 
+        * @param toolProperty
+        *            the toolProperty to set
         */
        public void setToolProperty(final String toolProperty) {
                _toolProperty = toolProperty;
        }
-       
+
        /**
         * Get the leftMenuProperty.
+        * 
         * @return the leftMenuProperty
         */
        public String getLeftMenuProperty() {
@@ -500,7 +505,9 @@ public class VersionDocumentAction extends UploadBaseNextAction {
 
        /**
         * Set the leftMenuProperty.
-        * @param leftMenuProperty the leftMenuProperty to set
+        * 
+        * @param leftMenuProperty
+        *            the leftMenuProperty to set
         */
        public void setLeftMenuProperty(final String leftMenuProperty) {
                _leftMenuProperty = leftMenuProperty;
index 54fc75f44f744fe2741c926d98a5d57cf47b711c..67ca84e11608de1ea54866a4b29c06219eedb8df 100644 (file)
@@ -14,10 +14,28 @@ package org.splat.wapp;
  * SIMAN constants.
  */
 public class Constants {
+       /**
+        * Standard menu key.
+        */
        public final static String STANDARD_MENU = "standard";
+       /**
+        * Study menu key.
+        */
        public final static String STUDY_MENU = "study";
+       /**
+        * Knowledge menu key.
+        */
        public final static String KNOWLEDGE_MENU = "knowledge";
+       /**
+        * No selected item key.
+        */
        public final static String NONE = "none";
+       /**
+        * TRUE literal constant.
+        */
        public final static String TRUE = "true";
+       /**
+        * Scenario properties menu key.
+        */
        public final static String PROP_SCENARIO = "prop-scenario";
 }