]> SALOME platform Git repositories - tools/siman.git/commitdiff
Salome HOME
Remove study method is implemented. Unit test is added.
authorrkv <rkv@opencascade.com>
Mon, 18 Mar 2013 06:45:40 +0000 (06:45 +0000)
committerrkv <rkv@opencascade.com>
Mon, 18 Mar 2013 06:45:40 +0000 (06:45 +0000)
Workspace/Siman-Common/src/org/splat/dal/bo/som/ProjectElement.java
Workspace/Siman-Common/src/org/splat/service/DocumentServiceImpl.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/StudyService.java
Workspace/Siman-Common/src/org/splat/service/StudyServiceImpl.java
Workspace/Siman-Common/src/org/splat/som/Step.java
Workspace/Siman-Common/src/spring/businessServiceContext.xml
Workspace/Siman-Common/src/test/splat/service/TestStudyService.java

index bf08b16ff78e281bd56f71348b1935ef35289f69..62d1e876af8c1c2a65594b35d5408de1abc2275f 100644 (file)
@@ -22,15 +22,36 @@ import org.splat.kernel.MultiplyDefinedException;
 import org.splat.kernel.ObjectProperties;
 import org.splat.som.Step;
 
+/**
+ * Persistent project element class. It can be study or scenario.
+ */
 public abstract class ProjectElement extends Entity {
 
        // Persistent fields
+       /**
+        * Persistent field: project element title.
+        */
        protected String title;
+       /**
+        * Persistent field: project element author/manager.
+        */
        protected User manager;
-       protected Date credate; // Object creation date
-       protected Date lasdate; // Object Last modification date
-       private final List<SimulationContext> contex = new Vector<SimulationContext>(); // Structured by the Step transient class
-       private final Set<Publication> docums = new LinkedHashSet<Publication>(); // Structured by the Step transient class
+       /**
+        * Persistent field: object creation date.
+        */
+       protected Date credate;
+       /**
+        * Persistent field: object last modification date.
+        */
+       protected Date lasdate;
+       /**
+        * Persistent field: simulation contexts structured by the Step transient class.
+        */
+       private final List<SimulationContext> contex = new Vector<SimulationContext>();
+       /**
+        * Persistent field: documents publications structured by the Step transient class.
+        */
+       private final Set<Publication> docums = new LinkedHashSet<Publication>();
 
        /**
         * Transient array of steps (folders).
@@ -181,18 +202,46 @@ public abstract class ProjectElement extends Entity {
        // Protected member functions
        // ==============================================================================================================================
 
+       /**
+        * Add a document publication to the project element.
+        * 
+        * @param newdoc
+        *            the publication to add
+        * @return true if added successfully, otherwise false
+        */
        public boolean add(final Publication newdoc) {
                return docums.add(newdoc);
        }
 
+       /**
+        * Add a simulation context to the project element.
+        * 
+        * @param newdoc
+        *            the simulation context to add
+        * @return true if added successfully, otherwise false
+        */
        public boolean add(final SimulationContext newdoc) {
                return contex.add(newdoc);
        }
 
+       /**
+        * Remove the document publication from the project element.
+        * 
+        * @param oldoc
+        *            the publication to remove
+        * @return true if removed successfully, otherwise false
+        */
        public boolean remove(final Publication oldoc) {
                return docums.remove(oldoc); // The removed tag becoming orphan, it is supposed automatically deleted from the data store
        }
 
+       /**
+        * Remove the simulation context from the project element.
+        * 
+        * @param oldoc
+        *            the simulation context to remove
+        * @return true if removed successfully, otherwise false
+        */
        public boolean remove(final SimulationContext oldoc) {
                return contex.remove(oldoc);
        }
index 0cb8eaba4bb5351841557310d6cbd8f67e0ff0ae..686e7343c720f69f7952881faaa7661bbca70b34 100644 (file)
@@ -338,6 +338,7 @@ public class DocumentServiceImpl implements DocumentService {
         *            the original document
         * @return true if the new reference is set
         */
+       @Transactional
        public boolean buildReferenceFrom(final Document aDoc,
                        final ProjectElement scope, final Document lineage) {
                boolean res = (aDoc.getProgressState() == ProgressState.inWORK);
@@ -366,6 +367,7 @@ public class DocumentServiceImpl implements DocumentService {
         *            the study
         * @return true if the new reference is set
         */
+       @Transactional
        public boolean buildReferenceFrom(final Document aDoc, final Study scope) {
                if (aDoc.getProgressState() != ProgressState.inWORK
                                && aDoc.getProgressState() != ProgressState.EXTERN) {
index 2d757e97769ed8bdcb07687c1d1939c8545a6604..b47c01fdbe777e04c5ee0c2fca4c9791eb3a1570 100644 (file)
@@ -27,7 +27,6 @@ import org.splat.dal.bo.kernel.Role;
 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.Document.Properties;
 import org.splat.dal.bo.som.DocumentType;
 import org.splat.dal.bo.som.File;
 import org.splat.dal.bo.som.KnowledgeElement;
@@ -40,6 +39,7 @@ import org.splat.dal.bo.som.SimulationContextType;
 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.Document.Properties;
 import org.splat.dal.dao.kernel.RoleDAO;
 import org.splat.dal.dao.kernel.UserDAO;
 import org.splat.dal.dao.som.KnowledgeElementDAO;
@@ -455,26 +455,6 @@ public class ScenarioServiceImpl implements ScenarioService {
                return kelm;
        }
 
-       /**
-        * Update the scenario in the database.
-        * 
-        * @param aScenario
-        *            the scenario to update
-        * @return true if updating succeeded
-        */
-       @Transactional
-       private boolean update(final Scenario aScenario) {
-               boolean isOk = false;
-               try {
-                       getScenarioDAO().update(aScenario); // Update of relational base
-                       isOk = true;
-               } catch (Exception error) {
-                       LOG.error("Unable to re-index the knowledge element '"
-                                       + aScenario.getIndex() + "', reason:", error);
-               }
-               return isOk;
-       }
-
        /**
         * {@inheritDoc}
         * 
@@ -691,7 +671,7 @@ public class ScenarioServiceImpl implements ScenarioService {
                                Publication newPub = getStepService().createDocument(step,
                                                dprop);
 
-                               // Remeber the new document
+                               // Remember the new document
                                newDocs.add(newPub);
 
                                saveFile(newPub, step, upfile);
index 7b23bc5942902d85cc341813e2c2fb8eceaacb12..aed2ea4aad53386bfd4dd56e1fb52838b2892038 100644 (file)
@@ -390,7 +390,6 @@ public class StepServiceImpl implements StepService {
         * @throws MismatchException
         *             if the document is not applicable to the given study step
         */
-       @Override
        @Transactional
        public Publication versionDocument(final Step aStep,
                        final Publication base, final Document.Properties dprop)
index 9b7af704e7c2f0bf208f0b106695c84571455538..347a0db89ff01f0803e66f352560fcf70affecda 100644 (file)
@@ -62,7 +62,7 @@ public interface StudyService {
         * @param index
         *            the study id
         */
-       public void removeStudy(final long index);
+       public void removeStudy(final Long index);
 
        /**
         * Create a new study.
@@ -185,7 +185,7 @@ public interface StudyService {
         * @see #isPublic()
         */
        boolean moveToPublic(Study aStudy);
-       
+
        /**
         * Moves this study from the Public to the Private area of the repository.
         * 
@@ -273,7 +273,7 @@ public interface StudyService {
         * @return the unmodifiable not null transient list of contributors of this study
         */
        List<User> getContributors(Study aStudy);
-       
+
        /**
         * Mark study as reference.
         * 
@@ -281,7 +281,7 @@ public interface StudyService {
         *            the Study
         */
        void markStudyAsReference(Study aStudy);
-       
+
        /**
         * Remove study as reference. This operation is inverse one to Mark as reference.
         * 
@@ -289,7 +289,7 @@ public interface StudyService {
         *            the Study
         */
        void removeStudyAsReference(Study aStudy);
-       
+
        /**
         * Get studies, scenarios and publications available for comparison.
         * <br><b> DocumentDto.id are actually filled in with Publication ids.</b>
@@ -311,7 +311,7 @@ public interface StudyService {
         *             if a study with such id does not exist in the database.
         */
        String getDescription(Long studyId) throws InvalidParameterException;
-       
+
        /**
         * Set the description attribute related to the study.
         * 
@@ -331,7 +331,7 @@ public interface StudyService {
         * @param studyId
         *            the study id
         * @throws InvalidParameterException
-        *              if no study with such Id has been found in the database.
+        *             if no study with such Id has been found in the database.
         * @return true if succeeded, false if study doesn't have a description.
         */
        boolean removeDescription(final Long studyId)
@@ -345,7 +345,7 @@ public interface StudyService {
         * @param userName
         *            the name of the user who compare the results.
         * @throws IncompatibleDataException
-        *         if data is incompatible for "Compare the studies" functionality.
+        *             if data is incompatible for "Compare the studies" functionality.
         * 
         * @return path to result file in the vault.
         */
index 8db0d6c83ba5a6e2c197ab115f46869d9a19d468..8e8e6a9558b8e23ab61a32ae0cc0279d8bb02960 100644 (file)
@@ -21,6 +21,7 @@ import java.util.Calendar;
 import java.util.Collections;
 import java.util.Date;
 import java.util.HashMap;
+import java.util.HashSet;
 import java.util.Iterator;
 import java.util.List;
 import java.util.Map;
@@ -29,7 +30,9 @@ import java.util.Set;
 
 import org.apache.lucene.index.IndexWriter;
 import org.apache.lucene.store.FSDirectory;
+import org.hibernate.Criteria;
 import org.hibernate.Hibernate;
+import org.hibernate.criterion.DetachedCriteria;
 import org.hibernate.criterion.Restrictions;
 import org.hibernate.proxy.HibernateProxy;
 import org.jfree.chart.ChartFactory;
@@ -51,18 +54,19 @@ 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.Study.Properties;
 import org.splat.dal.bo.som.ValidationCycle;
-import org.splat.dal.bo.som.ValidationCycle.Actor;
 import org.splat.dal.bo.som.ValidationCycleRelation;
 import org.splat.dal.bo.som.ValidationStep;
 import org.splat.dal.bo.som.Visibility;
+import org.splat.dal.bo.som.Study.Properties;
+import org.splat.dal.bo.som.ValidationCycle.Actor;
 import org.splat.dal.dao.som.DescriptionAttributeDAO;
 import org.splat.dal.dao.som.DocumentDAO;
 import org.splat.dal.dao.som.IDBuilderDAO;
 import org.splat.dal.dao.som.PublicationDAO;
 import org.splat.dal.dao.som.ScenarioDAO;
 import org.splat.dal.dao.som.StudyDAO;
+import org.splat.dal.dao.som.UsedByRelationDAO;
 import org.splat.dal.dao.som.ValidationCycleDAO;
 import org.splat.exception.IncompatibleDataException;
 import org.splat.exception.InvalidParameterException;
@@ -76,9 +80,9 @@ import org.splat.service.dto.DocumentDTO;
 import org.splat.service.dto.StudyFacadeDTO;
 import org.splat.service.technical.IndexService;
 import org.splat.service.technical.ProjectSettingsService;
-import org.splat.service.technical.ProjectSettingsService.Step;
 import org.splat.service.technical.ProjectSettingsServiceImpl;
 import org.splat.service.technical.RepositoryService;
+import org.splat.service.technical.ProjectSettingsService.Step;
 import org.splat.som.Revision;
 import org.springframework.transaction.annotation.Transactional;
 
@@ -129,6 +133,11 @@ public class StudyServiceImpl implements StudyService {
         */
        private StudyDAO _studyDAO;
 
+       /**
+        * Injected usedBy relations DAO.
+        */
+       private UsedByRelationDAO _usedByRelationDAO;
+
        /**
         * Injected scenario DAO.
         */
@@ -179,7 +188,6 @@ public class StudyServiceImpl implements StudyService {
         * 
         * @see org.splat.service.StudyService#selectStudy(long)
         */
-       @Override
        @Transactional
        public Study selectStudy(final long index) {
                Study result = getStudyDAO().get(index);
@@ -187,18 +195,60 @@ public class StudyServiceImpl implements StudyService {
                return result;
        }
 
-       /** 
+       /**
         * {@inheritDoc}
+        * 
         * @see org.splat.service.StudyService#removeStudy(long)
         */
        @Transactional
-       public void removeStudy(final long index) {
+       public void removeStudy(final Long index) {
                Study study = getStudyDAO().get(index);
+               Set<org.splat.dal.bo.som.Document> docums = new HashSet<org.splat.dal.bo.som.Document>();
                if (study != null) {
+                       // Select all documents published in the study and study's scenarios.
+                       DetachedCriteria query = DetachedCriteria.forClass(
+                                       Publication.class, "pub");
+                       query
+                                       .createCriteria("pub.owner", "projelem",
+                                                       Criteria.INNER_JOIN)
+                                       .createAlias("projelem.owner", "study", Criteria.LEFT_JOIN)
+                                       .add(
+                                                       Restrictions
+                                                                       .or(Restrictions.eq("projelem.rid", index),
+                                                                                       Restrictions.eq("study.rid", index)))
+                                       .setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
+
+                       if (LOG.isDebugEnabled()) {
+                               LOG.debug("Find study documents: " + query.toString());
+                       }
+                       for (Publication pub : getPublicationDAO().getFilteredList(query)) {
+                               docums.add(pub.value());
+                               // Find also all previous versions of the document
+                               for (org.splat.dal.bo.som.Document prev = pub.value()
+                                               .getPreviousVersion(); prev != null; prev = prev
+                                               .getPreviousVersion()) {
+                                       docums.add(prev);
+                               }
+                       }
+
+                       // Delete the study with its relations, scenarios and publications
                        getStudyDAO().delete(study);
+
+                       // Remove all relations of study documents
+                       for (org.splat.dal.bo.som.Document doc : docums) {
+                               LOG.debug("Found doc: " + doc.getTitle() + " [" + doc.getReference() + "]" + " [" + doc.getRid() + "]");
+                               doc.getAllRelations().clear();
+                       }
+                       getDocumentDAO().flush();
+
+                       // Remove all documents of the study
+                       for (org.splat.dal.bo.som.Document doc : docums) {
+                               LOG.debug("Remove doc: " + doc.getTitle() + " [" + doc.getReference() + "]" + " [" + doc.getRid() + "]");
+                               getDocumentDAO().delete(doc);
+                       }
                }
        }
-       
+
        /**
         * Get study by its reference.
         * 
@@ -219,7 +269,6 @@ public class StudyServiceImpl implements StudyService {
         * 
         * @see org.splat.service.StudyService#createStudy(org.splat.dal.bo.som.Study.Properties)
         */
-       @Override
        @Transactional
        public Study createStudy(final Study.Properties sprop)
                        throws MissedPropertyException, InvalidPropertyException,
@@ -229,14 +278,14 @@ public class StudyServiceImpl implements StudyService {
 
                buildReference(study);
                getStudyDAO().create(study);
-//             try {
-//                     IndexService lucin = getIndex();
-//                     lucin.add(study);
-//             } catch (IOException error) {
-//                     LOG.error("Unable to index the study '" + study.getIndex()
-//                                     + "', reason:", error);
-//                     // Continue and try to index later
-//             }
+               // try {
+               // IndexService lucin = getIndex();
+               // lucin.add(study);
+               // } catch (IOException error) {
+               // LOG.error("Unable to index the study '" + study.getIndex()
+               // + "', reason:", error);
+               // // Continue and try to index later
+               // }
                return study;
        }
 
@@ -245,7 +294,6 @@ public class StudyServiceImpl implements StudyService {
         * 
         * @see org.splat.service.StudyService#addProjectContext(org.splat.dal.bo.som.Study, org.splat.dal.bo.som.SimulationContext.Properties)
         */
-       @Override
        @Transactional
        public SimulationContext addProjectContext(final Study aStudy,
                        final SimulationContext.Properties cprop)
@@ -262,7 +310,6 @@ public class StudyServiceImpl implements StudyService {
         * 
         * @see org.splat.service.StudyService#addProjectContext(org.splat.dal.bo.som.Study, org.splat.dal.bo.som.SimulationContext)
         */
-       @Override
        @Transactional
        public SimulationContext addProjectContext(final Study aStudy,
                        final SimulationContext context) {
@@ -277,7 +324,6 @@ public class StudyServiceImpl implements StudyService {
         * 
         * @see org.splat.service.StudyService#addContributor(org.splat.dal.bo.som.Study, org.splat.dal.bo.kernel.User)
         */
-       @Override
        public boolean addContributor(final Study aStudy, final User user) {
                List<User> contributor = getModifiableContributors(aStudy); // Initializes contributor
                for (Iterator<User> i = contributor.iterator(); i.hasNext();) {
@@ -307,7 +353,6 @@ public class StudyServiceImpl implements StudyService {
         * @see #isPublic()
         * @see Publication#approve(Date)
         */
-       @Override
        public boolean moveToReference(final Study aStudy) {
                if (aStudy.getProgressState() != ProgressState.APPROVED) {
                        return false;
@@ -328,7 +373,6 @@ public class StudyServiceImpl implements StudyService {
         * 
         * @see org.splat.service.StudyService#update(org.splat.dal.bo.som.Study, org.splat.dal.bo.som.Study.Properties)
         */
-       @Override
        public boolean update(final Study aStudy, final Properties sprop)
                        throws InvalidPropertyException {
                if (sprop.getTitle() != null) {
@@ -362,13 +406,12 @@ public class StudyServiceImpl implements StudyService {
                }
                return false;
        }
-*/
+        */
        /**
         * {@inheritDoc}
         * 
         * @see org.splat.service.StudyService#removeContributor(org.splat.dal.bo.som.Study, org.splat.dal.bo.kernel.User[])
         */
-       @Override
        public boolean removeContributor(final Study aStudy, final User... users) {
                List<User> contributor = getModifiableContributors(aStudy); // Initializes contributor
                Boolean done = false;
@@ -397,7 +440,6 @@ public class StudyServiceImpl implements StudyService {
         * 
         * @see org.splat.service.StudyService#removeProjectContext(org.splat.dal.bo.som.Study, org.splat.dal.bo.som.SimulationContext)
         */
-       @Override
        public boolean removeProjectContext(final Study aStudy,
                        final SimulationContext context) {
                boolean done = getStepService().removeSimulationContext(
@@ -412,17 +454,17 @@ public class StudyServiceImpl implements StudyService {
         * @see org.splat.service.StudyService#setValidationCycle(org.splat.dal.bo.som.Study, org.splat.dal.bo.som.DocumentType,
         *      org.splat.dal.bo.som.ValidationCycle.Properties)
         */
-       @Override
        @Transactional
-       public void setValidationCycle(final Study aStudyDTO, final DocumentType type,
-                       final ValidationCycle.Properties vprop) {
-               Map<String, ValidationCycle> validactor = aStudyDTO.getValidationCycles();
+       public void setValidationCycle(final Study aStudyDTO,
+                       final DocumentType type, final ValidationCycle.Properties vprop) {
+               Map<String, ValidationCycle> validactor = aStudyDTO
+                               .getValidationCycles();
                if (validactor == null) {
                        setShortCuts(aStudyDTO); // Initializes validactor and actor
                }
 
                Study aStudy = selectStudy(aStudyDTO.getIndex());
-               
+
                String cname = type.getName();
                ValidationCycle cycle = validactor.get(cname);
 
@@ -457,7 +499,6 @@ public class StudyServiceImpl implements StudyService {
         *            a study to demote
         * @return true if the demotion succeeded.
         */
-       @Override
        public boolean demote(final Study aStudy) {
                if (aStudy.getProgressState() == ProgressState.inCHECK) {
                        aStudy.setProgressState(ProgressState.inDRAFT);
@@ -474,7 +515,6 @@ public class StudyServiceImpl implements StudyService {
         * 
         * @see org.splat.service.StudyService#generateLocalIndex(org.splat.dal.bo.som.Study)
         */
-       @Override
        @Transactional
        public int generateLocalIndex(final Study aStudy) {
                aStudy.setLastLocalIndex(aStudy.getLastLocalIndex() + 1);
@@ -489,7 +529,6 @@ public class StudyServiceImpl implements StudyService {
         *            a study to promote
         * @return true if the demotion succeeded.
         */
-       @Override
        @Transactional
        public boolean promote(final Study aStudy) {
                if (aStudy.getProgressState() == ProgressState.inWORK) {
@@ -518,7 +557,6 @@ public class StudyServiceImpl implements StudyService {
         * @return true if the move succeeded.
         * @see #isPublic()
         */
-       @Override
        @Transactional
        public boolean moveToPublic(final Study aStudy) {
                boolean isOk = false;
@@ -530,7 +568,7 @@ public class StudyServiceImpl implements StudyService {
                }
                return isOk;
        }
-       
+
        /**
         * Moves this study from the Public to the Private area of the repository.
         * 
@@ -538,7 +576,6 @@ public class StudyServiceImpl implements StudyService {
         *            a study to move
         * @return true if the move succeeded.
         */
-       @Override
        @Transactional
        public boolean moveToPrivate(final Study aStudy) {
                boolean isOk = false;
@@ -564,7 +601,7 @@ public class StudyServiceImpl implements StudyService {
                try {
                        getStudyDAO().merge(aStudy); // Update of relational base
                        setShortCuts(aStudy); // RKV: initialize transient actors set
-                       //RKV: getIndex().update(aStudy); // Update of Lucene index
+                       // RKV: getIndex().update(aStudy); // Update of Lucene index
                        isOk = true;
                } catch (Exception e) {
                        LOG.error("STD-000001", e, aStudy.getIndex(), e.getMessage());
@@ -624,7 +661,7 @@ public class StudyServiceImpl implements StudyService {
                                                        break;
                                                }
                                        }
-                                       SimpleDateFormat tostring = new SimpleDateFormat("yyyy"); //RKV: NOPMD: TODO: Use locale here?
+                                       SimpleDateFormat tostring = new SimpleDateFormat("yyyy"); // RKV: NOPMD: TODO: Use locale here?
                                        String year = tostring.format(study.getDate());
                                        year = year.substring(4 - (i - n), 4); // 4-(i-n) must be equal to either 0 or 2
                                        for (int j = 0; j < year.length(); j++) {
@@ -712,25 +749,25 @@ public class StudyServiceImpl implements StudyService {
         * @return true if reindexing succeeded
         */
        private boolean updateKnowledgeElementsIndex(final Study aStudy) {
-//             boolean isOk = false;
-//             try {
-//                     IndexService lucin = getIndex();
-//
-//                     for (Iterator<Scenario> i = aStudy.getScenariiList().iterator(); i
-//                                     .hasNext();) {
-//                             Scenario scene = i.next();
-//                             for (Iterator<KnowledgeElement> j = scene
-//                                             .getAllKnowledgeElements().iterator(); j.hasNext();) {
-//                                     KnowledgeElement kelm = j.next();
-//                                     lucin.update(kelm);
-//                             }
-//                     }
-//                     isOk = true;
-//             } catch (Exception error) {
-//                     LOG.error("Unable to re-index Knowledge Elements, reason:",
-//                                     error);
-//             }
-//             return isOk;
+               // boolean isOk = false;
+               // try {
+               // IndexService lucin = getIndex();
+               //
+               // for (Iterator<Scenario> i = aStudy.getScenariiList().iterator(); i
+               // .hasNext();) {
+               // Scenario scene = i.next();
+               // for (Iterator<KnowledgeElement> j = scene
+               // .getAllKnowledgeElements().iterator(); j.hasNext();) {
+               // KnowledgeElement kelm = j.next();
+               // lucin.update(kelm);
+               // }
+               // }
+               // isOk = true;
+               // } catch (Exception error) {
+               // LOG.error("Unable to re-index Knowledge Elements, reason:",
+               // error);
+               // }
+               // return isOk;
                return true;
        }
 
@@ -743,7 +780,7 @@ public class StudyServiceImpl implements StudyService {
         */
        private IndexService getIndex() throws IOException {
                IndexService lucin = getIndexService();
-                               if (IndexWriter.isLocked(FSDirectory.open(getRepositoryService()
+               if (IndexWriter.isLocked(FSDirectory.open(getRepositoryService()
                                .getRepositoryIndexDirectory()))) {
                        IndexWriter.unlock(FSDirectory.open(getRepositoryService()
                                        .getRepositoryIndexDirectory()));
@@ -920,7 +957,6 @@ public class StudyServiceImpl implements StudyService {
         *            the study
         * @return the unmodifiable not null transient list of contributors of this study
         */
-       @Override
        public List<User> getContributors(final Study aStudy) {
                if (aStudy.getContributor() == null) {
                        setShortCuts(aStudy);
@@ -951,10 +987,10 @@ public class StudyServiceImpl implements StudyService {
         *            the document type being subject of validation
         * @return the validation cycle of the document, or null if not defined.
         */
-       @Override
        public ValidationCycle getValidationCycleOf(final Study aStudy,
                        final DocumentType type) {
-               if (aStudy.getValidationCycles() == null || aStudy.getValidationCycles().isEmpty()) {
+               if (aStudy.getValidationCycles() == null
+                               || aStudy.getValidationCycles().isEmpty()) {
                        setShortCuts(aStudy);
                }
                ValidationCycle result = aStudy.getValidationCycles().get(
@@ -980,7 +1016,6 @@ public class StudyServiceImpl implements StudyService {
         * @return true if the given user is actor of this study.
         * @see #getActors()
         */
-       @Override
        public boolean hasActor(final Study aStudy, final User user) {
                if (user == null) {
                        return false;
@@ -1004,7 +1039,6 @@ public class StudyServiceImpl implements StudyService {
         * @return true if the given user is actor of this study.
         * @see #getContributors()
         */
-       @Override
        public boolean isStaffedBy(final Study aStudy, final User user) {
                if (user == null) {
                        return false;
@@ -1032,7 +1066,6 @@ public class StudyServiceImpl implements StudyService {
         * @param aStudy
         *            the study
         */
-       @Override
        public void loadWorkflow(final Study aStudy) {
                setShortCuts(aStudy);
        }
@@ -1093,172 +1126,185 @@ public class StudyServiceImpl implements StudyService {
                        aStudy.getActor().add(((ActorRelation) link).getTo());
                }
        }
-       
+
        /**
         * 
         * {@inheritDoc}
+        * 
         * @see org.splat.service.StudyService#markStudyAsReference(org.splat.dal.bo.som.Study)
         */
        @Override
        @Transactional
-       public void markStudyAsReference (final Study aStudy) {
-               
+       public void markStudyAsReference(final Study aStudy) {
+
                aStudy.setMarkreference(1);
                aStudy.setProgressState(ProgressState.TEMPLATE);
                getStudyDAO().merge(aStudy);
        }
-       
+
        /**
         * 
         * {@inheritDoc}
+        * 
         * @see org.splat.service.StudyService#removeStudyAsReference(org.splat.dal.bo.som.Study)
         */
        @Override
        @Transactional
        public void removeStudyAsReference(final Study aStudy) {
-               
+
                aStudy.setMarkreference(0);
                aStudy.setProgressState(ProgressState.APPROVED);
                getStudyDAO().merge(aStudy);
        }
-       
-       
-       /** 
+
+       /**
         * {@inheritDoc}
+        * 
         * @see org.splat.service.StudyService#getDescription(java.lang.Long)
         */
        @Override
        @Transactional(readOnly = true)
-       public String getDescription(final Long studyId) throws InvalidParameterException {
-               if(studyId == null) {
+       public String getDescription(final Long studyId)
+                       throws InvalidParameterException {
+               if (studyId == null) {
                        throw new InvalidParameterException("studyId", "null");
                }
                Study study = _studyDAO.get(studyId);
-               if(study == null) {
+               if (study == null) {
                        throw new InvalidParameterException("studyId", studyId.toString());
                }
                return study.getDescription();
        }
-       
-       
-       /** 
+
+       /**
         * {@inheritDoc}
+        * 
         * @see org.splat.service.StudyService#setDescription(java.lang.Long, java.lang.String)
         */
        @Override
        @Transactional
-       public void setDescription(final Long studyId, final String descriptionText) 
+       public void setDescription(final Long studyId, final String descriptionText)
                        throws InvalidParameterException {
-               if(studyId == null) {
+               if (studyId == null) {
                        throw new InvalidParameterException("studyId", "null");
                }
                Study study = _studyDAO.get(studyId);
-               if(study == null) {
+               if (study == null) {
                        throw new InvalidParameterException("studyId", studyId.toString());
                }
                study.setAttribute(new DescriptionAttribute(study, descriptionText));
        }
-       
-       /** 
+
+       /**
         * {@inheritDoc}
+        * 
         * @see org.splat.service.StudyService#removeStudyDescription(java.lang.Long)
         */
        @Override
        @Transactional
-       public boolean removeDescription(final Long studyId) throws InvalidParameterException {
-               if(studyId == null) {
-                       throw new InvalidParameterException("studyId", String.valueOf(studyId));
+       public boolean removeDescription(final Long studyId)
+                       throws InvalidParameterException {
+               if (studyId == null) {
+                       throw new InvalidParameterException("studyId", String
+                                       .valueOf(studyId));
                }
                Study study = _studyDAO.get(studyId);
-               if(study == null) {
-                       throw new InvalidParameterException("studyId", String.valueOf(studyId));
+               if (study == null) {
+                       throw new InvalidParameterException("studyId", String
+                                       .valueOf(studyId));
                }
-               return study.removeAttribute(study.getAttribute(DescriptionAttribute.class));
+               return study.removeAttribute(study
+                               .getAttribute(DescriptionAttribute.class));
        }
 
-       
        /**
         * 
         * {@inheritDoc}
+        * 
         * @see org.splat.service.StudyService#compare(java.util.List)
         */
        @Override
-       public String compare (final List<DocToCompareDTO> docsList, final String userName) throws IncompatibleDataException{
-               
+       public String compare(final List<DocToCompareDTO> docsList,
+                       final String userName) throws IncompatibleDataException {
+
                String axis1Name = "";
                String axis2Name = "";
                String chartTitle = "";
                String resultPath = "";
-               
+
                XYSeriesCollection dataset = new XYSeriesCollection();
-               
+
                Iterator<DocToCompareDTO> docListIter = docsList.iterator();
-               
+
                for (; docListIter.hasNext();) {
-                       
+
                        DocToCompareDTO docDTO = docListIter.next();
                        String pathToFile = docDTO.getPathToFile();
                        File compDocFile = new File(pathToFile);
-                       
-                       resultPath = pathToFile.substring(0, pathToFile.indexOf("vault")) + "downloads" + File.separator + userName + File.separator + "ComparisonResult.pdf";
-                       
+
+                       resultPath = pathToFile.substring(0, pathToFile.indexOf("vault"))
+                                       + "downloads" + File.separator + userName + File.separator
+                                       + "ComparisonResult.pdf";
+
                        XYSeries series = new XYSeries("Study: " + docDTO.getStudyTitle() + " Scenario: " + docDTO.getScenarioTitle() + " Document: " + docDTO.getDocumentTitle());
-                       
-                       //read the file and get points information.
+
+                       // read the file and get points information.
                        try {
                                Scanner input = new Scanner(compDocFile);
-                               
+
                                //get the title of the chart.
                                if (input.hasNext()) {
                                        chartTitle = input.nextLine();
                                }
                                
-                               //get the name of the axis.
+                               // get the name of the axis.
                                if (input.hasNext()) {
                                        String[] tokens = input.nextLine().split(",");
-                                                                               
-                                       if (tokens.length < 2)
-                                               throw new IncompatibleDataException(MessageKeyEnum.IDT_000001.toString());
-                                       
+
+                                       if (tokens.length < 2) {
+                                               throw new IncompatibleDataException(
+                                                               MessageKeyEnum.IDT_000001.toString());
+                                       }
+
                                        if ("".equals(axis1Name)) {
                                                axis1Name = tokens[0];
                                        } else if (!axis1Name.equals(tokens[0])) {
                                                LOG.debug("Axis must be the same for all documents");
-                                               throw new IncompatibleDataException(MessageKeyEnum.IDT_000001.toString());
+                                               throw new IncompatibleDataException(
+                                                               MessageKeyEnum.IDT_000001.toString());
                                        }
-                                       
+
                                        if ("".equals(axis2Name)) {
                                                axis2Name = tokens[1];
                                        } else if (!axis2Name.equals(tokens[1])) {
                                                LOG.debug("Axis must be the same for all documents");
-                                               throw new IncompatibleDataException(MessageKeyEnum.IDT_000001.toString());
+                                               throw new IncompatibleDataException(
+                                                               MessageKeyEnum.IDT_000001.toString());
                                        }
                                }
-                               
-                               //Get the XY points series.
-                               while(input.hasNext()) {
-                                       
+
+                               // Get the XY points series.
+                               while (input.hasNext()) {
+
                                        String currentString = input.nextLine();
-                                       
-                                       if ("".equals(currentString)) {
-                                               continue;
-                                       }
-                                       else {
+
+                                       if (!("".equals(currentString))) {
                                                String[] tokens = currentString.split(" ");
-                                               series.add(Double.valueOf(tokens[0]), Double.valueOf(tokens[1]));
-                                       }                   
-                                 
-                               } //while
-                               
+                                               series.add(Double.valueOf(tokens[0]), Double
+                                                               .valueOf(tokens[1]));
+                                       }
+
+                               } // while
+
                                dataset.addSeries(series);
-                               
+
                        } catch (FileNotFoundException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                                return "ERROR";
                        }
-               } //for
-               
+               } // for
+
                JFreeChart chart = ChartFactory.createXYLineChart(
                                chartTitle, // Title
                                axis1Name, // x-axis Label
@@ -1269,28 +1315,30 @@ public class StudyServiceImpl implements StudyService {
                                true, // Use tooltips
                                false // Configure chart to generate URLs?
                                );
-               
-               //export to PDF - file.                 
+
+               // export to PDF - file.
                int x = 500;
                int y = 300;
                Rectangle pagesize = new Rectangle(x, y);
                Document document = new Document(pagesize, 50, 50, 50, 50);
-        PdfWriter writer;
+               PdfWriter writer;
                try {
                        File resFile = new File(resultPath);
-                       File resFolder = new File(resultPath.substring(0, resultPath.lastIndexOf(File.separator)));
+                       File resFolder = new File(resultPath.substring(0, resultPath
+                                       .lastIndexOf(File.separator)));
                        resFolder.mkdirs();
-                       writer = PdfWriter.getInstance(document, new FileOutputStream(resFile));
-               
-               document.open();
-               PdfContentByte cb = writer.getDirectContent();
-               PdfTemplate tp = cb.createTemplate(x, y);
-               Graphics2D g2 = tp.createGraphics(x, y, new DefaultFontMapper());
-               chart.draw(g2, new java.awt.Rectangle(x,y));
-               g2.dispose();
-               cb.addTemplate(tp, 0, 0);
-               document.close(); 
-        
+                       writer = PdfWriter.getInstance(document, new FileOutputStream(
+                                       resFile));
+
+                       document.open();
+                       PdfContentByte cb = writer.getDirectContent();
+                       PdfTemplate tp = cb.createTemplate(x, y);
+                       Graphics2D g2 = tp.createGraphics(x, y, new DefaultFontMapper());
+                       chart.draw(g2, new java.awt.Rectangle(x, y));
+                       g2.dispose();
+                       cb.addTemplate(tp, 0, 0);
+                       document.close();
+
                } catch (FileNotFoundException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
@@ -1298,10 +1346,10 @@ public class StudyServiceImpl implements StudyService {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                }
-               
+
                return resultPath;
        }
-       
+
        /**
         * Get project settings.
         * 
@@ -1495,7 +1543,7 @@ public class StudyServiceImpl implements StudyService {
        public void setUserService(final UserService userService) {
                _userService = userService;
        }
-       
+
        /**
         * {@inheritDoc}
         * 
@@ -1596,6 +1644,7 @@ public class StudyServiceImpl implements StudyService {
        
        /**
         * Get the publicationDAO.
+        * 
         * @return the publicationDAO
         */
        public PublicationDAO getPublicationDAO() {
@@ -1604,7 +1653,9 @@ public class StudyServiceImpl implements StudyService {
 
        /**
         * Set the publicationDAO.
-        * @param publicationDAO the publicationDAO to set
+        * 
+        * @param publicationDAO
+        *            the publicationDAO to set
         */
        public void setPublicationDAO(final PublicationDAO publicationDAO) {
                _publicationDAO = publicationDAO;
@@ -1612,6 +1663,7 @@ public class StudyServiceImpl implements StudyService {
 
        /**
         * Get the repositoryService.
+        * 
         * @return the repositoryService
         */
        public RepositoryService getRepositoryService() {
@@ -1620,7 +1672,9 @@ public class StudyServiceImpl implements StudyService {
 
        /**
         * Set the repositoryService.
-        * @param repositoryService the repositoryService to set
+        * 
+        * @param repositoryService
+        *            the repositoryService to set
         */
        public void setRepositoryService(final RepositoryService repositoryService) {
                _repositoryService = repositoryService;
@@ -1628,6 +1682,7 @@ public class StudyServiceImpl implements StudyService {
 
        /**
         * Get the documentDAO.
+        * 
         * @return the documentDAO
         */
        public DocumentDAO getDocumentDAO() {
@@ -1636,7 +1691,9 @@ public class StudyServiceImpl implements StudyService {
 
        /**
         * Set the documentDAO.
-        * @param documentDAO the documentDAO to set
+        * 
+        * @param documentDAO
+        *            the documentDAO to set
         */
        public void setDocumentDAO(final DocumentDAO documentDAO) {
                _documentDAO = documentDAO;
@@ -1644,6 +1701,7 @@ public class StudyServiceImpl implements StudyService {
 
        /**
         * Get the descriptionAttributeDAO.
+        * 
         * @return the descriptionAttributeDAO
         */
        public DescriptionAttributeDAO getDescriptionAttributeDAO() {
@@ -1652,10 +1710,32 @@ public class StudyServiceImpl implements StudyService {
 
        /**
         * Set the descriptionAttributeDAO.
-        * @param descriptionAttributeDAO the descriptionAttributeDAO to set
+        * 
+        * @param descriptionAttributeDAO
+        *            the descriptionAttributeDAO to set
         */
        public void setDescriptionAttributeDAO(
                        final DescriptionAttributeDAO descriptionAttributeDAO) {
                _descriptionAttributeDAO = descriptionAttributeDAO;
        }
+
+       /**
+        * Get the usedByRelationDAO.
+        * 
+        * @return the usedByRelationDAO
+        */
+       public UsedByRelationDAO getUsedByRelationDAO() {
+               return _usedByRelationDAO;
+       }
+
+       /**
+        * Set the usedByRelationDAO.
+        * 
+        * @param usedByRelationDAO
+        *            the usedByRelationDAO to set
+        */
+       public void setUsedByRelationDAO(final UsedByRelationDAO usedByRelationDAO) {
+               _usedByRelationDAO = usedByRelationDAO;
+       }
+
 }
index 8fbbb06ef3a09a55a1d22e28b2408b27099341da..96297d19c4819faabea60c884df38c9c38ef9c32 100644 (file)
@@ -24,49 +24,72 @@ import org.splat.dal.bo.som.SimulationContextType;
 import org.splat.dal.bo.som.Study;
 import org.splat.service.technical.ProjectSettingsService;
 
+/**
+ * The activity (step) instance of a project element.
+ */
 public class Step {
 
+       /**
+        * The study workflow step presented by this step instance.
+        */
        private transient final ProjectSettingsService.Step _step;
+       /**
+        * The parent project element containing this step.
+        */
        private transient final ProjectElement _owner;
+       /**
+        * The list of applied simulation contexts.
+        */
        private transient final List<SimulationContext> _contex;
+       /**
+        * The list of documents publications of this step instance.
+        */
        private transient final List<Publication> _docums;
-       private User _actor; // Actor involved in operations on published documents and requiring a time-stamp
+       /**
+        * Actor involved in operations on published documents and requiring a time-stamp.
+        */
+       private User _actor;
 
-       // ==============================================================================================================================
+       // =========================================================================
        // Constructor
-       // ==============================================================================================================================
+       // =========================================================================
 
+       /**
+        * The constructor of the study step instance.
+        * 
+        * @param step
+        *            the study workflow step to instantiate
+        * @param owner
+        *            the parent project element
+        */
        public Step(final ProjectSettingsService.Step step,
                        final ProjectElement owner) {
                this._step = step;
                this._owner = owner;
                this._contex = new ArrayList<SimulationContext>();
                this._docums = new ArrayList<Publication>();
-               this._actor = null;
 
                // Filtering of Simulation contexts, if exist
                for (Iterator<SimulationContext> i = owner.SimulationContextIterator(); i
                                .hasNext();) {
                        SimulationContext adoc = i.next();
-                       if (!adoc.isInto(this)) {
-                               continue;
+                       if (adoc.isInto(this)) {
+                               this._contex.add(adoc);
                        }
-                       this._contex.add(adoc);
                }
                // Filtering of Documents, if exist
                for (Iterator<Publication> i = owner.PublicationIterator(); i.hasNext();) {
                        Publication mydoc = i.next();
-                       if (!mydoc.value().isInto(this)) {
-                               continue;
+                       if (mydoc.value().isInto(this)) {
+                               mydoc.setStep(this); // RKV
+                               this._docums.add(mydoc);
                        }
-                       mydoc.setStep(this); // RKV
-                       this._docums.add(mydoc);
                }
        }
 
-       // ==============================================================================================================================
+       // =========================================================================
        // Public member functions
-       // ==============================================================================================================================
+       // =========================================================================
 
        public User getActor() {
                return _actor;
@@ -89,63 +112,116 @@ public class Step {
                return Collections.unmodifiableList(_contex);
        }
 
+       /**
+        * Get document publication or null if it is not published in this step.
+        * 
+        * @param docId
+        *            document id
+        * @return document publication or null if not published in this step
+        */
        public Publication getDocument(final long docId) {
-               for (Iterator<Publication> i = _docums.iterator(); i.hasNext();) {
-                       Publication found = i.next(); // In a given study step,
-                       if (found.value().getIndex() == docId) {
-                               return found; // there is only one publication of a given document
+               Publication found = null;
+               for (Publication pub : _docums) {
+                       // In a given study step,
+                       if (pub.value().getIndex() == docId) {
+                               found = pub; // there is only one publication of a given document
+                               break;
                        }
                }
-               return null;
+               return found;
        }
 
+       /**
+        * Get step number.
+        * 
+        * @return step number
+        */
        public int getNumber() {
                return _step.getNumber();
        }
 
+       /**
+        * Get step's parent project element.
+        * 
+        * @return parent project element
+        */
        public ProjectElement getOwner() {
                return _owner; // May be a Study or a Scenario
        }
 
+       /**
+        * Get parent study.
+        * 
+        * @return the parent study
+        */
        public Study getOwnerStudy() {
                return _owner.getOwnerStudy();
        }
 
+       /**
+        * Get data path for this step.
+        * 
+        * @return the data path
+        */
        public String getPath() {
                return _step.getPath();
        }
 
+       /**
+        * Get all documents publications which are results of this step according to documents types.
+        * 
+        * @return list of the step result documents publications
+        */
        public List<Publication> getResultDocuments() {
                List<Publication> result = new ArrayList<Publication>();
 
                if (!_docums.isEmpty()) {
-                       for (Iterator<Publication> i = _docums.iterator(); i.hasNext();) {
-                               Publication content = i.next();
+                       for (Publication content : _docums) {
                                DocumentType type = content.value().getType();
-                               if (!type.isResultOf(this.getStep())) {
-                                       continue;
+                               if (type.isResultOf(this.getStep())) {
+                                       result.add(content);
                                }
-                               result.add(content);
                        }
                }
                return result;
        }
 
+       /**
+        * Get the abstract workflow step of this step instance.
+        * 
+        * @return the abstract workflow step
+        */
        public ProjectSettingsService.Step getStep() {
                return _step;
        }
 
-       public SimulationContext getSimulationContext(final long l) {
+       /**
+        * Get an applied simulation context by its id or null.
+        * 
+        * @param contextId
+        *            the simulation context id
+        * @return simulation context or null if it is not applied to this step
+        */
+       public SimulationContext getSimulationContext(final long contextId) {
+               SimulationContext found = null;
                for (Iterator<SimulationContext> i = _owner.SimulationContextIterator(); i
                                .hasNext();) {
                        SimulationContext myctex = i.next();
-                       if (myctex.getIndex() == l) {
-                               return myctex;
+                       if (myctex.getIndex() == contextId) {
+                               found = myctex;
+                               break;
                        }
                }
-               return null;
+               return found;
        }
 
+       /**
+        * Get applied simulation contexts of the given type.
+        * 
+        * @param type
+        *            the simulation context type
+        * @return the list of applied simulation contexts
+        */
        public List<SimulationContext> getSimulationContext(
                        final SimulationContextType type) {
                List<SimulationContext> result = new ArrayList<SimulationContext>();
@@ -160,6 +236,11 @@ public class Step {
                return result;
        }
 
+       /**
+        * Check if the step is started, i.e. it contains a knowledge if applicable or at least one document.
+        * 
+        * @return true if the step is started, otherwise false
+        */
        public boolean isStarted() {
                boolean res = _step.mayContain(KnowledgeElement.class);
                if (res) {
@@ -172,52 +253,73 @@ public class Step {
                return res;
        }
 
+       /**
+        * Check if the step is finished, i.e. all knowledges are approved if any,<BR>
+        * there is at least one non external result document and all non external <BR>
+        * result documents are approved.
+        * 
+        * @return true if the step is finished, otherwise false
+        */
        public boolean isFinished() {
-               if (_step.mayContain(KnowledgeElement.class)) { // Check if all result documents are approved
+               boolean result = false;
+               if (_step.mayContain(KnowledgeElement.class)) {
+                       // Check if all existing knowledges are approved
                        List<KnowledgeElement> kelm = ((Scenario) _owner)
                                        .getAllKnowledgeElements();
-                       if (kelm.isEmpty()) {
-                               return false;
-                       }
-                       for (Iterator<KnowledgeElement> i = kelm.iterator(); i.hasNext();) {
-                               KnowledgeElement content = i.next();
-                               if (content.getProgressState() != ProgressState.APPROVED) {
-                                       return false;
+                       if (!kelm.isEmpty()) {
+                               result = true;
+                               for (KnowledgeElement content : kelm) {
+                                       if (content.getProgressState() != ProgressState.APPROVED) {
+                                               result = false;
+                                               break;
+                                       }
                                }
                        }
-                       return true;
-               } else { // Check if all existing knowledges are approved
-                       if (_docums.isEmpty()) {
-                               return false;
-                       }
-                       boolean result = false;
-                       for (Iterator<Publication> i = _docums.iterator(); i.hasNext();) {
-                               Document content = i.next().value();
+               } else {
+                       // Check if all result documents are approved
+                       for (Publication pub : _docums) {
+                               Document content = pub.value();
                                DocumentType type = content.getType();
-                               if (!type.isResultOf(this.getStep())) {
-                                       continue;
-                               }
-                               if (content.getProgressState() == ProgressState.EXTERN) {
-                                       continue;
-                               }
-                               result = true; // There is at least 1 non external result document
-                               if (content.getProgressState() != ProgressState.APPROVED) {
-                                       return false;
+                               if (type.isResultOf(this.getStep())
+                                               && (content.getProgressState() != ProgressState.EXTERN)) {
+                                       // There is at least 1 non external result document
+                                       result = (content.getProgressState() == ProgressState.APPROVED);
+                                       if (!result) {
+                                               break; // not approved result is found
+                                       }
                                }
                        }
-                       return result;
                }
+               return result;
        }
 
+       /**
+        * Check if data of the given type are applicable to this step.
+        * 
+        * @param type
+        *            the data type to check
+        * @return true if the type is applicable to the step, otherwise false
+        */
        @SuppressWarnings("unchecked")
        public boolean mayContain(final Class type) {
                return _step.mayContain(type);
        }
 
+       /**
+        * Set an actor involved in operations on published documents and requiring a time-stamp.
+        * 
+        * @param user
+        *            the actor to set
+        */
        public void setActor(final User user) {
                _actor = user;
        }
 
+       /**
+        * Get the list of simulation contexts applied to this step instance.
+        * 
+        * @return the list of applied simulation contexts
+        */
        public List<SimulationContext> getContex() {
                return _contex;
        }
index 2e7fd929324afe94dc58b1bea55125529e69c0fe..ef382affb666210f7d13e182ca618ab0801e6d4b 100644 (file)
@@ -150,7 +150,9 @@ http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
                        ref="projectElementService" />
                <property name="projectSettings" ref="projectSettings" />
                <property name="stepService" ref="stepService" />
-               <property name="studyDAO" ref="studyDAO" />
+        <property name="studyDAO" ref="studyDAO" />
+        <property name="documentDAO" ref="documentDAO" />
+        <property name="usedByRelationDAO" ref="usedByRelationDAO" />
                <property name="scenarioDAO" ref="scenarioDAO" />
                <property name="IDBuilderDAO" ref="iDBuilderDAO" />
                <property name="validationCycleDAO" ref="validationCycleDAO" />
index 2c2f93a249b26331bf6061770954822acfba1359..dc2e30306ef8e9b21e29782801c61429b0f9c64c 100644 (file)
@@ -8,7 +8,9 @@
  *****************************************************************************/
 package test.splat.service;
 
+import java.io.File;
 import java.io.FileNotFoundException;
+import java.io.FileWriter;
 import java.io.IOException;
 import java.sql.SQLException;
 import java.util.Date;
@@ -47,11 +49,14 @@ import org.splat.kernel.MissedPropertyException;
 import org.splat.kernel.MultiplyDefinedException;
 import org.splat.log.AppLogger;
 import org.splat.service.DocumentTypeService;
+import org.splat.service.ProjectElementService;
 import org.splat.service.PublicationService;
 import org.splat.service.SimulationContextService;
 import org.splat.service.StepService;
 import org.splat.service.StudyService;
+import org.splat.service.dto.FileDTO;
 import org.splat.service.technical.ProjectSettingsService;
+import org.splat.service.technical.RepositoryService;
 import org.splat.service.technical.ProjectSettingsService.Step;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.beans.factory.annotation.Qualifier;
@@ -90,6 +95,13 @@ public class TestStudyService extends BaseTest {
        @Qualifier("publicationService")
        private transient PublicationService _publicationService;
 
+       /**
+        * The ProjectElementService. Later injected by Spring.
+        */
+       @Autowired
+       @Qualifier("projectElementService")
+       private transient ProjectElementService _projectElementService;
+
        /**
         * The StepService. Later injected by Spring.
         */
@@ -160,6 +172,13 @@ public class TestStudyService extends BaseTest {
        @Qualifier("validationCycleDAO")
        private transient ValidationCycleDAO _validationCycleDAO;
 
+       /**
+        * The RepositoryService. Later injected by Spring.
+        */
+       @Autowired
+       @Qualifier("repositoryService")
+       private transient RepositoryService _repositoryService;
+
        /**
         * Create a persistent scenario for tests.
         * 
@@ -641,9 +660,11 @@ public class TestStudyService extends BaseTest {
         * 
         * @throws BusinessException
         *             if test data creation is failed
+        * @throws IOException
+        *             if document creation is failed
         */
        @Test
-       public void testRemoveStudy() throws BusinessException {
+       public void testRemoveStudy() throws BusinessException, IOException {
                LOG.debug(">>>>> BEGIN testRemoveStudy()");
                startNestedTransaction();
 
@@ -679,7 +700,7 @@ public class TestStudyService extends BaseTest {
                SimulationContext.Properties cprop = new SimulationContext.Properties();
                cprop.setType(_simulationContextService.selectType("product"))
                                .setValue("Test Simulation Context: Product");
-               SimulationContext ctx = _studyService.addProjectContext(aStudy, cprop);
+               _studyService.addProjectContext(aStudy, cprop);
                ht.flush();
 
                // Add a scenario to the study
@@ -702,8 +723,8 @@ public class TestStudyService extends BaseTest {
 
                // Add a validation cycle with otherUser as a reviewer
                ValidationCycle.Properties vprop = new ValidationCycle.Properties();
-               DocumentType type = _documentTypeService.selectType("specification");
-               vprop.setDocumentType(type);
+               DocumentType dtype = _documentTypeService.selectType("minutes");
+               vprop.setDocumentType(dtype);
                vprop.setActor(ValidationStep.REVIEW, otherUser);
                ValidationCycle cycle = new ValidationCycle(aStudy, vprop);
                _validationCycleDAO.create(cycle);
@@ -712,11 +733,99 @@ public class TestStudyService extends BaseTest {
                ht.flush();
 
                // Add documents to the first study activity
-               // Add a version relation
-               // Add a converts relation
+               // Add a converts relations
+               Publication pub1 = addDoc(aStudy, "document1", dtype);
+               Publication pub2 = addDoc(aStudy, "document2", dtype);
+               Publication pub3 = addDoc(aStudy, "document3", dtype);
+               ht.flush();
+
+               LOG.debug("pub1 version doc: " + pub1.value().getTitle() + " ["
+                               + pub1.value().getReference() + "]" + " ["
+                               + pub1.value().getRid() + "]");
+               LOG.debug("pub2 version doc: " + pub2.value().getTitle() + " ["
+                               + pub2.value().getReference() + "]" + " ["
+                               + pub2.value().getRid() + "]");
+               LOG.debug("pub3 version doc: " + pub3.value().getTitle() + " ["
+                               + pub3.value().getReference() + "]" + " ["
+                               + pub3.value().getRid() + "]");
+
+               ht.update(aStudy);
+
+               ht.flush();
+               LOG.debug("Before versioning:");
+               for (Publication doc : _projectElementService.getFirstStep(aStudy)
+                               .getAllDocuments()) {
+                       LOG.debug("Study doc: " + doc.value().getTitle() + " ["
+                                       + doc.value().getReference() + "]" + " ["
+                                       + doc.value().getRid() + "]");
+               }
+               // Add a version relations
+               Publication pub31 = version(pub3);
+
+               // _publicationService.versionDocument(_projectElementService
+               // .getFirstStep(aStudy), goodUser, pub3
+               // .getSourceFile().getName(), pub3.value().getIndex(), "",
+               // "The new version", pub3.getProgressState(), new Date(), null,
+               // null);
+
+               // Publication pub31 = null;
+               // for (Publication pub : aStudy.getDocums()) {
+               // if (pub.value().getPreviousVersion() != null) {
+               // pub31 = pub;
+               // }
+               // }
+
+               LOG.debug("pub31 version doc: " + pub31.value().getTitle() + " ["
+                               + pub31.value().getReference() + "]" + " ["
+                               + pub31.value().getRid() + "]");
+               ht.saveOrUpdate(aStudy);
+
+               LOG.debug("After versioning:");
+               for (Publication doc : aStudy.getDocums()) {
+                       LOG.debug("Study doc: " + doc.value().getTitle() + " ["
+                                       + doc.value().getReference() + "]" + " ["
+                                       + doc.value().getRid() + "]");
+               }
+
                // Add documents to the first scenario activity
+               Publication spub1 = addDoc(scen, "sdocument1", dtype);
+               Publication spub2 = addDoc(scen, "sdocument2", dtype);
+               Publication spub3 = addDoc(scen, "sdocument3", dtype);
+               LOG.debug("spub1 version doc: " + spub1.value().getTitle() + " ["
+                               + spub1.value().getReference() + "]" + " ["
+                               + spub1.value().getRid() + "]");
+               LOG.debug("spub2 version doc: " + spub2.value().getTitle() + " ["
+                               + spub2.value().getReference() + "]" + " ["
+                               + spub2.value().getRid() + "]");
+               LOG.debug("spub3 version doc: " + spub3.value().getTitle() + " ["
+                               + spub3.value().getReference() + "]" + " ["
+                               + spub3.value().getRid() + "]");
+               ht.flush();
+
+               // Create a scenario document version
+               Publication spub31 = version(spub3);
+               LOG.debug("spub31 version doc: " + spub31.value().getTitle() + " ["
+                               + spub31.value().getReference() + "]" + " ["
+                               + spub31.value().getRid() + "]");
+
                // Add uses relations
+               pub2.addDependency(pub1);
+               ht.saveOrUpdate(pub2.value());
+               pub3.addDependency(pub2);
+               ht.saveOrUpdate(pub3.value());
+
+               spub2.addDependency(pub1);
+               spub2.addDependency(spub1);
+               spub2.addDependency(pub2);
+               spub2.addDependency(pub3);
+               ht.saveOrUpdate(spub2.value());
+               spub3.addDependency(spub2);
+               ht.saveOrUpdate(spub3.value());
+               spub31.addDependency(spub31);
+               ht.saveOrUpdate(spub31.value());
+               ht.flush();
 
+               // /////////////////////////////////////////////////////////
                ht.clear();
                _studyService.removeStudy(studyId);
                ht.flush();
@@ -747,14 +856,156 @@ public class TestStudyService extends BaseTest {
                                .find("from Publication pub left join pub.owner as own where own.rid="
                                                + studyId + " or own.rid=" + scen.getIndex());
                Assert.assertEquals(found.size(), 0, "Publication is not removed");
+               found = ht.find("from Publication");
+               Assert.assertEquals(found.size(), 0, "Publication is not removed");
                // Check removal of documents
+               found = ht.find("from Document");
+               Assert.assertEquals(found.size(), 0, "Document is not removed");
                // Check removal of version relations
+               found = ht.find("from VersionsRelation");
+               Assert.assertEquals(found.size(), 0, "VersionsRelation is not removed");
                // Check removal of converts relations
+               found = ht.find("from ConvertsRelation");
+               Assert.assertEquals(found.size(), 0, "ConvertsRelation is not removed");
                // Check removal of files
+               found = ht.find("from File");
+               Assert.assertEquals(found.size(), 0, "File is not removed");
                // Check removal of uses relations
+               found = ht.find("from UsesRelation");
+               Assert.assertEquals(found.size(), 0, "UsesRelation is not removed");
                // Check removal of usedBy relations
+               found = ht.find("from UsedByRelation");
+               Assert.assertEquals(found.size(), 0, "UsedByRelation is not removed");
 
                rollbackNestedTransaction();
                LOG.debug(">>>>> END testRemoveStudy()");
        }
+
+       /**
+        * Create a new version of the document.
+        * 
+        * @param pub
+        *            the current document publication
+        * @return the new document version publication
+        * @throws IOException
+        *             if versioning is failed
+        * @throws BusinessException
+        *             if versioning is failed
+        */
+       private Publication version(final Publication pub)
+                       throws BusinessException, IOException {
+               Document.Properties dprop = new Document.Properties();
+               dprop.setDocument(pub.value(), pub.getStep().getStep());
+               Publication newpub = _stepService.versionDocument(pub.getStep(), pub,
+                               dprop);
+               pub.getOwner().getDocums().remove(pub);
+               pub.getStep().getDocuments().remove(pub);
+               pub.getOwner().add(newpub);
+               pub.getStep().getDocuments().add(newpub);
+               return newpub;
+       }
+
+       /**
+        * Create a document and publish it in the project element.
+        * 
+        * @param aStudy
+        *            the project element
+        * @param stStep
+        * @param docname
+        *            document name
+        * @param dtype
+        *            document type
+        * @return publication of the created document
+        * @throws BusinessException
+        *             if document creation is failed
+        * @throws IOException
+        *             if file creation is failed
+        */
+       private Publication addDoc(final ProjectElement aStudy,
+                       final String docname, final DocumentType dtype)
+                       throws BusinessException, IOException {
+               HibernateTemplate ht = getHibernateTemplate();
+               // Add documents to the first study activity
+               org.splat.som.Step aStep = _projectElementService.getFirstStep(aStudy);
+               Document.Properties dprop = new Document.Properties().setAuthor(
+                               aStudy.getAuthor()).setDate(new Date()).setName(docname)
+                               .setType(dtype).setFormat("py");
+               dprop.setLocalPath(dprop.getName() + "." + dprop.getFormat());
+               dprop.setStep(aStep.getStep());
+               Publication pub = _stepService.createDocument(aStep, dprop);
+               pub.setStep(aStep);
+               aStudy.add(pub);
+               aStep.getDocuments().add(pub);
+               ht.saveOrUpdate(pub);
+               ht.save(pub.value());
+               // Add a converts relation
+               // Attach a med file
+               ht.saveOrUpdate(_publicationService.attach(pub, "med"));
+               createDownloadedFile(aStudy.getAuthor().getIndex(), dprop
+                               .getLocalPath());
+               createDownloadedFile(aStudy.getAuthor().getIndex(), dprop
+                               .getLocalPath().substring(0,
+                                               dprop.getLocalPath().lastIndexOf(".") - 1), "med");
+               return pub;
+       }
+
+       /**
+        * Create a file in the user's repository downloads directory.
+        * 
+        * @param userId
+        *            user id
+        * @param name
+        *            file name
+        * @param format
+        *            file extension
+        * @return created file DTO
+        * @throws IOException
+        *             if file creation failed
+        */
+       private FileDTO createDownloadedFile(final long userId, final String name,
+                       final String format) throws IOException {
+               // Create a file in the download directory
+               return createDownloadedFile(userId, name + "." + format);
+       }
+
+       /**
+        * Get path to the user's downloads directory. The directory is created if it is not exist yet.
+        * 
+        * @param userId
+        *            user id
+        * @return absolute path to downloads directory followed by slash
+        */
+       private String getDownloadPath(final long userId) {
+               // Prepare download directory
+               File tmpDir = _repositoryService.getDownloadDirectory(userId);
+               if (!tmpDir.exists()) {
+                       Assert.assertTrue(tmpDir.mkdir(),
+                                       "Can't create temporary directory: "
+                                                       + tmpDir.getAbsolutePath());
+               }
+
+               return tmpDir.getAbsolutePath() + "/";
+       }
+
+       /**
+        * Create a file in the user's repository downloads directory.
+        * 
+        * @param userId
+        *            user id
+        * @param fname
+        *            file name
+        * @return created file DTO
+        * @throws IOException
+        *             if file creation failed
+        */
+       private FileDTO createDownloadedFile(final long userId, final String fname)
+                       throws IOException {
+               // Create a file in the download directory
+               String filePath = getDownloadPath(userId) + fname;
+               FileWriter fw = new FileWriter(filePath);
+               fw.write("Simulation of " + fname + " file for checkin at "
+                               + new Date());
+               fw.close();
+               return new FileDTO(filePath);
+       }
 }