Salome HOME
Creation of a new study from an existing one is implemented.
[tools/siman.git] / Workspace / Siman-Common / src / test / splat / service / TestScenarioService.java
index 1c486123b063568e997415d0c98871c1aee437a2..ddb34ac2c23a4361f052b6a02ce766b6c5ec1788 100644 (file)
@@ -16,15 +16,18 @@ import java.sql.SQLException;
 import java.util.ArrayList;
 import java.util.Date;
 import java.util.HashMap;
+import java.util.Iterator;
 import java.util.List;
 import java.util.Map;
 import java.util.Set;
 
 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.KnowledgeElementType;
+import org.splat.dal.bo.som.ProjectElement;
 import org.splat.dal.bo.som.Publication;
 import org.splat.dal.bo.som.Scenario;
 import org.splat.dal.bo.som.SimulationContext;
@@ -32,9 +35,18 @@ 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.ValidationCycle;
+import org.splat.dal.bo.som.ValidationCycleRelation;
+import org.splat.dal.bo.som.ValidationStep;
 import org.splat.dal.bo.som.Document.Properties;
+import org.splat.dal.dao.kernel.UserDAO;
 import org.splat.dal.dao.som.Database;
 import org.splat.dal.dao.som.ScenarioDAO;
+import org.splat.dal.dao.som.StudyDAO;
+import org.splat.dal.dao.som.ValidationCycleDAO;
+import org.splat.exception.BusinessException;
+import org.splat.exception.InvalidParameterException;
+import org.splat.i18n.I18nUtils;
 import org.splat.kernel.InvalidPropertyException;
 import org.splat.kernel.MismatchException;
 import org.splat.kernel.MissedPropertyException;
@@ -43,15 +55,19 @@ import org.splat.kernel.NotApplicableException;
 import org.splat.log.AppLogger;
 import org.splat.service.DocumentTypeService;
 import org.splat.service.KnowledgeElementTypeService;
+import org.splat.service.ProjectElementService;
 import org.splat.service.PublicationService;
 import org.splat.service.ScenarioService;
 import org.splat.service.SimulationContextService;
 import org.splat.service.StepService;
+import org.splat.service.StudyService;
 import org.splat.service.dto.DocumentDTO;
 import org.splat.service.dto.FileDTO;
+import org.splat.service.dto.ScenarioDTO;
 import org.splat.service.dto.StepDTO;
 import org.splat.service.technical.ProjectSettingsService;
 import org.splat.service.technical.RepositoryService;
+import org.splat.service.technical.StepsConfigService;
 import org.splat.service.technical.ProjectSettingsService.Step;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.beans.factory.annotation.Qualifier;
@@ -61,6 +77,7 @@ import org.testng.annotations.Test;
 import org.testng.reporters.Files;
 
 import test.splat.common.BaseTest;
+import test.splat.util.TestEntitiesGenerator;
 
 /**
  * Test class for ScenarioService.
@@ -125,6 +142,13 @@ public class TestScenarioService extends BaseTest {
        @Qualifier("projectSettings")
        private transient ProjectSettingsService _projectSettings;
 
+       /**
+        * The StepsConfigService. Later injected by Spring.
+        */
+       @Autowired
+       @Qualifier("stepsConfigService")
+       private transient StepsConfigService _stepsConfigService;
+
        /**
         * The DocumentTypeService. Later injected by Spring.
         */
@@ -139,6 +163,41 @@ public class TestScenarioService extends BaseTest {
        @Qualifier("knowledgeElementTypeService")
        private transient KnowledgeElementTypeService _knowledgeElementTypeService;
 
+       /**
+        * The UserDAO. Later injected by Spring.
+        */
+       @Autowired
+       @Qualifier("userDAO")
+       private transient UserDAO _userDAO;
+
+       /**
+        * The StudyService. Later injected by Spring.
+        */
+       @Autowired
+       @Qualifier("studyService")
+       private transient StudyService _studyService;
+
+       /**
+        * The StudyDAO. Later injected by Spring.
+        */
+       @Autowired
+       @Qualifier("studyDAO")
+       private transient StudyDAO _studyDAO;
+
+       /**
+        * The ValidationCycleDAO. Later injected by Spring.
+        */
+       @Autowired
+       @Qualifier("validationCycleDAO")
+       private transient ValidationCycleDAO _validationCycleDAO;
+
+       /**
+        * The ProjectElementService. Later injected by Spring.
+        */
+       @Autowired
+       @Qualifier("projectElementService")
+       private transient ProjectElementService _projectElementService;
+
        /**
         * Test of getting a scenario content for building siman-salome.conf.<BR>
         * <B>Description :</B> <BR>
@@ -184,7 +243,7 @@ public class TestScenarioService extends BaseTest {
                Assert.assertNotNull(steps, "List of steps must not be null.");
                Assert.assertTrue(steps.size() > 0, "No steps are read.");
 
-               List<Step> projSteps = _projectSettings.getStepsOf(Scenario.class);
+               List<Step> projSteps = _stepsConfigService.getStepsOf(Scenario.class);
                Assert.assertEquals(steps.size(), projSteps.size(),
                                "Not all steps are listed.");
                int docIndex = 0;
@@ -342,8 +401,7 @@ public class TestScenarioService extends BaseTest {
                startNestedTransaction();
 
                _projectSettings.getAllSteps().clear(); // Clear config to be able to load it again
-               _projectSettings.configure(ClassLoader
-                               .getSystemResource("test/som.xml").getPath());
+               _projectSettings.configure("classpath:test/som.xml");
                getHibernateTemplate().flush();
                long scenarioId = createScenario();
                Scenario aScen = _scenarioDAO.get(scenarioId);
@@ -351,15 +409,48 @@ public class TestScenarioService extends BaseTest {
                long userId = user.getIndex();
 
                // ////////////////////////////////////////////////////////
-               // Call checkin method for good prepared transient data.
+               // Call checkin method for empty list of modules.
 
                // Simulate checkout
                List<StepDTO> steps = _scenarioService.getScenarioInfo(scenarioId);
                _scenarioService.checkout(aScen, user);
+               _scenarioDAO.flush();
+               // Check that scenario is no more marked as checked out
+               aScen = _scenarioDAO.get(scenarioId);
+               Assert.assertTrue(aScen.isCheckedout(),
+                               "Scenario is not marked as checked out after checkout.");
 
                // Prepare test data for checkin
                // Checkin only two first steps (geom and mesh)
                List<StepDTO> stepsToCheckin = new ArrayList<StepDTO>();
+               // Do test checkin
+               _scenarioService.checkin(scenarioId, userId, stepsToCheckin);
+
+               _scenarioDAO.flush();
+               // Check that scenario is no more marked as checked out
+               aScen = _scenarioDAO.get(scenarioId);
+               Assert.assertFalse(aScen.isCheckedout(),
+                               "Scenario is still marked as checked out after checkin.");
+
+               // ////////////////////////////////////////////////////////
+               // Call checkin method for good prepared transient data.
+
+               // Simulate checkout
+               steps = _scenarioService.getScenarioInfo(scenarioId);
+               _scenarioService.checkout(aScen, user);
+
+               // Remember modification dates of all attached files
+               Map<Long, Date> dates = new HashMap<Long, Date>();
+               for (Publication p : aScen.getDocums()) {
+                       for (Relation r : p.value().getRelations(ConvertsRelation.class)) {
+                               org.splat.dal.bo.som.File attach = ((ConvertsRelation) r)
+                                               .getTo();
+                               dates.put(attach.getIndex(), attach.getDate());
+                       }
+               }
+
+               // Prepare test data for checkin
+               // Checkin only two first steps (geom and mesh)
                for (StepDTO step : steps) {
                        // Prepare GEOM: checkin actual brep
                        StepDTO stepToCheckin = createDocDTOForModule(null, "GEOM", "brep",
@@ -375,8 +466,8 @@ public class TestScenarioService extends BaseTest {
                aScen = _scenarioDAO.get(scenarioId);
                Assert.assertFalse(aScen.isCheckedout(),
                                "Scenario is still marked as checked out after checkin.");
+               boolean modifDatesChecked = false;
                // Check that new document versions are created for checked in documents
-               boolean caseFound = false;
                for (StepDTO step : stepsToCheckin) {
                        for (DocumentDTO docDTO : step.getDocs()) {
                                if ((docDTO.getId() != 0) && (docDTO.getId() != null)) {
@@ -415,18 +506,21 @@ public class TestScenarioService extends BaseTest {
                                                Assert.assertFalse(aScen.publishes(prevDoc));
                                                // Check that presentation of the previous version is removed
                                                checkFiles(docDTO, newPub);
-                                               
+
                                                // Formats of files are new if they are according to the document's type on the study step
                                                if ("py".equals(prevDoc.getFormat())
-                                                               && "geometry".equals(prevDoc.getType().getName())) {
-                                                       Assert.assertEquals(newPub.value().getFormat(), "brep");
-                                                       Assert.assertEquals(newPub.getSourceFile().getFormat(),
+                                                               && "geometry".equals(prevDoc.getType()
+                                                                               .getName())) {
+                                                       Assert.assertEquals(newPub.value().getFormat(),
                                                                        "brep");
+                                                       Assert.assertEquals(newPub.getSourceFile()
+                                                                       .getFormat(), "brep");
                                                        Assert.assertEquals(newPub.getSourceFile()
                                                                        .getRelativePath().substring(
                                                                                        newPub.getSourceFile()
-                                                                                                       .getRelativePath().lastIndexOf(
-                                                                                                                       '.') + 1), "brep");
+                                                                                                       .getRelativePath()
+                                                                                                       .lastIndexOf('.') + 1),
+                                                                       "brep");
                                                }
 
                                                // Check that uses relations are copied correctly
@@ -443,7 +537,8 @@ public class TestScenarioService extends BaseTest {
                                                                        if ((lastPub.value().getPreviousVersion() != null)
                                                                                        && (lastPub.value()
                                                                                                        .getPreviousVersion()
-                                                                                                       .getIndex() == used.getIndex())) {
+                                                                                                       .getIndex() == used
+                                                                                                       .getIndex())) {
                                                                                toBeUsed = lastPub;
                                                                                break;
                                                                        }
@@ -467,7 +562,6 @@ public class TestScenarioService extends BaseTest {
                                                                                                + using.getTitle() + " ("
                                                                                                + using.getType().getName()
                                                                                                + ") must become outdated.");
-                                                               caseFound = true;
                                                        }
                                                }
                                        } else {
@@ -482,10 +576,33 @@ public class TestScenarioService extends BaseTest {
                                                Assert.assertTrue(attFile.asFile().exists(), "File "
                                                                + docDTO.getFiles().get(0).getPath()
                                                                + " attached to the document "
-                                                               + docDTO.getTitle() + "#" + docDTO.getId() + " doesn't exist");
+                                                               + docDTO.getTitle() + "#" + docDTO.getId()
+                                                               + " doesn't exist");
+                                               LOG.debug("Source format: " + curDoc.getFormat()
+                                                               + ", new format: " + newFormat);
+                                               // Check that attachment with the same format is not duplicated.
+                                               int attachNb = 0;
+                                               for (Relation conv : curDoc
+                                                               .getRelations(ConvertsRelation.class)) {
+                                                       if (newFormat.equals(((ConvertsRelation) conv)
+                                                                       .getTo().getFormat())) {
+                                                               attachNb++;
+                                                       }
+                                               }
+                                               Assert
+                                                               .assertEquals(attachNb, 1,
+                                                                               "Attachment with the same format must be only one.");
+
+                                               // Check that the attached file date is updated
+                                               if (dates.containsKey(attFile.getIndex())) {
+                                                       Assert
+                                                                       .assertTrue(attFile.getDate().compareTo(
+                                                                                       dates.get(attFile.getIndex())) > 0,
+                                                                                       "Attachment modification date is not updated.");
+                                                       modifDatesChecked = true;
+                                               }
                                        }
 
-
                                } else {
                                        // Check that new documents are created for new data
                                        boolean found = false;
@@ -537,8 +654,11 @@ public class TestScenarioService extends BaseTest {
                                }
                        }
                }
-               Assert.assertTrue(caseFound,
-                               "Not checked in dependent documents must become outdated.");
+
+               Assert
+                               .assertTrue(
+                                               modifDatesChecked,
+                                               "No modification date is checked because no files were attached when attachment with same extension already exists.");
 
                // ///////////////////////////////////////////////////////////
                // Call checkin method for a not existing id.
@@ -647,8 +767,8 @@ public class TestScenarioService extends BaseTest {
                                                        doc.getId(), doc.getTitle());
                                        for (FileDTO file : doc.getFiles()) {
                                                if (file.getPath().endsWith(format)
-                                                               || (file.getPath().endsWith("py") && format
-                                                                               .equals("brep"))) {
+                                                               || (file.getPath().endsWith("py") && (format
+                                                                               .equals("brep") || format.equals("med")))) {
                                                        // Create a file in the download directory
                                                        docToCheckin.addFile(createDownloadedFile(userId,
                                                                        doc.getTitle() + "_result", format));
@@ -705,6 +825,23 @@ public class TestScenarioService extends BaseTest {
                return new FileDTO(filePath);
        }
 
+       /**
+        * Create a file.
+        * 
+        * @param fname
+        *            file name
+        * @throws IOException
+        *             if file creation failed
+        */
+       private void createFile(final String fname) throws IOException {
+               // Create a file in the download directory
+               LOG.debug("Create file: " + fname);
+               String filePath = fname;
+               FileWriter fw = new FileWriter(filePath);
+               fw.write("Simulation of " + fname + " data file at " + new Date());
+               fw.close();
+       }
+
        /**
         * Get path to the user's downloads directory. The directory is created if it is not exist yet.
         * 
@@ -749,12 +886,11 @@ public class TestScenarioService extends BaseTest {
                _projectSettings.getAllSteps().clear(); // Clear config to be able to load it again
                // Load workflow customization
                try {
-                       _projectSettings.configure(ClassLoader.getSystemResource(
-                                       "test/som.xml").getPath());
+                       _projectSettings.configure("classpath:test/som.xml");
                } catch (FileNotFoundException e) {
                        Assert.fail("Can't find som.xml: ", e);
                }
-               List<Step> steps = _projectSettings.getStepsOf(Scenario.class);
+               List<Step> steps = _stepsConfigService.getStepsOf(Scenario.class);
                Assert.assertTrue(steps.size() > 0, "No steps are created.");
 
                // Create a test user
@@ -800,11 +936,10 @@ public class TestScenarioService extends BaseTest {
                                // <source-file>.brep
                                // <attached-file>.med
                                dprop.setName("document" + i++).setType(dtype);
-                               if (step.getNumber() > 3) {
-                                       dprop.setFormat("med");
-                               } else {
-                                       dprop.setFormat("py");
-                               }
+                               /*
+                                * if (step.getNumber() > 3) { dprop.setFormat("med"); } else {
+                                */dprop.setFormat("py");
+                               // }
                                dprop.setLocalPath(dprop.getName() + "." + dprop.getFormat());
                                Publication pub = createDoc(aScenario, aScStep, dprop, "med",
                                                false);
@@ -946,65 +1081,41 @@ public class TestScenarioService extends BaseTest {
        }
 
        /**
-        * Test check-in scenario operation to be performed after SALOME session.<BR>
+        * Test study creation.<BR>
         * <B>Description :</B> <BR>
-        * <i>Create a scenario and try to check-in it with some simulated SALOME results data.<BR>
-        * After check-in verify following points:
-        * <ul>
-        * <li>scenario is no more marked as checked out</li>
-        * <li>new document versions are created for checked in documents</li>
-        * <li>presentation of the previous version is removed</li>
-        * <li>uses relations are copied correctly</li>
-        * <li>files are moved correctly</li>
-        * <li>new documents are created for new data</li>
-        * <li>uses relations are created correctly</li>
-        * <li>files are moved correctly</li>
-        * </ul>
-        * </i><BR>
+        * <i>Create a study.</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>
+        * <i>1. call the method for a not existing product.</i><BR>
+        * <i>2. call the method for an existing username and an existing product.</i><BR>
+        * <i>3. call the method for a not existing username expecting an exception.</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>
+        * <li>1: The new study must be created. The new product simulation context must be created.</li>
+        * <li>2: The new study must be created.</li>
+        * <li>3: The new study must not be created. Exception must be thrown.</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
+        *             if application configuration loading is failed
         * @throws SQLException
-        *             if scenario creation is failed
-        * @throws NotApplicableException
-        *             if checkin failed
-        * @throws MismatchException
-        *             if checkin failed
+        *             if application configuration loading is failed
+        * @throws BusinessException
+        *             if test data creation is failed
         */
        @Test(groups = { "study", "sevice", "functional", "business" })
-       public void testCreateStudy() throws InvalidPropertyException,
-                       MissedPropertyException, MultiplyDefinedException, IOException,
-                       SQLException, MismatchException, NotApplicableException {
+       public void testCreateStudy() throws BusinessException, IOException,
+                       SQLException {
                LOG.debug(">>>>> BEGIN testCreateStudy()");
                startNestedTransaction();
 
                Database.getInstance().reset();
                _projectSettings.getAllSteps().clear(); // Clear config to be able to load it again
-               _projectSettings.configure(ClassLoader
-                               .getSystemResource("test/som.xml").getPath());
+               _projectSettings.configure("classpath:test/som.xml");
 
                // Create a test user
                User.Properties uprop = new User.Properties();
@@ -1049,7 +1160,651 @@ public class TestScenarioService extends BaseTest {
                                .setValue("Test Simulation Context: Product");
                Study study = _scenarioService.createStudy(sprop, oprop, cprop);
 
+               Assert.assertNotNull(study);
+               Assert.assertTrue(study.getIndex() > 0);
+
                rollbackNestedTransaction();
                LOG.debug(">>>>> END testCreateStudy()");
        }
+
+       /**
+        * Test study creation.<BR>
+        * <B>Description :</B> <BR>
+        * <i>Create a study.</i><BR>
+        * <B>Action : </B><BR>
+        * <i>1. call the method for a not existing product.</i><BR>
+        * <i>2. call the method for an existing username and an existing product.</i><BR>
+        * <i>3. call the method for a not existing username expecting an exception.</i><BR>
+        * <B>Test data : </B><BR>
+        * <i>no input parameters</i><BR>
+        * 
+        * <B>Outcome results:</B><BR>
+        * <i>
+        * <ul>
+        * <li>1: The new study must be created. The new product simulation context must be created.</li>
+        * <li>2: The new study must be created.</li>
+        * <li>3: The new study must not be created. Exception must be thrown.</li>
+        * </ul>
+        * </i>
+        * 
+        * @throws IOException
+        *             if application configuration loading is failed
+        * @throws SQLException
+        *             if application configuration loading is failed
+        * @throws BusinessException
+        *             if test data creation is failed
+        */
+       @Test(groups = { "study", "sevice", "functional", "business" })
+       public void testCreateStudyFromPython() throws IOException, SQLException,
+                       BusinessException {
+               LOG.debug(">>>>> BEGIN testCreateStudyFromPython()");
+               startNestedTransaction();
+
+               HibernateTemplate ht = getHibernateTemplate();
+
+               Database.getInstance().reset();
+               _projectSettings.getAllSteps().clear(); // Clear config to be able to load it again
+               _projectSettings.configure("classpath:test/som.xml");
+
+               // Create a test user
+               User goodUser = TestEntitiesGenerator.getTestUser("goodUser");
+               _userDAO.create(goodUser);
+               SimulationContextType prodtype = _simulationContextService
+                               .selectType("product");
+               Assert
+                               .assertNotNull(prodtype,
+                                               "Simulation context type 'product' must be created in the database.");
+
+               String productName = "New Test Product " + new Date().toString();
+
+               ht.flush();
+               ht.clear();
+               long studyId1 = _scenarioService.createStudy("goodUser",
+                               "Test Study 1", productName, "Test description");
+               Assert.assertTrue(studyId1 > 0);
+
+               ht.flush();
+               ht.clear();
+               try {
+                       _scenarioService.createStudy("badbadUser", "Test Study 2",
+                                       productName, "Test description");
+                       Assert.fail("Study must not be created for not existing user.");
+               } catch (InvalidPropertyException ipe) {
+                       LOG.debug("Expected exception: " + ipe.getMessage());
+               }
+
+               ht.flush();
+               ht.clear();
+               long studyId3 = _scenarioService.createStudy("goodUser",
+                               "Test Study 3", productName, "Test description");
+               Assert.assertTrue(studyId3 > 0);
+
+               // Check that the simulation context is the same
+               Study study1 = _studyService.selectStudy(studyId1);
+               Study study3 = _studyService.selectStudy(studyId3);
+               Assert.assertEquals(study1.SimulationContextIterator().next(), study3
+                               .SimulationContextIterator().next());
+
+               // Check the title of the created scenario
+               String scTitle = study1.getScenarii()[0].getTitle();
+               Assert.assertEquals(scTitle, I18nUtils
+                               .getMessageLocaleDefault("label.scenario")
+                               + " 1");
+               Assert.assertFalse(scTitle.equals("label.scenario 1"));
+
+               rollbackNestedTransaction();
+               LOG.debug(">>>>> END testCreateStudyFromPython()");
+       }
+
+       /**
+        * Test study content copy.<BR>
+        * <B>Description :</B> <BR>
+        * <i>Create a study.</i><BR>
+        * <B>Action : </B><BR>
+        * <i>1. call the method for a not existing source study.</i><BR>
+        * <i>2. call the method for a not existing source scenario with not evolving step.</i><BR>
+        * <i>3. call the method for a not existing source scenario with evolving step.</i><BR>
+        * <i>4. call the method for an existing source scenario with evolving step.</i><BR>
+        * <B>Test data : </B><BR>
+        * <i>no input parameters</i><BR>
+        * 
+        * <B>Outcome results:</B><BR>
+        * <i>
+        * <ul>
+        * <li>1: Exception must be thrown.</li>
+        * <li>2: The study content must be copied.</li>
+        * <li>3: Exception must be thrown.</li>
+        * <li>4: The study content must be copied.</li>
+        * </ul>
+        * </i>
+        * 
+        * @throws IOException
+        *             if application configuration loading is failed
+        * @throws SQLException
+        *             if application configuration loading is failed
+        * @throws BusinessException
+        *             if test data creation is failed
+        */
+       @Test(groups = { "study", "sevice", "functional", "business" })
+       public void testCopyStudyContent() throws IOException, SQLException,
+                       BusinessException {
+               LOG.debug(">>>>> BEGIN testCopyStudyContent()");
+               startNestedTransaction();
+
+               HibernateTemplate ht = getHibernateTemplate();
+
+               Database.getInstance().reset();
+               _projectSettings.getAllSteps().clear(); // Clear config to be able to load it again
+               _projectSettings.configure("classpath:test/som.xml");
+
+               User goodUser = TestEntitiesGenerator.getTestUser("GoodUser");
+               _userDAO.create(goodUser);
+               User otherUser = TestEntitiesGenerator.getTestUser("otherUser");
+               _userDAO.create(otherUser);
+
+               // Create private study
+               Study aStudy = TestEntitiesGenerator.getTestStudy(goodUser);
+               aStudy.setTitle("0.This is private study");
+               Long studyId = _studyDAO.create(aStudy);
+
+               // Add a scenario to the study
+               Scenario scen = TestEntitiesGenerator.getTestScenario(aStudy);
+               _scenarioDAO.create(scen);
+               ht.flush();
+               // Add a second scenario to the study
+               scen = TestEntitiesGenerator.getTestScenario(aStudy);
+               Long aScenId = _scenarioDAO.create(scen);
+               ht.flush();
+
+               // Add a validation cycle with otherUser as a reviewer
+               ValidationCycle.Properties vprop = new ValidationCycle.Properties();
+               DocumentType dtype = _documentTypeService.selectType("minutes");
+               vprop.setDocumentType(dtype);
+               vprop.setActor(ValidationStep.REVIEW, otherUser);
+               ValidationCycle cycle = new ValidationCycle(aStudy, vprop);
+               _validationCycleDAO.create(cycle);
+               ValidationCycleRelation link = cycle.getContext();
+               aStudy.addRelation(link);
+               ht.flush();
+
+               // Add documents to the first study activity
+               // Add a converts relations
+               Map<Integer, org.splat.som.Step> stSteps = _projectElementService
+                               .getStepsMap(aStudy);
+               org.splat.som.Step aStep = stSteps.get(1);
+               Publication pub1 = addDoc(aStudy, aStep, "document1", dtype);
+               Publication pub2 = addDoc(aStudy, aStep, "document2", dtype);
+               Publication pub3 = addDoc(aStudy, aStep, "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);
+               //
+               // 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
+               Map<Integer, org.splat.som.Step> scSteps = _projectElementService
+                               .getStepsMap(scen);
+               aStep = scSteps.get(2);
+               Publication spub1 = addDoc(scen, aStep, "sdocument1", dtype);
+               Publication spub2 = addDoc(scen, aStep, "sdocument2", dtype);
+               Publication spub3 = addDoc(scen, aStep, "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();
+
+               // Create target study1
+               Study aStudy1 = TestEntitiesGenerator.getTestStudy(goodUser);
+               aStudy1.setTitle("1.This is a target study1");
+               aStudy1.setReference("tst1");
+               Long studyId1 = _studyDAO.create(aStudy1);
+
+               // Add a scenario to the study
+               Scenario scen1 = TestEntitiesGenerator.getTestScenario(aStudy1);
+               _scenarioDAO.create(scen1);
+               ht.flush();
+
+               // Create target study2
+               Study aStudy2 = TestEntitiesGenerator.getTestStudy(goodUser);
+               aStudy2.setTitle("2.This is a target study2");
+               aStudy2.setReference("tst2");
+               Long studyId2 = _studyDAO.create(aStudy2);
+
+               // Add a scenario to the study
+               Scenario scen2 = TestEntitiesGenerator.getTestScenario(aStudy2);
+               _scenarioDAO.create(scen2);
+               ht.flush();
+               ht.clear();
+
+               // //////////////////// TEST CALL /////////////////////////////////////
+               // 1. call the method for a not existing source study.
+               try {
+                       _scenarioService.copyStudyContent(-1, -1, -1, -1);
+                       Assert.fail("Exception must be thrown for not existing study id.");
+               } catch (InvalidParameterException e) {
+                       LOG.debug("Expected exception: " + e.getClass().getSimpleName()
+                                       + ": " + e.getMessage());
+               }
+
+               ht.flush();
+               ht.clear();
+
+               // 2. call the method for a not existing source scenario with not evolving step.
+               _scenarioService.copyStudyContent(studyId, -1, 1, studyId1);
+
+               ht.flush();
+               ht.clear();
+
+               aStudy = _studyService.selectStudy(studyId);
+               aStudy1 = _studyService.selectStudy(studyId1);
+               for (Publication pub : aStudy.getDocums()) {
+                       // Find the same document in the created copy of the study
+                       Publication found = null;
+                       for (Publication newPub : aStudy1.getDocums()) {
+                               if (pub.value().getTitle().equals(newPub.value().getTitle())
+                                               && pub.value().getType().equals(
+                                                               newPub.value().getType())) {
+                                       found = newPub;
+                                       break;
+                               }
+                       }
+                       Assert.assertNotNull(found, "The document "
+                                       + pub.value().getTitle() + "is not copied");
+                       // Check that all files are copied (source and attached)
+               }
+
+               // 3. call the method for a not existing source scenario with evolving step.
+               try {
+                       _scenarioService.copyStudyContent(studyId, -1, 2, studyId2);
+                       Assert
+                                       .fail("Exception must be thrown for not existing scenario id and evolving step.");
+               } catch (InvalidParameterException e) {
+                       LOG.debug("Expected exception: " + e.getClass().getSimpleName()
+                                       + ": " + e.getMessage());
+               }
+
+               ht.flush();
+               ht.clear();
+
+               // 4. call the method for an existing source scenario with evolving step.
+               _scenarioService.copyStudyContent(studyId, aScenId, 9, studyId2);
+               ht.flush();
+
+               rollbackNestedTransaction();
+               LOG.debug(">>>>> END testCopyStudyContent()");
+       }
+
+       /**
+        * Create a document and publish it in the project element.
+        * 
+        * @param aProjElem
+        *            the project element
+        * @param aStep
+        *            the project element step
+        * @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 aProjElem,
+                       final org.splat.som.Step aStep, final String docname,
+                       final DocumentType dtype) throws BusinessException, IOException {
+               HibernateTemplate ht = getHibernateTemplate();
+               // Add documents to the study activity
+               Document.Properties dprop = new Document.Properties().setAuthor(
+                               aProjElem.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);
+               aProjElem.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"));
+               String filepath = pub.getSourceFile().asFile().getAbsolutePath();
+               createFile(filepath);
+               createFile(filepath.substring(0, filepath.lastIndexOf(".")) + ".med");
+               return pub;
+       }
+
+       /**
+        * 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;
+       }
+
+       /**
+        * Test assigning a simulation context to a study.<BR>
+        * <B>Description :</B> <BR>
+        * <i>Create a study and assign a simulation context to it.</i><BR>
+        * <B>Action : </B><BR>
+        * <i>1. call the method for not existing study id.</i><BR>
+        * <i>2. call the method for not existing context type and context value.</i><BR>
+        * <i>3. call the method for existing context type and context value.</i><BR>
+        * <i>4. call the method for existing context type and not existing context value.</i><BR>
+        * <i>5. call the method for empty context type.</i><BR>
+        * <i>6. call the method for empty context value.</i><BR>
+        * <B>Test data : </B><BR>
+        * <i>no input parameters</i><BR>
+        * 
+        * <B>Outcome results:</B><BR>
+        * <i>
+        * <ul>
+        * <li>1: Exception must be thrown.</li>
+        * <li>2: The new context type and value must be created. The new context must be assigned to the study first step.</li>
+        * <li>3: The existing context must be assigned to the study first step.</li>
+        * <li>4: The new context value must be created. The new context must be assigned to the study first step.</li>
+        * <li>5: Exception must be thrown.</li>
+        * <li>6: Exception must be thrown.</li>
+        * </ul>
+        * </i>
+        * 
+        * @throws IOException
+        *             if application configuration loading is failed
+        * @throws SQLException
+        *             if application configuration loading is failed
+        * @throws BusinessException
+        *             if test data creation is failed
+        */
+       @Test(groups = { "study", "sevice", "functional", "business" })
+       public void testAssignStudyContextFromPython() throws IOException,
+                       SQLException, BusinessException {
+               LOG.debug(">>>>> BEGIN testAssignStudyContextFromPython()");
+               startNestedTransaction();
+
+               HibernateTemplate ht = getHibernateTemplate();
+
+               Database.getInstance().reset();
+               _projectSettings.getAllSteps().clear(); // Clear config to be able to load it again
+               _projectSettings.configure("classpath:test/som.xml");
+
+               // Create a test user
+               User goodUser = TestEntitiesGenerator.getTestUser("goodUser");
+               _userDAO.create(goodUser);
+               SimulationContextType prodtype = _simulationContextService
+                               .selectType("product");
+               Assert
+                               .assertNotNull(prodtype,
+                                               "Simulation context type 'product' must be created in the database.");
+
+               String productName = "New Test Product " + new Date().toString();
+
+               ht.flush();
+               ht.clear();
+               long studyId1 = _scenarioService.createStudy("goodUser",
+                               "Test Study 1", productName, "Test description");
+               Assert.assertTrue(studyId1 > 0);
+
+               ht.flush();
+               ht.clear();
+
+               // //////// START OF TESTS
+               // 1. call the method for not existing study id.</i><BR>
+               try {
+                       _scenarioService.assignStudyContext(-1L, "new context type",
+                                       "new context value");
+                       Assert.fail("Not existing study must not be found.");
+               } catch (InvalidPropertyException ipe) {
+                       LOG.debug("Expected exception: " + ipe.getMessage());
+               }
+
+               // 2. call the method for not existing context type and context value.</i><BR>
+               _scenarioService.assignStudyContext(studyId1, "new context type",
+                               "new context value");
+
+               ht.flush();
+               ht.clear();
+
+               // Check the assigned simulation context
+               checkCtx(studyId1, "new context type", "new context value");
+
+               // 3. call the method for existing context type and context value.</i><BR>
+               _scenarioService.assignStudyContext(studyId1, "new context type",
+                               "new context value");
+
+               ht.flush();
+               ht.clear();
+
+               // Check the assigned simulation context
+               checkCtx(studyId1, "new context type", "new context value");
+
+               // 4. call the method for existing context type and not existing context value.</i><BR>
+               _scenarioService.assignStudyContext(studyId1, "new context type",
+                               "new context value1");
+
+               ht.flush();
+               ht.clear();
+
+               // Check the assigned simulation context
+               checkCtx(studyId1, "new context type", "new context value1");
+
+               // 5. call the method for empty context type.</i><BR>
+               try {
+                       _scenarioService.assignStudyContext(studyId1, "",
+                                       "new context value");
+                       Assert.fail("Empty context type name must be forbidden.");
+               } catch (InvalidPropertyException ipe) {
+                       LOG.debug("Expected exception: " + ipe.getMessage());
+               }
+               // 6. call the method for empty context value.</i><BR>
+               try {
+                       _scenarioService.assignStudyContext(studyId1, "new context type",
+                                       "");
+                       Assert.fail("Empty context value must be forbidden.");
+               } catch (InvalidPropertyException ipe) {
+                       LOG.debug("Expected exception: " + ipe.getMessage());
+               }
+
+               rollbackNestedTransaction();
+               LOG.debug(">>>>> END testAssignStudyContextFromPython()");
+       }
+
+       /**
+        * Test getting a study scenarios DTO list.<BR>
+        * <B>Description :</B> <BR>
+        * <i>Create a study and get its scenarios DTO list.</i><BR>
+        * <B>Action : </B><BR>
+        * <i>1. call the method for not existing study id.</i><BR>
+        * <i>2. call the method for a study with one scenario.</i><BR>
+        * <i>3. call the method for a study with several scenarios.</i><BR>
+        * <B>Test data : </B><BR>
+        * <i>no input parameters</i><BR>
+        * 
+        * <B>Outcome results:</B><BR>
+        * <i>
+        * <ul>
+        * <li>1: The returned list of DTO must be empty.</li>
+        * <li>2: The returned list of DTO must contain one scenario DTO.</li>
+        * <li>3: The returned list of DTO must contain several scenario DTOs.</li>
+        * </ul>
+        * </i>
+        * 
+        * @throws IOException
+        *             if application configuration loading is failed
+        * @throws SQLException
+        *             if application configuration loading is failed
+        * @throws BusinessException
+        *             if test data creation is failed
+        */
+       @Test(groups = { "study", "sevice", "functional", "business" })
+       public void testGetStudyScenarios() throws IOException, SQLException,
+                       BusinessException {
+               LOG.debug(">>>>> BEGIN testGetStudyScenarios()");
+               startNestedTransaction();
+
+               HibernateTemplate ht = getHibernateTemplate();
+
+               Database.getInstance().reset();
+               _projectSettings.getAllSteps().clear(); // Clear config to be able to load it again
+               _projectSettings.configure("classpath:test/som.xml");
+
+               // Create a test user
+               User goodUser = TestEntitiesGenerator.getTestUser("goodUser");
+               _userDAO.create(goodUser);
+               Study study = TestEntitiesGenerator.getTestStudy(goodUser);
+               long studyId1 = _studyDAO.create(study);
+               ht.flush();
+               Scenario scen = TestEntitiesGenerator.getTestScenario(study,
+                               "test scen11");
+               long id11 = _scenarioDAO.create(scen);
+               ht.flush();
+               study = TestEntitiesGenerator.getTestStudy(goodUser);
+               long studyId2 = _studyDAO.create(study);
+               ht.flush();
+               scen = TestEntitiesGenerator.getTestScenario(study, "test scen21");
+               long id21 = _scenarioDAO.create(scen);
+               ht.flush();
+               scen = TestEntitiesGenerator.getTestScenario(study, "test scen22");
+               long id22 = _scenarioDAO.create(scen);
+               ht.flush();
+               scen = TestEntitiesGenerator.getTestScenario(study, "test scen23");
+               long id23 = _scenarioDAO.create(scen);
+               ht.flush();
+               ht.clear();
+
+               // //////// START OF TESTS
+               // 1. call the method for not existing study id.
+               List<ScenarioDTO> scens = _scenarioService.getStudyScenarios(-1L);
+
+               Assert.assertNotNull(scens);
+               Assert.assertTrue(scens.isEmpty());
+
+               // 2. call the method for a study with one scenario.
+               scens = _scenarioService.getStudyScenarios(studyId1);
+
+               ht.flush();
+               ht.clear();
+               Assert.assertNotNull(scens);
+               Assert.assertEquals(scens.size(), 1);
+               Assert.assertEquals(scens.get(0).getIndex().longValue(), id11);
+               Assert.assertEquals(scens.get(0).getTitle(), "test scen11");
+
+               // 3. call the method for a study with several scenarios.
+               scens = _scenarioService.getStudyScenarios(studyId2);
+               Assert.assertEquals(scens.size(), 3);
+               Assert.assertEquals(scens.get(0).getIndex().longValue(), id21);
+               Assert.assertEquals(scens.get(0).getTitle(), "test scen21");
+               Assert.assertEquals(scens.get(1).getIndex().longValue(), id22);
+               Assert.assertEquals(scens.get(1).getTitle(), "test scen22");
+               Assert.assertEquals(scens.get(2).getIndex().longValue(), id23);
+               Assert.assertEquals(scens.get(2).getTitle(), "test scen23");
+
+               ht.flush();
+               ht.clear();
+
+               rollbackNestedTransaction();
+               LOG.debug(">>>>> END testGetStudyScenarios()");
+       }
+
+       /**
+        * Check if the context is assigned to the study.
+        * 
+        * @param studyId1
+        *            the study id
+        * @param ctxType
+        *            the context type name
+        * @param ctxValue
+        *            the context value
+        */
+       private void checkCtx(final long studyId1, final String ctxType,
+                       final String ctxValue) {
+               // Check the assigned simulation context
+               Study study1 = _studyService.selectStudy(studyId1);
+               Iterator<SimulationContext> it = study1.SimulationContextIterator();
+               SimulationContext ctx;
+               boolean isFound = false;
+               while ((!isFound) && it.hasNext()) {
+                       ctx = it.next();
+                       isFound = ctx.getType().getName().equals(ctxType)
+                                       && ctx.getValue().equals(ctxValue);
+               }
+               Assert.assertTrue(isFound, "Context must be assigned to the study.");
+       }
 }