- /**
- * Logger for the class.
- */
- private static final AppLogger LOG = AppLogger
- .getLogger(TestScenarioService.class);
-
- /**
- * The tested ScenarioService. Later injected by Spring.
- */
- @Autowired
- @Qualifier("scenarioService")
- private transient ScenarioService _scenarioService;
-
- /**
- * The RepositoryService. Later injected by Spring.
- */
- @Autowired
- @Qualifier("repositoryService")
- private transient RepositoryService _repositoryService;
-
- /**
- * The Scenario DAO. Later injected by Spring.
- */
- @Autowired
- @Qualifier("scenarioDAO")
- private transient ScenarioDAO _scenarioDAO;
-
- /**
- * The PublicationService. Later injected by Spring.
- */
- @Autowired
- @Qualifier("publicationService")
- private transient PublicationService _publicationService;
-
- /**
- * The StepService. Later injected by Spring.
- */
- @Autowired
- @Qualifier("stepService")
- private transient StepService _stepService;
-
- /**
- * The SimulationContextService. Later injected by Spring.
- */
- @Autowired
- @Qualifier("simulationContextService")
- private transient SimulationContextService _simulationContextService;
-
- /**
- * The ProjectSettingsService. Later injected by Spring.
- */
- @Autowired
- @Qualifier("projectSettings")
- private transient ProjectSettingsService _projectSettings;
-
- /**
- * The DocumentTypeService. Later injected by Spring.
- */
- @Autowired
- @Qualifier("documentTypeService")
- private transient DocumentTypeService _documentTypeService;
-
- /**
- * The KnowledgeElementTypeService. Later injected by Spring.
- */
- @Autowired
- @Qualifier("knowledgeElementTypeService")
- private transient KnowledgeElementTypeService _knowledgeElementTypeService;
-
- /**
- * Test of getting a scenario content for building siman-salome.conf.<BR>
- * <B>Description :</B> <BR>
- * <i>Create a scenario and try to get an info for it.</i><BR>
- * <B>Action : </B><BR>
- * <i>1. call the method for an existing scenario id.</i><BR>
- * <i>2. call the method for a not existing scenario id.</i><BR>
- * <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>result DTO must contain list of all documents and files<BR>
- * </li>
- * <li>Exception is thrown<BR>
- * </li>
- * </ul>
- * </i>
- *
- * @throws InvalidPropertyException
- * if an invalid property is used when creating objects
- * @throws MultiplyDefinedException
- * when trying to create an object with already existing id
- * @throws MissedPropertyException
- * if a mandatory property is not defined for an object to be created
- * @throws IOException
- * if scenario creation is failed
- * @throws SQLException
- * if scenario creation is failed
- */
- @Test(groups = { "checkout", "sevice", "functional", "business" })
- public void testGetScenarioInfo() throws InvalidPropertyException,
- MissedPropertyException, MultiplyDefinedException, IOException,
- SQLException {
- LOG.debug(">>>>> BEGIN testGetScenarioInfo()");
- startNestedTransaction();
-
- long scenarioId = createScenario();
- // Call DAO's create method for a good transient knowledge element.
- List<StepDTO> steps = _scenarioService.getScenarioInfo(scenarioId);
- 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);
- Assert.assertEquals(steps.size(), projSteps.size(),
- "Not all steps are listed.");
- int docIndex = 0;
- for (StepDTO step : steps) {
- LOG.debug("check the step " + step.getNumber() + ":\n" + step);
- Assert.assertNotNull(step, "Step DTO must not be null.");
- Assert.assertNotNull(step.getKey(), "Step name must not be null.");
- Assert.assertFalse(step.getKey().isEmpty(),
- "Step name must not empty.");
- Assert.assertTrue(step.getNumber() > 0,
- "Step number must be positive integer.");
- Assert.assertNotNull(step.getDocs(),
- "Step documents list must not be null.");
-
- Step aProjStep = null;
- for (Step projStep : projSteps) {
- if (projStep.getNumber() == step.getNumber()) {
- aProjStep = projStep;
- break;
- }
- }
-
- List<DocumentType> dtypes = _documentTypeService
- .selectTypesOf(aProjStep);
- for (DocumentType dtype : dtypes) {
- Assert.assertTrue(step.getDocs().size() > 0,
- "Step documents list must not be empty.");
- String docName = "document" + docIndex;
- for (DocumentDTO doc : step.getDocs()) {
- if (docName.equals(doc.getTitle())) {
- Assert.assertTrue(doc.getId() > 0,
- "Document id must be positive integer.");
- Assert.assertEquals(doc.getTitle(), docName);
- Assert.assertNotNull(doc.getFiles(),
- "Document files list must not be null.");
- Assert
- .assertTrue(doc.getFiles().size() > 1,
- "Document must have more then 1 attached file.");
-
- for (FileDTO file : doc.getFiles()) {
- Assert.assertNotNull(file.getPath(),
- "File path must not be null.");
- Assert.assertFalse(file.getPath().isEmpty(),
- "File path must not be empty.");
- /*
- * <mappings> <document type="geometry"> <import format="brep"/> <!-- Result Shape --> </document> <document
- * type="model"> <import format="med"/> <!-- Result mesh without input parameters --> </document> <document
- * type="loads"> <import format="c3m"/> <!-- Input data created interactively --> </document> <document
- * type="results"> <import format="med"/> <!-- Calculation results source file --> </document> </mappings>
- */
- // Check state and processing instruction
- String fileFormat = file.getPath().substring(
- file.getPath().lastIndexOf('.') + 1);
- /*
- * if (_projectSettings.doImport(dtype.getName(), fileFormat)) { Assert.assertTrue(file.isResult(), "The file
- * must be a result file."); } else { Assert.assertFalse(file.isResult(), "The file must be a source file."); }
- */if ((docIndex % 2) == 0) { // New
- Assert.assertEquals(file.getState(), 'Y',
- "File state must be actual ('Y').");
- if (_projectSettings.doImport(dtype.getName(),
- fileFormat)) {
- Assert.assertEquals(file.getProcessing(),
- "file-import",
- "File must be imported.");
- } else {
- Assert.assertEquals(file.getProcessing(),
- "file-download",
- "File must be downloaded.");
- }
- } else { // Outdated
- Assert.assertEquals(file.getState(), 'O',
- "File state must be outdated ('O').");
- Assert
- .assertEquals(file.getProcessing(),
- "file-download",
- "Outdated document should not be imported but downloaded.");
- }
- }
- }
- }
- docIndex++;
- }
- }
-
- // Call DAO's get method for a not existing id.
- try {
- steps = _scenarioService.getScenarioInfo(-1L);
- // getHibernateTemplate().flush();
- Assert
- .fail("Getting an object with not existing id must be failed.");
- } catch (Exception e) {
- LOG.debug("Expected exception is thrown: "
- + e.getClass().getSimpleName() + ": " + e.getMessage());
- }
- rollbackNestedTransaction();
- LOG.debug(">>>>> END testGetScenarioInfo()");
- }
-
- /**
- * Test check-in scenario operation to be performed after SALOME session.<BR>
- * <B>Description :</B> <BR>
- * <i>Create a scenario and try to check-in it with some simulated SALOME results data.<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>formats of files are new if they are according to the document's type on the study step</li>
- * <li>new documents are created for new data</li>
- * <li>new documents have correctly generated names</li>
- * <li>uses relations are created correctly</li>
- * <li>files are moved correctly</li>
- * </ul>
- * </i><BR>
- * <B>Action : </B><BR>
- * <i>1. call the method for an existing scenario id.</i><BR>
- * <i>2. call the method for a not existing scenario id.</i><BR>
- * <B>Test data : </B><BR>
- * <i>no input parameters</i><BR>
- * <i>no input parameters</i><BR>
- *
- * <B>Outcome results:</B><BR>
- * <i>
- * <ul>
- * <li>New version of existing documents must be created and new documents must be imported for documents with zero id. Correct
- * relations must be created.<BR>
- * </li>
- * <li>Exception is thrown<BR>
- * </li>
- * </ul>
- * </i>
- *
- * @throws InvalidPropertyException
- * if an invalid property is used when creating objects
- * @throws MultiplyDefinedException
- * when trying to create an object with already existing id
- * @throws MissedPropertyException
- * if a mandatory property is not defined for an object to be created
- * @throws IOException
- * if scenario creation is failed
- * @throws SQLException
- * if scenario creation is failed
- * @throws NotApplicableException
- * if checkin failed
- * @throws MismatchException
- * if checkin failed
- */
- @Test(groups = { "checkin", "sevice", "functional", "business" })
- public void testCheckin() throws InvalidPropertyException,
- MissedPropertyException, MultiplyDefinedException, IOException,
- SQLException, MismatchException, NotApplicableException {
- LOG.debug(">>>>> BEGIN testCheckin()");
- startNestedTransaction();
-
- _projectSettings.getAllSteps().clear(); // Clear config to be able to load it again
- _projectSettings.configure(ClassLoader
- .getSystemResource("test/som.xml").getPath());
- getHibernateTemplate().flush();
- long scenarioId = createScenario();
- Scenario aScen = _scenarioDAO.get(scenarioId);
- User user = aScen.getAuthor();
- long userId = user.getIndex();
-
-
- // ////////////////////////////////////////////////////////
- // 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);
-
- // 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",
- userId, step, stepsToCheckin);
- createDocDTOForModule(stepToCheckin, "SMESH", "med", userId, step,
- stepsToCheckin);
- }
- // 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.");
- // Check that new document versions are created for checked in documents
- for (StepDTO step : stepsToCheckin) {
- for (DocumentDTO docDTO : step.getDocs()) {
- if ((docDTO.getId() != 0) && (docDTO.getId() != null)) {
- boolean found = false;
- Document prevDoc = null;
- Document curDoc = null;
- Publication newPub = null;
- for (Publication pub : aScen.getDocums()) {
- prevDoc = pub.value().getPreviousVersion();
- if (prevDoc != null) {
- found = (prevDoc.getIndex() == docDTO.getId());
- if (found) { // Found next published version of the checked in document
- newPub = pub;
- break;
- }
- }
- if (pub.value().getIndex() == docDTO.getId()) {
- // Document version was not changed, old document is still published
- curDoc = pub.value();
- break;
- }
- }
- Assert.assertTrue(found || (curDoc != null),
- "New version or new attached file of the existing checked in document \""
- + docDTO.getTitle() + "\" (id="
- + docDTO.getId()
- + ") is not found in the scenario.");
- // If previous version is found then the format must be the same
- String newFormat = docDTO.getFiles().get(0).getPath()
- .substring(
- docDTO.getFiles().get(0).getPath()
- .lastIndexOf('.') + 1);
- if (found) {
- Assert.assertEquals(prevDoc.getFormat(), newFormat,
- "Formats of versions must be same");
- 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(),
- "brep");
- Assert.assertEquals(newPub.getSourceFile()
- .getRelativePath().substring(
- newPub.getSourceFile()
- .getRelativePath().lastIndexOf(
- '.') + 1), "brep");
- }
-
- // Check that uses relations are copied correctly
-
- // 1. Get all uses relations of the previous document version
- for (Relation rel : prevDoc
- .getRelations(UsesRelation.class)) {
- Document used = ((UsesRelation) rel).getTo();
- // 2.1. Get the latest version of the document published in this scenario
- Publication toBeUsed = aScen.getPublication(used);
- if (toBeUsed == null) {
- // Find the latest published version
- for (Publication lastPub : aScen.getDocums()) {
- if ((lastPub.value().getPreviousVersion() != null)
- && (lastPub.value()
- .getPreviousVersion()
- .getIndex() == used.getIndex())) {
- toBeUsed = lastPub;
- break;
- }
- }
- }
- if ((toBeUsed != null) && (!toBeUsed.isOutdated())) {
- // 2.2. For each used document check that its latest not outdated version
- // is used by the new checked in document version.
- checkUsesRelation(newPub, toBeUsed);
- }
- }
- // 1. Get all usedBy relations of the previous document version
- for (Relation rel : prevDoc
- .getRelations(UsedByRelation.class)) {
- Document using = ((UsedByRelation) rel).getTo();
- // Check that not checked in dependent documents became outdated
- Publication usingPub = aScen.getPublication(using);
- if (usingPub != null) { // if the document using the old version is still published
- Assert.assertTrue(usingPub.isOutdated(),
- "Not checked in dependent document "
- + using.getTitle() + " ("
- + using.getType().getName()
- + ") must become outdated.");
- }
- }
- } else {
- // Otherwise the new file format must differ from the previous one
- // and the new file must be attached to the same document
- org.splat.dal.bo.som.File attFile = curDoc
- .getAttachedFile(newFormat);
- Assert.assertNotNull(attFile, "File "
- + docDTO.getFiles().get(0).getPath()
- + " must be attached to the document "
- + docDTO.getTitle() + "#" + docDTO.getId());
- Assert.assertTrue(attFile.asFile().exists(), "File "
- + docDTO.getFiles().get(0).getPath()
- + " attached to the document "
- + docDTO.getTitle() + "#" + docDTO.getId() + " doesn't exist");
- LOG.debug("Source format: " + curDoc.getFormat() + ", new format: " + newFormat);
- }
-
-
- } else {
- // Check that new documents are created for new data
- boolean found = false;
- Publication newPub = null;
- for (Publication pub : aScen.getDocums()) {
- if (pub.value().getPreviousVersion() == null) {
- found = (pub.value().getTitle().startsWith(pub
- .value().getType().getName()));
- if (found) { // Found next published version of the checked in document
- String fcontent = Files.readFile(pub
- .getSourceFile().asFile());
- found = fcontent.contains(docDTO.getTitle());
- if (found) {
- LOG
- .debug("Found new document with generated title: "
- + pub.value().getTitle());
- newPub = pub;
- break;
- }
- }
- }
- }
- Assert.assertTrue(found,
- "New document is not created for checked in document \""
- + docDTO.getTitle() + "\".");
-
- // Check that uses relations are created correctly
- Assert.assertTrue(newPub.value().getTitle().startsWith(
- newPub.value().getType().getName() + "_"),
- "Document title newPub.value().getTitle() must start with "
- + newPub.value().getType().getName() + "_");
-
- // 1. Find the document type used by this document type
- Set<DocumentType> usedTypes = newPub.value().getType()
- .getDefaultUses();
- // 2. Find documents of used types in the current study step and previous study steps
- for (Publication pub : aScen.getDocums()) {
- if ((pub.getStep().getNumber() <= step.getNumber())
- && (!pub.isOutdated())
- && usedTypes.contains(pub.value().getType())) {
- // 3. Check that there is uses relation to the found document
- // if it is not outdated.
- checkUsesRelation(newPub, pub);
- }
- }
-
- // Check that files are moved correctly
- checkFiles(docDTO, newPub);
- }
- }
- }
-
- // ///////////////////////////////////////////////////////////
- // Call checkin method for a not existing id.
- try {
- _scenarioService.checkin(-1, userId, stepsToCheckin);
- Assert
- .fail("Check in for scenario with not existing id must be failed.");
- } catch (Exception e) {
- LOG.debug("Expected exception is thrown: "
- + e.getClass().getSimpleName() + ": " + e.getMessage());
- }
-
- // Test checkin with empty list of steps
- stepsToCheckin.clear();
- _scenarioService.checkin(scenarioId, userId, stepsToCheckin);
-
- rollbackNestedTransaction();
- LOG.debug(">>>>> END testCheckin()");
- }
-
- /**
- * Check if there is uses relation from the newPub to pub.
- *
- * @param newPub
- * the new publication
- * @param pub
- * the publication to be used
- */
- private void checkUsesRelation(final Publication newPub,
- final Publication pub) {
- boolean uses = false;
- boolean usesExist = false;
- for (Publication usesPub : newPub.getRelations(UsesRelation.class)) {
- usesExist = true;
- uses = (usesPub.equals(pub));
- if (uses) {
- break;
- }
- }
- Assert.assertTrue(usesExist && uses, "The created document "
- + newPub.value().getTitle() + "("
- + newPub.value().getType().getName() + ")"
- + " has no uses relation to the document "
- + pub.value().getTitle() + "("
- + pub.value().getType().getName() + ")");
- }
-
- /**
- * Check that files are moved correctly.
- *
- * @param docDTO
- * checked in document DTO
- * @param newPub
- * the created document publication
- */
- private void checkFiles(final DocumentDTO docDTO, final Publication newPub) {
- // Check that original files are deleted
- for (int j = 0; j < docDTO.getFiles().size(); j++) {
- FileDTO fileDTO = docDTO.getFiles().get(j);
- Assert.assertFalse(new File(fileDTO.getPath()).exists(), "File"
- + fileDTO.getPath()
- + " was not removed from downloads directory.");
- String format = fileDTO.getPath().substring(
- fileDTO.getPath().lastIndexOf('.') + 1);
- }
- // TODO: Check file by its internal content
- Assert.assertTrue(newPub.getSourceFile().exists(), "File "
- + newPub.getSourceFile().asFile().getAbsolutePath()
- + " for the document " + docDTO.getTitle()
- + " was not created.");
- }
-
- /**
- * Prepare a document with a file for check-in.
- *
- * @param stepTo
- * step DTO with data for check-in
- * @param module
- * SALOME module name
- * @param format
- * file extension
- * @param userId
- * download directory
- * @param stepFrom
- * checked out stepDTO
- * @param stepsToCheckin
- * DTO for check-in
- * @throws IOException
- * if file creation failed
- * @return step DTO with data prepared for check-in (stepTo or new if stepTo is null)
- */
- private StepDTO createDocDTOForModule(final StepDTO stepTo,
- final String module, final String format, final long userId,
- final StepDTO stepFrom, final List<StepDTO> stepsToCheckin)
- throws IOException {
- StepDTO stepToCheckin = stepTo;
- if (stepToCheckin == null) {
- stepToCheckin = new StepDTO();
- }
- if (module.equals(stepFrom.getModule())) {
- stepsToCheckin.add(stepToCheckin);
- stepToCheckin.setNumber(stepFrom.getNumber());
- for (DocumentDTO doc : stepFrom.getDocs()) {
- if (doc.getFiles().get(0).getState() != 'O') {
- DocumentDTO docToCheckin = stepToCheckin.addDoc(
- doc.getId(), doc.getTitle());
- for (FileDTO file : doc.getFiles()) {
- if (file.getPath().endsWith(format)
- || (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));
- }
- }
- }
- }
- // Prepare new data
- stepToCheckin.addDoc(0, "newdoc" + stepFrom.getNumber()).addFile(
- createDownloadedFile(userId, "newdoc"
- + stepFrom.getNumber(), "brep"));
- }
- return stepToCheckin;
- }
-
- /**
- * 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);
- }
-
- /**
- * 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);
- }
-
- /**
- * 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 persistent scenario for tests.
- *
- * @return a persistent scenario
- * @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 document creation is failed
- * @throws SQLException
- * if project settings loading is failed
- */
- private long createScenario() throws InvalidPropertyException,
- MissedPropertyException, MultiplyDefinedException, IOException,
- SQLException {
- // Create a scenario for tests
- HibernateTemplate ht = getHibernateTemplate();
-
- Database.getInstance().reset();
- _projectSettings.getAllSteps().clear(); // Clear config to be able to load it again
- // Load workflow customization
- try {
- _projectSettings.configure(ClassLoader.getSystemResource(
- "test/som.xml").getPath());
- } catch (FileNotFoundException e) {
- Assert.fail("Can't find som.xml: ", e);
- }
- List<Step> steps = _projectSettings.getStepsOf(Scenario.class);
- Assert.assertTrue(steps.size() > 0, "No steps are created.");
-
- // Create a test user
- User.Properties uprop = new User.Properties();
- uprop.setUsername("TST_Username").setName("TST_SimanUnitTestsUser")
- .setFirstName("TST_FirstName").setDisplayName("TST_test.user")
- .addRole("TST_user").setMailAddress(
- "noreply@salome-platform.org");
- uprop.disableCheck();
- User anAuthor = new User(uprop);
- ht.saveOrUpdate(anAuthor);
-
- // Create a test study
- Study.Properties stprops = new Study.Properties().setReference(
- "TST_SID_01").setTitle("TST_Study").setManager(anAuthor);
- Study aStudy = new Study(stprops);
- ht.saveOrUpdate(aStudy);
-
- // Create a test scenario
- Scenario.Properties sprops = new Scenario.Properties().setTitle(
- "TST_Scenario").setManager(anAuthor).setOwnerStudy(aStudy);
- Scenario aScenario = new Scenario(sprops);
- aStudy.getScenariiList().add(aScenario);
- ht.saveOrUpdate(anAuthor);
- ht.saveOrUpdate(aStudy);
- ht.saveOrUpdate(aScenario);
-
- // Create documents for each scenario step
- Document.Properties dprop = new Document.Properties().setAuthor(
- anAuthor).setDate(new Date());
- int i = 0;
- Publication usedPub = null;
- Map<Long, Long> usedMap = new HashMap<Long, Long>();
- for (Step step : steps) {
- LOG.debug("Create scenario step: " + i);
-
- org.splat.som.Step aScStep = new org.splat.som.Step(step, aScenario);
- List<DocumentType> dtypes = _documentTypeService
- .selectTypesOf(step);
- for (DocumentType dtype : dtypes) {
- // Create a document published in the scenario
- // document<i>: document type[0] - first type used on the step
- // <source-file>.brep
- // <attached-file>.med
- dprop.setName("document" + i++).setType(dtype);
-/* 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);
- if (usedPub != null) {
- pub.addDependency(usedPub);
- ht.saveOrUpdate(pub.value());
-
- usedMap.put(pub.getIndex(), usedPub.getIndex());
- }
- usedPub = pub;
-
- // Create another document with outdated publication
- dprop.setName("document" + i++).setType(dtype).setFormat("py");
- dprop.setLocalPath(dprop.getName() + "." + dprop.getFormat());
- createDoc(aScenario, aScStep, dprop, "med", true);
-
- }
- if (dtypes.size() <= 0) {
- LOG.debug("No document types are found for scenario step " + i);
- }
- }
-
- // Check that the scenario and its documents have been created correctly.
-
- Assert.assertNotNull(ht.find("from Document"),
- "No documents in the database.");
- Assert.assertTrue(ht.find("from Document").size() > 0,
- "No documents in the database.");
-
- Assert.assertNotNull(ht.find("from Publication where owner="
- + aScenario.getIndex()), "No publications in the database.");
- Assert.assertTrue(
- ht.find("from Publication where owner=" + aScenario.getIndex())
- .size() > 0, "No publications in the database.");
-
- for (Publication p : (List<Publication>) ht
- .find("from Publication where owner=" + aScenario.getIndex())) {
- LOG.debug("Publication found: [id=" + p.getIndex() + ", owner="
- + p.getOwner().getIndex() + ", doc=" + p.value().getIndex()
- + "]");
- Assert.assertEquals(p.getOwner().getIndex(), aScenario.getIndex(),
- "The publication was not attached to the scenario.");
- }
-
- // Remove the scenario from the current hibernate session.
- ht.evict(aScenario);
- // Check that the scenario is created in the database.
- Scenario aScen = ht.load(Scenario.class, aScenario.getIndex());
- Assert.assertNotNull(aScen, "Scenario was not saved in the database.");
- Assert.assertTrue(aScen.getDocums().size() > 0,
- "No publications in the scenario.");
-
- Assert.assertTrue(i > 0,
- "More then one document must be in the database");
-
- // Check created uses relations
- Assert
- .assertTrue(usedMap.size() > 0,
- "Uses relations must be created.");
- boolean foundAny = false;
- for (Long usingId : usedMap.keySet()) {
- for (Publication pub : aScen.getDocums()) {
- if (pub.getIndex() == usingId) {
- boolean found = false;
- for (Publication used : aScen.getDocums()) {
- found = (used.getIndex() == usedMap.get(usingId));
- if (found) {
- break;
- }
- }
- Assert.assertTrue(found,
- "Uses relation was not created in the database.");
- foundAny = foundAny || found;
- }
- }
- }
- Assert.assertTrue(foundAny,
- "No Uses relation was created in the database.");
-
- return aScenario.getIndex();
- }
-
- /**
- * Create a document published in the scenario. <BR>
- * document:<BR>
- * document type[0] - first type used on the step <BR>
- * <source-file>.brep <BR>
- * <attached-file>.med
- *
- * @param aScenario
- * the scenario to add the document to
- * @param aScStep
- * scenario step where the document to be published
- * @param dprop
- * document properties
- * @param attachedFileExt
- * extension of the secon attached (exported) file
- * @param isOutdated
- * outdated document flag
- * @return the publication of the created document
- * @throws IOException
- * @throws MultiplyDefinedException
- * @throws InvalidPropertyException
- * @throws MissedPropertyException
- */
- private Publication createDoc(final Scenario aScenario,
- final org.splat.som.Step aScStep, final Properties dprop,
- final String attachedFileExt, final boolean isOutdated)
- throws MissedPropertyException, InvalidPropertyException,
- MultiplyDefinedException, IOException {
- // Create a document published in the scenario
- // document<i>: document type[0] - first type used on the step
- // <source-file>.brep
- // <attached-file>.med
- createDownloadedFile(aScenario.getAuthor().getIndex(), dprop
- .getLocalPath());
- Publication pub = _stepService.createDocument(aScStep, dprop);
- Assert.assertNotNull(pub.getOwner(),
- "The publication must be attached to the scenario.");
- Assert.assertEquals(pub.getOwner().getIndex(), aScenario.getIndex(),
- "The publication was not attached to the scenario.");
-
- if (isOutdated) {
- pub.setIsnew('O');
- }
- aScenario.add(pub);
- HibernateTemplate ht = getHibernateTemplate();
- ht.saveOrUpdate(pub);
-
- // Attach a file
- createDownloadedFile(aScenario.getAuthor().getIndex(), dprop
- .getLocalPath().substring(0,
- dprop.getLocalPath().lastIndexOf(".") - 1),
- attachedFileExt);
- ht.save(pub.value());
- ht.saveOrUpdate(_publicationService.attach(pub, attachedFileExt));
-
- return pub;
- }
-
- /**
- * Test check-in scenario operation to be performed after SALOME session.<BR>
- * <B>Description :</B> <BR>
- * <i>Create a scenario and try to check-in it with some simulated SALOME results data.<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>
- * <B>Action : </B><BR>
- * <i>1. call the method for an existing scenario id.</i><BR>
- * <i>2. call the method for a not existing scenario id.</i><BR>
- * <B>Test data : </B><BR>
- * <i>no input parameters</i><BR>
- * <i>no input parameters</i><BR>
- *
- * <B>Outcome results:</B><BR>
- * <i>
- * <ul>
- * <li>New version of existing documents must be created and new documents must be imported for documents with zero id. Correct
- * relations must be created.<BR>
- * </li>
- * <li>Exception is thrown<BR>
- * </li>
- * </ul>
- * </i>
- *
- * @throws InvalidPropertyException
- * if an invalid property is used when creating objects
- * @throws MultiplyDefinedException
- * when trying to create an object with already existing id
- * @throws MissedPropertyException
- * if a mandatory property is not defined for an object to be created
- * @throws IOException
- * if scenario creation is failed
- * @throws SQLException
- * if scenario creation is failed
- * @throws NotApplicableException
- * if checkin failed
- * @throws MismatchException
- * if checkin failed
- */
- @Test(groups = { "study", "sevice", "functional", "business" })
- public void testCreateStudy() throws InvalidPropertyException,
- MissedPropertyException, MultiplyDefinedException, IOException,
- SQLException, MismatchException, NotApplicableException {
- 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());
-
- // Create a test user
- User.Properties uprop = new User.Properties();
- uprop.setUsername("TST_Username").setName("TST_SimanUnitTestsUser")
- .setFirstName("TST_FirstName").setDisplayName("TST_test.user")
- .addRole("TST_user").setMailAddress(
- "noreply@salome-platform.org");
- uprop.disableCheck();
- User anAuthor = new User(uprop);
-
- getHibernateTemplate().saveOrUpdate(anAuthor);
- KnowledgeElementType ucase = _knowledgeElementTypeService
- .selectType("usecase");
- Assert.assertNotNull(ucase,
- "Knowledge type 'usecase' must be created in the database.");
- SimulationContextType prodtype = _simulationContextService
- .selectType("product");
- Assert
- .assertNotNull(prodtype,
- "Simulation context type 'product' must be created in the database.");
-
- // Create admin
- uprop.clear();
- uprop.setUsername("TST_Admin").setName("TST_SimanUnitTestsAdmin")
- .setFirstName("TST_AdminFirstName").setDisplayName(
- "TST_test.admin").addRole("TST_user,sysadmin")
- .setMailAddress("noreply@salome-platform.org");
- uprop.disableCheck();
-
- getHibernateTemplate().saveOrUpdate(new User(uprop));
- getHibernateTemplate().flush();
-
- Study.Properties sprop = new Study.Properties();
- sprop.setTitle("Test study creation").setManager(anAuthor);
- Scenario.Properties oprop = new Scenario.Properties();
- oprop.setTitle("Test scenario for the created study");
-
- // Addition of the entered project context
- SimulationContext.Properties cprop = new SimulationContext.Properties();
- // Input of new project context
- cprop.setType(_simulationContextService.selectType("product"))
- .setValue("Test Simulation Context: Product");
- Study study = _scenarioService.createStudy(sprop, oprop, cprop);
-
- rollbackNestedTransaction();
- LOG.debug(">>>>> END testCreateStudy()");
- }
+ /**
+ * Logger for the class.
+ */
+ private static final AppLogger LOG = AppLogger
+ .getLogger(TestScenarioService.class);
+
+ /**
+ * The tested ScenarioService. Later injected by Spring.
+ */
+ @Autowired
+ @Qualifier("scenarioService")
+ private transient ScenarioService _scenarioService;
+
+ /**
+ * The RepositoryService. Later injected by Spring.
+ */
+ @Autowired
+ @Qualifier("repositoryService")
+ private transient RepositoryService _repositoryService;
+
+ /**
+ * The Scenario DAO. Later injected by Spring.
+ */
+ @Autowired
+ @Qualifier("scenarioDAO")
+ private transient ScenarioDAO _scenarioDAO;
+
+ /**
+ * The PublicationService. Later injected by Spring.
+ */
+ @Autowired
+ @Qualifier("publicationService")
+ private transient PublicationService _publicationService;
+
+ /**
+ * The StepService. Later injected by Spring.
+ */
+ @Autowired
+ @Qualifier("stepService")
+ private transient StepService _stepService;
+
+ /**
+ * The SimulationContextService. Later injected by Spring.
+ */
+ @Autowired
+ @Qualifier("simulationContextService")
+ private transient SimulationContextService _simulationContextService;
+
+ /**
+ * The ProjectSettingsService. Later injected by Spring.
+ */
+ @Autowired
+ @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.
+ */
+ @Autowired
+ @Qualifier("documentTypeService")
+ private transient DocumentTypeService _documentTypeService;
+
+ /**
+ * The KnowledgeElementTypeService. Later injected by Spring.
+ */
+ @Autowired
+ @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 new id of document arrived during checkin.<BR>
+ * <B>Description :</B> <BR>
+ * <i>Create a study, scenario, documents and list extension of documents arrived after checkin.<BR>
+ * Try get new id for every new document</i><BR>
+ * <B>Action : </B><BR>
+ * <i>
+ * <ol>
+ * <li>call the method for activityNumber = -1</li>
+ * <li>call the method for first test case, when before check in existed
+ * D1.comm and after checkin arrived three documents file1.comm, file2.resu, file3.mess</li>
+ * <li>call the method for second test case, when before check in not existed
+ * docs and after checkin arrived three documents file1.comm, file2.resu, file3.mess</li>
+ * <li>call the method for third test case, when before check in existed D1.comm,
+ * D2.resu(id of D1 > id of D2) and after checkin arrived three documents file1.comm, file2.resu, file3.mess</li>
+ * <li>call the method for fourth test case, when before check in existed D1.comm,
+ * D2.resu (id of D1 < id of D2) and after checkin arrived three documents file1.comm, file2.resu, file3.mess</li>
+ * </ol>
+ * </i>
+
+ * <B>Test data : </B><BR>
+ * <i>no input parameters</i><BR>
+ * <BR>
+ * <B>Outcome results:</B><BR>
+ * <i>The returned id is -1 if there is no appropriate document in the step or max id of existing document with appropriate type<BR>
+ * <ol>
+ * <li>If activityNumber = -1 then throw InvalidPropertyException.</li>
+ * <li>comm: id of D1.comm document; resu and mess: -1</li>
+ * <li>comm: -1; resu and mess: -1</li>
+ * <li>comm: id of D1.comm document; resu and mess: id of D2.resu document;</li>
+ * <li>comm: id of D1.comm document; resu and mess: id of D2.resu document;</li>
+ * </ol>
+ * </i>
+ * @throws BusinessException
+ * if documents creation is failed
+ * @throws IOException
+ * if scenario creation is failed
+ * @throws SQLException
+ * if scenario creation is failed
+ */
+
+ @Test(groups = {"checkin", "sevice", "functional", "business" })
+ public void testGetNewDocumentId() throws IOException, SQLException,
+ BusinessException {
+ LOG.debug(">>>>> BEGIN testGetNewDocumentId()");
+ int numOfMecaStep = 5;
+ long maxId = -1;
+
+ startNestedTransaction();
+
+ HibernateTemplate ht = getHibernateTemplate();
+
+ Database.getInstance().reset();
+ _projectSettings.getAllSteps().clear();
+ _projectSettings.configure("classpath:test/som-generated-copy.xml");
+
+ List<String> docAfterCheckin = new ArrayList<String>();
+
+ docAfterCheckin.add("comm");
+ docAfterCheckin.add("resu");
+ docAfterCheckin.add("mess");
+
+ // Create a test user
+ User goodUser = TestEntitiesGenerator.getTestUser("goodUser");
+ _userDAO.create(goodUser);
+ Study study = TestEntitiesGenerator.getTestStudy(goodUser);
+
+
+ // Create a test study
+ _studyDAO.create(study);
+ ht.flush();
+
+ //Create a test scenario
+ Scenario scen1 = TestEntitiesGenerator.getTestScenario(study,
+ "test scen 1");
+ long id1 = _scenarioDAO.create(scen1);
+ Map<Integer, org.splat.som.Step> stSteps = _projectElementService
+ .getStepsMap(scen1);
+
+ org.splat.som.Step aStep = stSteps.get(numOfMecaStep);
+
+ Publication pub1 = createDoc("D1", "loads", "comm", aStep,
+ goodUser, scen1, ht);
+ ht.flush();
+
+ // test valid number of step
+ try {
+ _scenarioService.getNewDocumentId(id1, -1, pub1.value().getIndex(),
+ docAfterCheckin.get(0));
+ Assert.fail("Document must not be found with an invalid step number");
+ } catch (InvalidPropertyException e) {
+ LOG.debug("Expected exception: " + e.getMessage());
+ }
+
+ // first test case
+
+ Assert.assertTrue(_scenarioService.getNewDocumentId(id1, numOfMecaStep,
+ pub1.value().getIndex(), docAfterCheckin.get(0))
+ == pub1.value().getIndex());
+ Assert.assertTrue(_scenarioService.getNewDocumentId(id1, numOfMecaStep,
+ pub1.value().getIndex(), docAfterCheckin.get(1))
+ == -1);
+ Assert.assertTrue(_scenarioService.getNewDocumentId(id1, numOfMecaStep,
+ pub1.value().getIndex(), docAfterCheckin.get(2))
+ == -1);
+
+
+ scen1 = TestEntitiesGenerator.getTestScenario(study, "test scen 1");
+ id1 = _scenarioDAO.create(scen1);
+ stSteps = _projectElementService
+ .getStepsMap(scen1);
+ aStep = stSteps.get(numOfMecaStep);
+ ht.flush();
+
+ //second test case
+
+ Assert.assertTrue(_scenarioService.getNewDocumentId(id1, numOfMecaStep,
+ maxId, docAfterCheckin.get(0)) == -1);
+ Assert.assertTrue(_scenarioService.getNewDocumentId(id1, numOfMecaStep,
+ maxId, docAfterCheckin.get(1)) == -1);
+ Assert.assertTrue(_scenarioService.getNewDocumentId(id1, numOfMecaStep,
+ maxId, docAfterCheckin.get(2)) == -1);
+
+ scen1 = TestEntitiesGenerator.getTestScenario(study, "test scen 1");
+ id1 = _scenarioDAO.create(scen1);
+ stSteps = _projectElementService.getStepsMap(scen1);
+ aStep = stSteps.get(numOfMecaStep);
+
+ pub1 = createDoc("D1", "loads", "comm", aStep, goodUser, scen1, ht);
+ Publication pub2 = createDoc("D2", "resultsMeca", "resu", aStep,
+ goodUser, scen1, ht);
+
+ ht.flush();
+
+ //third test case
+
+ if (pub1.value().getIndex() > pub2.value().getIndex()) {
+ maxId = pub1.value().getIndex();
+ } else {
+ maxId = pub2.value().getIndex();
+ }
+
+ Assert.assertTrue(_scenarioService.getNewDocumentId(id1, numOfMecaStep,
+ maxId, docAfterCheckin.get(0))
+ == pub1.value().getIndex());
+ Assert.assertTrue(_scenarioService.getNewDocumentId(id1, numOfMecaStep,
+ maxId, docAfterCheckin.get(1))
+ == pub2.value().getIndex());
+ Assert.assertTrue(_scenarioService.getNewDocumentId(id1, numOfMecaStep,
+ maxId, docAfterCheckin.get(2))
+ == pub2.value().getIndex());
+
+ scen1 = TestEntitiesGenerator.getTestScenario(study, "test scen 1");
+ id1 = _scenarioDAO.create(scen1);
+ stSteps = _projectElementService.getStepsMap(scen1);
+ aStep = stSteps.get(numOfMecaStep);
+
+ pub1 = createDoc("D2", "resultsMeca", "resu", aStep,
+ goodUser, scen1, ht);
+ pub2 = createDoc("D1", "loads", "comm", aStep, goodUser, scen1, ht);
+
+ ht.flush();
+
+ // fourth test case
+
+ if (pub1.value().getIndex() > pub2.value().getIndex()) {
+ maxId = pub1.value().getIndex();
+ } else {
+ maxId = pub2.value().getIndex();
+ }
+
+ Assert.assertTrue(_scenarioService.getNewDocumentId(id1, numOfMecaStep,
+ maxId, docAfterCheckin.get(0)) == pub2.value().getIndex());
+ Assert.assertTrue(_scenarioService.getNewDocumentId(id1, numOfMecaStep,
+ maxId, docAfterCheckin.get(1)) == pub1.value().getIndex());
+ Assert.assertTrue(_scenarioService.getNewDocumentId(id1, numOfMecaStep,
+ maxId, docAfterCheckin.get(2)) == pub1.value().getIndex());
+
+ rollbackNestedTransaction();
+ LOG.debug(">>>>> END testGetNewDocId()");
+ }
+
+ /**
+ * Create a document published in the scenario. <BR>
+ *
+ * @param name
+ * name of the document
+ * @param docType
+ * type of the document
+ * @param format
+ * document extension
+ * @param step
+ * scenario step where the document to be published
+ * @param user
+ * User of document
+ * @param scen
+ * the scenario to add the document to
+ * @param ht
+ * hinernate session
+ *
+ *
+ * @return the publication of the created document
+ * @throws IOException
+ * @throws SQLException
+ * @throws BusinessException
+ */
+
+ protected final Publication createDoc(final String name,
+ final String docType, final String format,
+ final org.splat.som.Step step, final User user,
+ final Scenario scen,
+ final HibernateTemplate ht)throws
+ IOException, SQLException, BusinessException {
+ DocumentType dtype = _documentTypeService.selectType(docType);
+
+ Document.Properties dprop = new Document.Properties().setAuthor(
+ user).setDate(new Date()).setName(name)
+ .setType(dtype).setFormat(format);
+
+ dprop.setStep(step.getStep());
+ Publication pub = _stepService.createDocument(step, dprop);
+
+ pub.setStep(step);
+ scen.add(pub);
+
+ step.getDocuments().add(pub);
+
+ ht.saveOrUpdate(pub);
+ ht.save(pub.value());
+
+ return pub;
+ }
+
+ /**
+ * Test of getting a scenario content for building siman-salome.conf.<BR>
+ * <B>Description :</B> <BR>
+ * <i>Create a scenario and try to get an info for it.</i><BR>
+ * <B>Action : </B><BR>
+ * <i>1. call the method for an existing scenario id.</i><BR>
+ * <i>2. call the method for a not existing scenario id.</i><BR>
+ * <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>result DTO must contain list of all documents and files<BR>
+ * </li>
+ * <li>Exception is thrown<BR>
+ * </li>
+ * </ul>
+ * </i>
+ *
+ * @throws InvalidPropertyException
+ * if an invalid property is used when creating objects
+ * @throws MultiplyDefinedException
+ * when trying to create an object with already existing id
+ * @throws MissedPropertyException
+ * if a mandatory property is not defined for an object to be
+ * created
+ * @throws IOException
+ * if scenario creation is failed
+ * @throws SQLException
+ * if scenario creation is failed
+ */
+ @Test(groups = { "checkout", "sevice", "functional", "business" })
+ public void testGetScenarioInfo() throws InvalidPropertyException,
+ MissedPropertyException, MultiplyDefinedException, IOException,
+ SQLException {
+ LOG.debug(">>>>> BEGIN testGetScenarioInfo()");
+ startNestedTransaction();
+
+ long scenarioId = createScenario();
+ // Call DAO's create method for a good transient knowledge element.
+ List<StepDTO> steps = _scenarioService.getScenarioInfo(scenarioId);
+ Assert.assertNotNull(steps, "List of steps must not be null.");
+ Assert.assertTrue(steps.size() > 0, "No steps are read.");
+
+ List<Step> projSteps = _stepsConfigService.getStepsOf(Scenario.class);
+ Assert.assertEquals(steps.size(), projSteps.size(),
+ "Not all steps are listed.");
+ int docIndex = 0;
+ for (StepDTO step : steps) {
+ LOG.debug("check the step " + step.getNumber() + ":\n" + step);
+ Assert.assertNotNull(step, "Step DTO must not be null.");
+ Assert.assertNotNull(step.getKey(), "Step name must not be null.");
+ Assert.assertFalse(step.getKey().isEmpty(),
+ "Step name must not empty.");
+ Assert.assertTrue(step.getNumber() > 0,
+ "Step number must be positive integer.");
+ Assert.assertNotNull(step.getDocs(),
+ "Step documents list must not be null.");
+
+ Step aProjStep = null;
+ for (Step projStep : projSteps) {
+ if (projStep.getNumber() == step.getNumber()) {
+ aProjStep = projStep;
+ break;
+ }
+ }
+
+ List<DocumentType> dtypes = _documentTypeService
+ .selectTypesOf(aProjStep);
+ for (DocumentType dtype : dtypes) {
+ Assert.assertTrue(step.getDocs().size() > 0,
+ "Step documents list must not be empty.");
+ String docName = "document" + docIndex;
+ for (DocumentDTO doc : step.getDocs()) {
+ if (docName.equals(doc.getTitle())) {
+ Assert.assertTrue(doc.getId() > 0,
+ "Document id must be positive integer.");
+ Assert.assertEquals(doc.getTitle(), docName);
+ Assert.assertNotNull(doc.getFiles(),
+ "Document files list must not be null.");
+ Assert.assertTrue(doc.getFiles().size() > 1,
+ "Document must have more then 1 attached file.");
+
+ for (FileDTO file : doc.getFiles()) {
+ Assert.assertNotNull(file.getPath(),
+ "File path must not be null.");
+ Assert.assertFalse(file.getPath().isEmpty(),
+ "File path must not be empty.");
+ /*
+ * <mappings> <document type="geometry"> <import
+ * format="brep"/> <!-- Result Shape --> </document>
+ * <document type="model"> <import format="med"/>
+ * <!-- Result mesh without input parameters -->
+ * </document> <document type="loads"> <import
+ * format="c3m"/> <!-- Input data created
+ * interactively --> </document> <document
+ * type="results"> <import format="med"/> <!--
+ * Calculation results source file --> </document>
+ * </mappings>
+ */
+ // Check state and processing instruction
+ String fileFormat = file.getPath().substring(
+ file.getPath().lastIndexOf('.') + 1);
+ /*
+ * if (_projectSettings.doImport(dtype.getName(),
+ * fileFormat)) { Assert.assertTrue(file.isResult(),
+ * "The file must be a result file.
+ * "); } else { Assert.assertFalse(file.isResult(), "
+ * The file must be a source file."); }
+ */if ((docIndex % 2) == 0) { // New
+ Assert.assertEquals(file.getState(), 'Y',
+ "File state must be actual ('Y').");
+ if (_projectSettings.doImport(dtype.getName(),
+ fileFormat)) {
+ Assert.assertEquals(file.getProcessing(),
+ "file-import",
+ "File must be imported.");
+ } else {
+ Assert.assertEquals(file.getProcessing(),
+ "file-download",
+ "File must be downloaded.");
+ }
+ } else { // Outdated
+ Assert.assertEquals(file.getState(), 'O',
+ "File state must be outdated ('O').");
+ Assert.assertEquals(file.getProcessing(),
+ "file-download",
+ "Outdated document should not be imported but downloaded.");
+ }
+ }
+ }
+ }
+ docIndex++;
+ }
+ }
+
+ // Call DAO's get method for a not existing id.
+ try {
+ steps = _scenarioService.getScenarioInfo(-1L);
+ // getHibernateTemplate().flush();
+ Assert.fail("Getting an object with not existing id must be failed.");
+ } catch (Exception e) {
+ LOG.debug("Expected exception is thrown: "
+ + e.getClass().getSimpleName() + ": " + e.getMessage());
+ }
+ rollbackNestedTransaction();
+ LOG.debug(">>>>> END testGetScenarioInfo()");
+ }
+
+ /**
+ * Test check-in scenario operation to be performed after SALOME session.<BR>
+ * <B>Description :</B> <BR>
+ * <i>Create a scenario and try to check-in it with some simulated SALOME
+ * results data.<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>formats of files are new if they are according to the document's type
+ * on the study step</li>
+ * <li>new documents are created for new data</li>
+ * <li>new documents have correctly generated names</li>
+ * <li>uses relations are created correctly</li>
+ * <li>files are moved correctly</li>
+ * </ul>
+ * </i><BR>
+ * <B>Action : </B><BR>
+ * <i>1. call the method for an existing scenario id.</i><BR>
+ * <i>2. call the method for a not existing scenario id.</i><BR>
+ * <B>Test data : </B><BR>
+ * <i>no input parameters</i><BR>
+ * <i>no input parameters</i><BR>
+ *
+ * <B>Outcome results:</B><BR>
+ * <i>
+ * <ul>
+ * <li>New version of existing documents must be created and new documents
+ * must be imported for documents with zero id. Correct relations must be
+ * created.<BR>
+ * </li>
+ * <li>Exception is thrown<BR>
+ * </li>
+ * </ul>
+ * </i>
+ *
+ * @throws InvalidPropertyException
+ * if an invalid property is used when creating objects
+ * @throws MultiplyDefinedException
+ * when trying to create an object with already existing id
+ * @throws MissedPropertyException
+ * if a mandatory property is not defined for an object to be
+ * created
+ * @throws IOException
+ * if scenario creation is failed
+ * @throws SQLException
+ * if scenario creation is failed
+ * @throws NotApplicableException
+ * if checkin failed
+ * @throws MismatchException
+ * if checkin failed
+ */
+ @Test(groups = { "checkin", "sevice", "functional", "business" })
+ public void testCheckin() throws InvalidPropertyException,
+ MissedPropertyException, MultiplyDefinedException, IOException,
+ SQLException, MismatchException, NotApplicableException {
+ LOG.debug(">>>>> BEGIN testCheckin()");
+ startNestedTransaction();
+
+ _projectSettings.getAllSteps().clear(); // Clear config to be able to
+ // load it again
+ _projectSettings.configure("classpath:test/som.xml");
+ getHibernateTemplate().flush();
+ long scenarioId = createScenario();
+ Scenario aScen = _scenarioDAO.get(scenarioId);
+ User user = aScen.getAuthor();
+ long userId = user.getIndex();
+
+ // ////////////////////////////////////////////////////////
+ // Call checkin method for empty list of modules.
+
+ // Simulate checkout
+ _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.");
+
+ // ///////////////////////////////////////////////////////////
+ // Different test cases
+
+ // Fancy but compact way to iterate over all possible combinations
+ // without missing any of them.
+ List<Boolean> trueFalse = new ArrayList<Boolean>();
+ trueFalse.add(false);
+ trueFalse.add(true);
+ long testCaseNumber = 1; // To provide some uniqueness to files content.
+
+ for (boolean hasSource : trueFalse) {
+ for (boolean hasAttachments : trueFalse) {
+ for (boolean checkinSource : trueFalse) {
+ for (boolean checkinAttachments : trueFalse) {
+ if (hasAttachments && !hasSource) { // Impossible test
+ // cases
+ continue;
+ }
+ if (!checkinAttachments && !checkinSource) { // Unnecessary
+ // test
+ // cases
+ continue;
+ }
+
+ // startNestedTransaction();
+ Set<String> res = testCheckinTestcase(testCaseNumber++,
+ scenarioId, userId, hasSource, hasAttachments,
+ checkinSource, checkinAttachments);
+ // rollbackNestedTransaction();
+
+ // These combinations are dictated by
+ // assertCheckinValidity logic
+ Assert.assertEquals(!hasSource
+ && (checkinSource || checkinAttachments),
+ res.contains("aNewSourceCreated"));
+ Assert.assertEquals(hasSource && checkinSource,
+ res.contains("oldSourceVersioned"));
+ Assert.assertEquals(checkinAttachments && hasSource
+ && checkinSource,
+ res.contains("fileAttachedToAVersionedDoc"));
+ Assert.assertEquals(checkinAttachments && hasSource
+ && !checkinSource,
+ res.contains("fileAttachedToAnOldDoc"));
+ Assert.assertEquals(checkinAttachments && !hasSource,
+ res.contains("fileAttachedToANewDoc"));
+
+ }
+ }
+ }
+ }
+
+ // ///////////////////////////////////////////////////////////
+ // Call checkin method for a not existing id.
+ try {
+ _scenarioService.checkin(-1, userId, stepsToCheckin);
+ Assert.fail("Check in for scenario with not existing id must be failed.");
+ } catch (Exception e) {
+ LOG.debug("Expected exception is thrown: "
+ + e.getClass().getSimpleName() + ": " + e.getMessage());
+ }
+
+ // Test checkin with empty list of steps
+ stepsToCheckin.clear();
+ _scenarioService.checkin(scenarioId, userId, stepsToCheckin);
+
+ rollbackNestedTransaction();
+ LOG.debug(">>>>> END testCheckin()");
+ }
+
+ /**
+ * Performs necessary checks after checkin.
+ *
+ * @param testCaseNumber
+ * the test case number
+ * @param stepsToCheckin
+ * stepDTOs which has been checked in
+ * @param aScen
+ * the scenario
+ * @param dates
+ * modification dates
+ * @return set of strings indicating which cases has occurred
+ * @throws IOException
+ * if something is wrong
+ */
+ private Set<String> assertCheckinValidity(final long testCaseNumber,
+ final List<StepDTO> stepsToCheckin, final Scenario aScen,
+ final Map<Long, Date> dates) throws IOException {
+ Set<String> result = new HashSet<String>();
+ Assert.assertFalse(aScen.isCheckedout(),
+ "Scenario is still marked as checked out after checkin.");
+ // Check that new document versions are created for checked in documents
+ for (StepDTO step : stepsToCheckin) {
+ for (DocumentDTO docDTO : step.getDocs()) {
+ for (FileDTO fileDTO : docDTO.getFiles()) {
+
+ if ((docDTO.getId() != 0) && (docDTO.getId() != null)) {
+ boolean prevVersFound = false;
+ boolean versionedWithThisFile = false;
+ Document prevDoc = null;
+ Document curDoc = null;
+ Publication newPub = null;
+
+ // If previous version is found then the format must be
+ // the same
+ String newFormat = fileDTO.getPath().substring(
+ fileDTO.getPath().lastIndexOf('.') + 1);
+ for (Publication pub : aScen.getDocums()) {
+ prevDoc = pub.value().getPreviousVersion();
+ if (prevDoc != null) {
+ prevVersFound = (prevDoc.getIndex() == docDTO
+ .getId());
+ if (prevVersFound) { // Found next published
+ // version of the checked
+ // in document
+ newPub = pub;
+ if (pub.value().getFormat()
+ .equals(newFormat)) {
+ versionedWithThisFile = true;
+ }
+ break;
+ }
+ }
+ if (pub.value().getIndex() == docDTO.getId()) {
+ // Document version was not changed, old
+ // document is still published
+ curDoc = pub.value();
+ break;
+ }
+ }
+ Assert.assertTrue(prevVersFound || (curDoc != null),
+ "New version or new attached file of the existing checked in document \""
+ + docDTO.getTitle() + "\" (id="
+ + docDTO.getId()
+ + ") is not found in the scenario.");
+
+ if (prevVersFound && versionedWithThisFile) {
+ result.add("oldSourceVersioned");
+ 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
+ Assert.assertEquals(newPub.getSourceFile()
+ .getFormat(), newFormat);
+ Assert.assertEquals(
+ newPub.getSourceFile()
+ .getRelativePath()
+ .substring(
+ newPub.getSourceFile()
+ .getRelativePath()
+ .lastIndexOf('.') + 1),
+ newFormat);
+
+ // Check that uses relations are copied correctly
+
+ // 1. Get all uses relations of the previous
+ // document version
+ for (Relation rel : prevDoc
+ .getRelations(UsesRelation.class)) {
+ Document used = ((UsesRelation) rel).getTo();
+ // 2.1. Get the latest version of the document
+ // published in this scenario
+ Publication toBeUsed = aScen
+ .getPublication(used);
+ if (toBeUsed == null) {
+ // Find the latest published version
+ for (Publication lastPub : aScen
+ .getDocums()) {
+ if ((lastPub.value()
+ .getPreviousVersion() != null)
+ && (lastPub.value()
+ .getPreviousVersion()
+ .getIndex() == used
+ .getIndex())) {
+ toBeUsed = lastPub;
+ break;
+ }
+ }
+ }
+ if ((toBeUsed != null)
+ && (!toBeUsed.isOutdated())) {
+ // 2.2. For each used document check that
+ // its latest not outdated version
+ // is used by the new checked in document
+ // version.
+ checkUsesRelation(newPub, toBeUsed);
+ }
+ }
+ // 1. Get all usedBy relations of the previous
+ // document version
+ for (Relation rel : prevDoc
+ .getRelations(UsedByRelation.class)) {
+ Document using = ((UsedByRelation) rel).getTo();
+ // Check that not checked in dependent documents
+ // became outdated
+ Publication usingPub = aScen
+ .getPublication(using);
+ if (usingPub != null) { // if the document using
+ // the old version is
+ // still published
+ Assert.assertTrue(usingPub.isOutdated(),
+ "Not checked in dependent document "
+ + using.getTitle() + " ("
+ + using.getType().getName()
+ + ") must become outdated.");
+ }
+ }
+
+ // Check that a correct comment is generated for
+ // VersionsRelation
+ VersionsRelation versRel = (VersionsRelation) newPub
+ .value().getFirstRelation(
+ VersionsRelation.class);
+ Assert.assertNotNull(versRel,
+ "VersionsRelation must be created.");
+ Assert.assertNotNull(versRel.getDescription(),
+ "VersionsRelation description was not generated.");
+ int descrLen = versRel.getDescription().length();
+ Assert.assertTrue(descrLen > 0,
+ "VersionsRelation description is empty.");
+ LOG.debug("Version description: "
+ + versRel.getDescription());
+ } else {
+ // Otherwise the file is attached to some other
+ // document,
+ // which has been or has not been versioned during
+ // checkin
+ Document targetDoc = null;
+ if (prevVersFound) { // if the document has been
+ // versioned
+ Assert.assertEquals(
+ Long.valueOf(prevDoc.getIndex()),
+ docDTO.getId());
+ targetDoc = newPub.value();
+ result.add("fileAttachedToAVersionedDoc");
+ } else {
+ targetDoc = curDoc;
+ result.add("fileAttachedToAnOldDoc");
+ }
+ Assert.assertFalse(newFormat.equals(targetDoc
+ .getFormat()));
+
+ // Check file content
+ Assert.assertTrue(Files.readFile(
+ targetDoc.getAttachedFile(newFormat)
+ .asFile()).contains(
+ new File(fileDTO.getPath()).getName()));
+
+ // Otherwise the new file format must differ from
+ // the previous one
+ // and the new file must be attached to the same
+ // document
+ org.splat.dal.bo.som.File attFile = targetDoc
+ .getAttachedFile(newFormat);
+ Assert.assertNotNull(
+ attFile,
+ "File "
+ + fileDTO.getPath()
+ + " must be attached to the document "
+ + docDTO.getTitle() + "#"
+ + docDTO.getId());
+ Assert.assertTrue(
+ attFile.asFile().exists(),
+ "File " + fileDTO.getPath()
+ + " attached to the document "
+ + docDTO.getTitle() + "#"
+ + docDTO.getId() + " doesn't exist");
+ LOG.debug("Source format: " + targetDoc.getFormat()
+ + ", new format: " + newFormat);
+ // Check that attachment with the same format is not
+ // duplicated.
+ int attachNb = 0;
+ for (Relation conv : targetDoc
+ .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.");
+ result.add("modifDatesChecked");
+ }
+ }
+
+ } else {
+ // here file may be attached to a newly created one,
+ // or it may be a source of new doc itself.
+
+ // Check that new documents are created for new data
+ boolean foundAsSource = false;
+ boolean foundAsAttachment = false;
+ Publication newPub = null;
+ for (Publication pub : aScen.getDocums()) {
+ if (pub.value().getPreviousVersion() == null) {
+ // TODO: is it correct? type name here?
+ foundAsSource = (pub.value().getTitle()
+ .startsWith(pub.value().getType()
+ .getName()));
+ if (foundAsSource) { // Found next published
+ // version of the checked
+ // in document
+ String fcontent = Files.readFile(pub
+ .getSourceFile().asFile());
+ foundAsSource = fcontent.contains(new File(
+ fileDTO.getPath()).getName());
+ if (foundAsSource) {
+ LOG.debug("Found new document with generated title: "
+ + pub.value().getTitle());
+ newPub = pub;
+ break;
+ }
+ }
+
+ String format = fileDTO.getPath().substring(
+ fileDTO.getPath().lastIndexOf('.') + 1);
+ org.splat.dal.bo.som.File attachment = pub
+ .value().getAttachedFile(format);
+ if (attachment != null) {
+ String fcontent = Files.readFile(attachment
+ .asFile());
+ if (fcontent.contains(new File(fileDTO
+ .getPath()).getName())) {
+ foundAsAttachment = true;
+ Assert.assertFalse(
+ new File(fileDTO.getPath())
+ .exists(),
+ "File"
+ + fileDTO.getPath()
+ + " was not removed from downloads directory.");
+ result.add("fileAttachedToANewDoc");
+ break;
+ }
+ }
+ }
+ }
+ Assert.assertTrue(foundAsSource || foundAsAttachment,
+ "New document or attachment is not created for checked in document \""
+ + docDTO.getTitle() + "\".");
+
+ if (foundAsSource) {
+
+ // TODO: check that all the conditions for this file
+ // to be chosen
+ // as fileToAttachTo are present.
+ // probably, drop some unimportant
+
+ // Check file content
+ Assert.assertTrue(Files.readFile(
+ newPub.getSourceFile().asFile()).contains(
+ new File(fileDTO.getPath()).getName()));
+
+ result.add("aNewSourceCreated");
+ // Check that uses relations are created correctly
+ Assert.assertTrue(
+ newPub.value()
+ .getTitle()
+ .startsWith(
+ newPub.value().getType()
+ .getName()
+ + "_"),
+ "Document title newPub.value().getTitle() must start with "
+ + newPub.value().getType()
+ .getName() + "_");
+
+ // 1. Find the document type used by this document
+ // type
+ Set<DocumentType> usedTypes = newPub.value()
+ .getType().getDefaultUses();
+ // 2. Find documents of used types in the current
+ // study step and previous study steps
+ for (Publication pub : aScen.getDocums()) {
+ if ((pub.getStep().getNumber() <= step
+ .getNumber())
+ && (!pub.isOutdated())
+ && usedTypes.contains(pub.value()
+ .getType())
+ && !newPub.equals(pub)) {
+ // 3. Check that there is uses relation to
+ // the found document
+ // if it is not outdated.
+ checkUsesRelation(newPub, pub);
+ }
+ }
+
+ // Check that files are moved correctly
+ checkFiles(docDTO, newPub);
+ }
+ }
+ }
+ }
+ }
+ return result;
+ }
+
+ /**
+ * Check if there is uses relation from the newPub to pub.
+ *
+ * @param newPub
+ * the new publication
+ * @param pub
+ * the publication to be used
+ */
+ private void checkUsesRelation(final Publication newPub,
+ final Publication pub) {
+ boolean uses = false;
+ boolean usesExist = false;
+ for (Publication usesPub : newPub.getRelations(UsesRelation.class)) {
+ usesExist = true;
+ uses = (usesPub.equals(pub));
+ if (uses) {
+ break;
+ }
+ }
+ Assert.assertTrue(usesExist && uses, "The created document "
+ + newPub.value().getTitle() + "("
+ + newPub.value().getType().getName() + ")"
+ + " has no uses relation to the document "
+ + pub.value().getTitle() + "("
+ + pub.value().getType().getName() + ")");
+ }
+
+ /**
+ * Check that files are moved correctly.
+ *
+ * @param docDTO
+ * checked in document DTO
+ * @param newPub
+ * the created document publication
+ */
+ private void checkFiles(final DocumentDTO docDTO, final Publication newPub) {
+ // Check that original files are deleted
+ for (int j = 0; j < docDTO.getFiles().size(); j++) {
+ FileDTO fileDTO = docDTO.getFiles().get(j);
+ Assert.assertFalse(new File(fileDTO.getPath()).exists(), "File"
+ + fileDTO.getPath()
+ + " was not removed from downloads directory.");
+ String format = fileDTO.getPath().substring(
+ fileDTO.getPath().lastIndexOf('.') + 1);
+ }
+ // TODO: Check file by its internal content
+ Assert.assertTrue(newPub.getSourceFile().exists(), "File "
+ + newPub.getSourceFile().asFile().getAbsolutePath()
+ + " for the document " + docDTO.getTitle()
+ + " was not created.");
+ }
+
+ /**
+ * Prepare a document with a file for check-in.
+ *
+ * @param stepTo
+ * step DTO with data for check-in
+ * @param module
+ * SALOME module name
+ * @param format
+ * file extension
+ * @param userId
+ * download directory
+ * @param stepFrom
+ * checked out stepDTO
+ * @param stepsToCheckin
+ * DTO for check-in
+ * @throws IOException
+ * if file creation failed
+ * @return step DTO with data prepared for check-in (stepTo or new if stepTo
+ * is null)
+ */
+ private StepDTO createDocDTOForModule(final StepDTO stepTo,
+ final String module, final String format, final long userId,
+ final StepDTO stepFrom, final List<StepDTO> stepsToCheckin)
+ throws IOException {
+ StepDTO stepToCheckin = stepTo;
+ if (stepToCheckin == null) {
+ stepToCheckin = new StepDTO();
+ }
+ if (module.equals(stepFrom.getModule())) {
+ stepsToCheckin.add(stepToCheckin);
+ stepToCheckin.setNumber(stepFrom.getNumber());
+ for (DocumentDTO doc : stepFrom.getDocs()) {
+ if (doc.getFiles().get(0).getState() != 'O') {
+ DocumentDTO docToCheckin = stepToCheckin.addDoc(
+ doc.getId(), doc.getTitle());
+ for (FileDTO file : doc.getFiles()) {
+ if (file.getPath().endsWith(format)
+ || (file.getPath().endsWith("py") && (format
+ .equals("brep") || format.equals("med")))) {
+ // Create a file in the download directory
+ if ("GEOM".equals(module)) {
+ // New version case
+ docToCheckin.addFile(createDownloadedFile(
+ userId, doc.getTitle() + "_newvers",
+ "py"));
+ } else {
+ // Attached generated result case
+ docToCheckin.addFile(createDownloadedFile(
+ userId, doc.getTitle() + "_result",
+ format));
+ }
+ }
+ }
+ }
+ }
+ // Prepare new data
+ stepToCheckin.addDoc(0, "newdoc" + stepFrom.getNumber()).addFile(
+ createDownloadedFile(userId,
+ "newdoc" + stepFrom.getNumber(), "brep"));
+ }
+ return stepToCheckin;
+ }
+
+ /**
+ * Tests a checkin testcase.
+ *
+ * @param testCaseNumber
+ * the test case number
+ * @param scenarioId
+ * the scenrio id
+ * @param userId
+ * the user id
+ * @param hasSource
+ * whether the scenario is supposed to have a source file in this
+ * test case befor checkin
+ * @param hasAttachments
+ * whether the scenario is supposed to have files attached to the
+ * source in this test case befor checkin
+ * @param checkinSource
+ * whether the "comm" file should be checked in
+ * @param checkinAttachment
+ * whether the "resu" and "mess" files should be checked in
+ * @return set of strings indicating which cases has occurred
+ * @throws IOException
+ * if something is wrong
+ * @throws InvalidPropertyException
+ * if something is wrong
+ * @throws MultiplyDefinedException
+ * if something is wrong
+ * @throws MissedPropertyException
+ * if something is wrong
+ * @throws SQLException
+ * if something is wrong
+ * @throws NotApplicableException
+ * if something is wrong
+ * @throws MismatchException
+ * if something is wrong
+ */
+ private Set<String> testCheckinTestcase(final long testCaseNumber,
+ final long scenarioId, final long userId, final boolean hasSource,
+ final boolean hasAttachments, final boolean checkinSource,
+ final boolean checkinAttachment) throws IOException,
+ InvalidPropertyException, MultiplyDefinedException,
+ MissedPropertyException, SQLException, NotApplicableException,
+ MismatchException {
+
+ Scenario aScen = _scenarioDAO.get(scenarioId);
+ User user = _userDAO.get(userId);
+
+ List<StepDTO> steps = _scenarioService.getScenarioInfo(scenarioId);
+
+ // ////////////////////////////////////////////////////////
+ // 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());
+ }
+ }
+
+ long targetDocId = addMecaDocsToScenario(testCaseNumber, aScen, user,
+ hasAttachments, hasSource);
+
+ List<StepDTO> stepsToCheckin = new ArrayList<StepDTO>();
+ for (StepDTO step : steps) {
+ createDocDTOForMeca(testCaseNumber, targetDocId, null, userId,
+ step, stepsToCheckin, checkinSource, checkinAttachment);
+ }
+
+ // /////////////////////////////////////////////////////////////////
+ // Do test checkin
+ _scenarioService.checkin(scenarioId, userId, stepsToCheckin);
+
+ // Check that scenario is no more marked as checked out
+ aScen = _scenarioDAO.get(scenarioId);
+ return assertCheckinValidity(testCaseNumber, stepsToCheckin, aScen,
+ dates);
+ }
+
+ /**
+ * It will delete any "comm" publications in the scenario, and then create a
+ * new one, with attachments if specified.
+ *
+ * @param testCaseNumber
+ * the test case number
+ * @param aScen
+ * the scenario
+ * @param user
+ * user who will be used as an author for the added documents
+ * @param hasAttachments
+ * whether to add the "comm" doc to the scenario
+ * @param hasSource
+ * whether to add "resu" and "mess" docs to the scenario
+ * @return the source document id, if exists, 0 otherwise.
+ * @throws IOException
+ * if something is wrong
+ * @throws InvalidPropertyException
+ * if something is wrong
+ * @throws MissedPropertyException
+ * if something is wrong
+ * @throws MultiplyDefinedException
+ * if something is wrong
+ */
+ private long addMecaDocsToScenario(final long testCaseNumber,
+ final Scenario aScen, final User user,
+ final boolean hasAttachments, final boolean hasSource)
+ throws IOException, InvalidPropertyException,
+ MissedPropertyException, MultiplyDefinedException {
+
+ long res = 0;
+ org.splat.som.Step mecaStep = null;
+ for (org.splat.som.Step step : _projectElementService.getSteps(aScen)) {
+ if ("SALOME_MECA".equals(step.getStep().getModule())) {
+ mecaStep = step;
+ }
+ }
+
+ // remove comm documents
+ List<Publication> toRemove = new ArrayList<Publication>();
+ for (Publication pub : mecaStep.getDocuments()) {
+ if ("comm".equals(pub.value().getFormat())) {
+ toRemove.add(pub);
+ }
+ }
+ for (Publication pub : toRemove) {
+ // remove relations so the publication can be removed correctly
+ List<Relation> relations = new ArrayList<Relation>();
+ relations.addAll(pub.value().getAllRelations());
+ for (Relation rel : relations) {
+ pub.value().removeRelation(UsesRelation.class, rel.getTo());
+ }
+ aScen.remove(pub);
+ }
+
+ if (hasSource) {
+ // Select result document type for Meca step
+ List<DocumentType> dtypes = _documentTypeService
+ .selectTypesOf(mecaStep.getStep());
+ DocumentType resultType = null;
+ for (DocumentType doctype : dtypes) {
+ if (doctype.isResultOf(mecaStep.getStep())) {
+ resultType = doctype;
+ break;
+ }
+ }
+
+ Document.Properties dprop = new Document.Properties();
+ File directory = _repositoryService.getDownloadDirectory(user);
+ directory.mkdirs();
+ dprop.setName("commDoc" + testCaseNumber).setFormat("comm")
+ .setAuthor(user).setDate(new Date()).setType(resultType)
+ .setLocalPath(dprop.getName() + "." + dprop.getFormat());
+
+ Publication commPub = createDoc(aScen, mecaStep, dprop, "", false);
+ // The following is necessary because createDoc does not do all
+ // required work
+ // (and PublicationServiceImpl.createDoc() is complicated so it's
+ // harder to make it work)
+ commPub.setStep(mecaStep);
+ aScen.getDocums().add(commPub);
+ mecaStep.getDocuments().add(commPub);
+
+ res = commPub.value().getIndex();
+
+ // add attachments
+ if (hasAttachments) {
+ // Create new "resu" file
+ FileDTO resuFileDTO = createDownloadedFile(user.getIndex(),
+ "resuFile", "resu");
+ ConvertsRelation export = _publicationService.attach(commPub,
+ "resu");
+ File resuFile = new File(resuFileDTO.getPath());
+ File dest = export.getTo().asFile();
+ dest.delete();
+ Assert.assertTrue(resuFile.renameTo(dest));
+
+ // Create new "mess" file
+ FileDTO messFileDTO = createDownloadedFile(user.getIndex(),
+ "messFile", "mess");
+ export = _publicationService.attach(commPub, "mess");
+ File messFile = new File(messFileDTO.getPath());
+ dest = export.getTo().asFile();
+ dest.delete();
+ Assert.assertTrue(messFile.renameTo(dest));
+ }
+ }
+
+ return res;
+ }
+
+ /**
+ * Prepare a document with a file for check-in.
+ *
+ * @param stepTo
+ * step DTO with data for check-in
+ * @param userId
+ * download directory
+ * @param stepFrom
+ * checked out stepDTO
+ * @param stepsToCheckin
+ * DTO for check-in
+ * @param createSource
+ * whether to add the COMM file to the DTO
+ * @param createAttachment
+ * whether to add the RESU and MESS files to the DTO
+ * @throws IOException
+ * if file creation failed
+ * @return step DTO with data prepared for check-in (stepTo or new if stepTo
+ * is null)
+ */
+ private StepDTO createDocDTOForMeca(final long testCaseNumber,
+ final long targetDocId, final StepDTO stepTo, final long userId,
+ final StepDTO stepFrom, final List<StepDTO> stepsToCheckin,
+ final boolean createSource, final boolean createAttachment)
+ throws IOException {
+ StepDTO stepToCheckin = stepTo;
+ if (stepToCheckin == null) {
+ stepToCheckin = new StepDTO();
+ }
+ if ("SALOME_MECA".equals(stepFrom.getModule())) {
+
+ stepsToCheckin.add(stepToCheckin);
+ stepToCheckin.setNumber(stepFrom.getNumber());
+
+ DocumentDTO docToCheckin = stepToCheckin.addDoc(targetDocId,
+ "newCommDoc");
+
+ if (createSource) {
+ docToCheckin.addFile(createDownloadedFile(userId, "newCommDoc"
+ + testCaseNumber + "_result", "comm"));
+ }
+ if (createAttachment) {
+ docToCheckin.addFile(createDownloadedFile(userId, "newResuDoc"
+ + testCaseNumber + "_result", "resu"));
+ docToCheckin.addFile(createDownloadedFile(userId, "newMessDoc"
+ + testCaseNumber + "_result", "mess"));
+ }
+ }
+ return stepToCheckin;
+ }
+
+ /**
+ * 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);
+ }
+
+ /**
+ * 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);
+ }
+
+ /**
+ * Create a persistent scenario for tests.
+ *
+ * @return a persistent scenario
+ * @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 document creation is failed
+ * @throws SQLException
+ * if project settings loading is failed
+ */
+ private long createScenario() throws InvalidPropertyException,
+ MissedPropertyException, MultiplyDefinedException, IOException,
+ SQLException {
+ // Create a scenario for tests
+ HibernateTemplate ht = getHibernateTemplate();
+
+ Database.getInstance().reset();
+ _projectSettings.getAllSteps().clear(); // Clear config to be able to
+ // load it again
+ // Load workflow customization
+ try {
+ _projectSettings.configure("classpath:test/som.xml");
+ } catch (FileNotFoundException e) {
+ Assert.fail("Can't find som.xml: ", e);
+ }
+ List<Step> steps = _stepsConfigService.getStepsOf(Scenario.class);
+ Assert.assertTrue(steps.size() > 0, "No steps are created.");
+
+ // Create a test user
+ User.Properties uprop = new User.Properties();
+ uprop.setUsername("TST_Username").setName("TST_SimanUnitTestsUser")
+ .setFirstName("TST_FirstName").setDisplayName("TST_test.user")
+ .addRole("TST_user")
+ .setMailAddress("noreply@salome-platform.org");
+ uprop.disableCheck();
+ User anAuthor = new User(uprop);
+ ht.saveOrUpdate(anAuthor);
+
+ // Create a test study
+ Study.Properties stprops = new Study.Properties()
+ .setReference("TST_SID_01").setTitle("TST_Study")
+ .setManager(anAuthor);
+ Study aStudy = new Study(stprops);
+ ht.saveOrUpdate(aStudy);
+
+ // Create a test scenario
+ Scenario.Properties sprops = new Scenario.Properties()
+ .setTitle("TST_Scenario").setManager(anAuthor)
+ .setOwnerStudy(aStudy);
+ Scenario aScenario = new Scenario(sprops);
+ aStudy.getScenariiList().add(aScenario);
+ ht.saveOrUpdate(anAuthor);
+ ht.saveOrUpdate(aStudy);
+ ht.saveOrUpdate(aScenario);
+
+ // Create documents for each scenario step
+ Document.Properties dprop = new Document.Properties().setAuthor(
+ anAuthor).setDate(new Date());
+ int i = 0;
+ Publication usedPub = null;
+ Map<Long, Long> usedMap = new HashMap<Long, Long>();
+ for (Step step : steps) {
+ LOG.debug("Create scenario step: " + i);
+
+ org.splat.som.Step aScStep = new org.splat.som.Step(step, aScenario);
+ List<DocumentType> dtypes = _documentTypeService
+ .selectTypesOf(step);
+ for (DocumentType dtype : dtypes) {
+ // Create a document published in the scenario
+ // document<i>: document type[0] - first type used on the step
+ // <source-file>.brep
+ // <attached-file>.med
+ dprop.setName("document" + i++).setType(dtype);
+ /*
+ * 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);
+ if (usedPub != null) {
+ pub.addDependency(usedPub);
+ ht.saveOrUpdate(pub.value());
+
+ usedMap.put(pub.getIndex(), usedPub.getIndex());
+ }
+ usedPub = pub;
+
+ // Create another document with outdated publication
+ dprop.setName("document" + i++).setType(dtype).setFormat("py");
+ dprop.setLocalPath(dprop.getName() + "." + dprop.getFormat());
+ createDoc(aScenario, aScStep, dprop, "med", true);
+
+ }
+ if (dtypes.size() <= 0) {
+ LOG.debug("No document types are found for scenario step " + i);
+ }
+ }
+
+ // Check that the scenario and its documents have been created
+ // correctly.
+
+ Assert.assertNotNull(ht.find("from Document"),
+ "No documents in the database.");
+ Assert.assertTrue(ht.find("from Document").size() > 0,
+ "No documents in the database.");
+
+ Assert.assertNotNull(
+ ht.find("from Publication where owner=" + aScenario.getIndex()),
+ "No publications in the database.");
+ Assert.assertTrue(
+ ht.find("from Publication where owner=" + aScenario.getIndex())
+ .size() > 0, "No publications in the database.");
+
+ for (Publication p : (List<Publication>) ht
+ .find("from Publication where owner=" + aScenario.getIndex())) {
+ LOG.debug("Publication found: [id=" + p.getIndex() + ", owner="
+ + p.getOwner().getIndex() + ", doc=" + p.value().getIndex()
+ + "]");
+ Assert.assertEquals(p.getOwner().getIndex(), aScenario.getIndex(),
+ "The publication was not attached to the scenario.");
+ }
+
+ // Remove the scenario from the current hibernate session.
+ ht.evict(aScenario);
+ // Check that the scenario is created in the database.
+ Scenario aScen = ht.load(Scenario.class, aScenario.getIndex());
+ Assert.assertNotNull(aScen, "Scenario was not saved in the database.");
+ Assert.assertTrue(aScen.getDocums().size() > 0,
+ "No publications in the scenario.");
+
+ Assert.assertTrue(i > 0,
+ "More then one document must be in the database");
+
+ // Check created uses relations
+ Assert.assertTrue(usedMap.size() > 0, "Uses relations must be created.");
+ boolean foundAny = false;
+ for (Long usingId : usedMap.keySet()) {
+ for (Publication pub : aScen.getDocums()) {
+ if (pub.getIndex() == usingId) {
+ boolean found = false;
+ for (Publication used : aScen.getDocums()) {
+ found = (used.getIndex() == usedMap.get(usingId));
+ if (found) {
+ break;
+ }
+ }
+ Assert.assertTrue(found,
+ "Uses relation was not created in the database.");
+ foundAny = foundAny || found;
+ }
+ }
+ }
+ Assert.assertTrue(foundAny,
+ "No Uses relation was created in the database.");
+
+ return aScenario.getIndex();
+ }
+
+ /**
+ * Create a document published in the scenario. <BR>
+ * document:<BR>
+ * document type[0] - first type used on the step <BR>
+ * <source-file>.brep <BR>
+ * <attached-file>.med
+ *
+ * @param aScenario
+ * v
+ * @param aScStep
+ * scenario step where the document to be published
+ * @param dprop
+ * document properties
+ * @param attachedFileExt
+ * extension of the secon attached (exported) file
+ * @param isOutdated
+ * outdated document flag
+ * @return the publication of the created document
+ * @throws IOException
+ * @throws MultiplyDefinedException
+ * @throws InvalidPropertyException
+ * @throws MissedPropertyException
+ */
+ private Publication createDoc(final Scenario aScenario,
+ final org.splat.som.Step aScStep, final Properties dprop,
+ final String attachedFileExt, final boolean isOutdated)
+ throws MissedPropertyException, InvalidPropertyException,
+ MultiplyDefinedException, IOException {
+ // Create a document published in the scenario
+ // document<i>: document type[0] - first type used on the step
+ // <source-file>.brep
+ // <attached-file>.med
+ createDownloadedFile(aScenario.getAuthor().getIndex(),
+ dprop.getLocalPath());
+ Publication pub = _stepService.createDocument(aScStep, dprop);
+ Assert.assertNotNull(pub.getOwner(),
+ "The publication must be attached to the scenario.");
+ Assert.assertEquals(pub.getOwner().getIndex(), aScenario.getIndex(),
+ "The publication was not attached to the scenario.");
+
+ if (isOutdated) {
+ pub.setIsnew('O');
+ }
+ aScenario.add(pub);
+ HibernateTemplate ht = getHibernateTemplate();
+ ht.saveOrUpdate(pub);
+
+ // Attach a file
+ createDownloadedFile(
+ aScenario.getAuthor().getIndex(),
+ dprop.getLocalPath().substring(0,
+ dprop.getLocalPath().lastIndexOf(".") - 1),
+ attachedFileExt);
+ ht.save(pub.value());
+ ht.saveOrUpdate(_publicationService.attach(pub, attachedFileExt));
+
+ return pub;
+ }
+
+ /**
+ * 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 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("classpath:test/som.xml");
+
+ // Create a test user
+ User.Properties uprop = new User.Properties();
+ uprop.setUsername("TST_Username").setName("TST_SimanUnitTestsUser")
+ .setFirstName("TST_FirstName").setDisplayName("TST_test.user")
+ .addRole("TST_user")
+ .setMailAddress("noreply@salome-platform.org");
+ uprop.disableCheck();
+ User anAuthor = new User(uprop);
+
+ getHibernateTemplate().saveOrUpdate(anAuthor);
+ KnowledgeElementType ucase = _knowledgeElementTypeService
+ .selectType("usecase");
+ Assert.assertNotNull(ucase,
+ "Knowledge type 'usecase' must be created in the database.");
+ SimulationContextType prodtype = _simulationContextService
+ .selectType("product");
+ Assert.assertNotNull(prodtype,
+ "Simulation context type 'product' must be created in the database.");
+
+ // Create admin
+ uprop.clear();
+ uprop.setUsername("TST_Admin").setName("TST_SimanUnitTestsAdmin")
+ .setFirstName("TST_AdminFirstName")
+ .setDisplayName("TST_test.admin").addRole("TST_user,sysadmin")
+ .setMailAddress("noreply@salome-platform.org");
+ uprop.disableCheck();
+
+ getHibernateTemplate().saveOrUpdate(new User(uprop));
+ getHibernateTemplate().flush();
+
+ Study.Properties sprop = new Study.Properties();
+ sprop.setTitle("Test study creation").setManager(anAuthor);
+ Scenario.Properties oprop = new Scenario.Properties();
+ oprop.setTitle("Test scenario for the created study");
+
+ // Addition of the entered project context
+ SimulationContext.Properties cprop = new SimulationContext.Properties();
+ // Input of new project context
+ cprop.setType(_simulationContextService.selectType("product"))
+ .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);
+ ht.flush();
+ //
+ // 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() + "]");
+ ht.flush();
+
+ // 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(pub31);
+ 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()");
+ }
+
+ /**
+ * 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.");
+ }