1 /*****************************************************************************
5 * Creation date 12 Oct 2012
8 *****************************************************************************/
9 package test.splat.service;
12 import java.io.FileNotFoundException;
13 import java.io.FileWriter;
14 import java.io.IOException;
15 import java.sql.SQLException;
16 import java.util.ArrayList;
17 import java.util.Date;
18 import java.util.HashMap;
19 import java.util.Iterator;
20 import java.util.List;
24 import org.splat.dal.bo.kernel.Relation;
25 import org.splat.dal.bo.kernel.User;
26 import org.splat.dal.bo.som.ConvertsRelation;
27 import org.splat.dal.bo.som.Document;
28 import org.splat.dal.bo.som.DocumentType;
29 import org.splat.dal.bo.som.KnowledgeElementType;
30 import org.splat.dal.bo.som.Publication;
31 import org.splat.dal.bo.som.Scenario;
32 import org.splat.dal.bo.som.SimulationContext;
33 import org.splat.dal.bo.som.SimulationContextType;
34 import org.splat.dal.bo.som.Study;
35 import org.splat.dal.bo.som.UsedByRelation;
36 import org.splat.dal.bo.som.UsesRelation;
37 import org.splat.dal.bo.som.ValidationCycle;
38 import org.splat.dal.bo.som.ValidationCycleRelation;
39 import org.splat.dal.bo.som.ValidationStep;
40 import org.splat.dal.bo.som.Document.Properties;
41 import org.splat.dal.dao.kernel.UserDAO;
42 import org.splat.dal.dao.som.Database;
43 import org.splat.dal.dao.som.ScenarioDAO;
44 import org.splat.dal.dao.som.StudyDAO;
45 import org.splat.dal.dao.som.ValidationCycleDAO;
46 import org.splat.exception.BusinessException;
47 import org.splat.exception.InvalidParameterException;
48 import org.splat.i18n.I18nUtils;
49 import org.splat.kernel.InvalidPropertyException;
50 import org.splat.kernel.MismatchException;
51 import org.splat.kernel.MissedPropertyException;
52 import org.splat.kernel.MultiplyDefinedException;
53 import org.splat.kernel.NotApplicableException;
54 import org.splat.log.AppLogger;
55 import org.splat.service.DocumentTypeService;
56 import org.splat.service.KnowledgeElementTypeService;
57 import org.splat.service.ProjectElementService;
58 import org.splat.service.PublicationService;
59 import org.splat.service.ScenarioService;
60 import org.splat.service.SimulationContextService;
61 import org.splat.service.StepService;
62 import org.splat.service.StudyService;
63 import org.splat.service.dto.DocumentDTO;
64 import org.splat.service.dto.FileDTO;
65 import org.splat.service.dto.ScenarioDTO;
66 import org.splat.service.dto.StepDTO;
67 import org.splat.service.technical.ProjectSettingsService;
68 import org.splat.service.technical.RepositoryService;
69 import org.splat.service.technical.StepsConfigService;
70 import org.splat.service.technical.ProjectSettingsService.Step;
71 import org.springframework.beans.factory.annotation.Autowired;
72 import org.springframework.beans.factory.annotation.Qualifier;
73 import org.springframework.orm.hibernate3.HibernateTemplate;
74 import org.testng.Assert;
75 import org.testng.annotations.Test;
76 import org.testng.reporters.Files;
78 import test.splat.common.BaseTest;
79 import test.splat.util.TestEntitiesGenerator;
82 * Test class for ScenarioService.
84 * @author <a href="mailto:roman.kozlov@opencascade.com">Roman Kozlov (RKV)</a>
87 public class TestScenarioService extends BaseTest {
90 * Logger for the class.
92 private static final AppLogger LOG = AppLogger
93 .getLogger(TestScenarioService.class);
96 * The tested ScenarioService. Later injected by Spring.
99 @Qualifier("scenarioService")
100 private transient ScenarioService _scenarioService;
103 * The RepositoryService. Later injected by Spring.
106 @Qualifier("repositoryService")
107 private transient RepositoryService _repositoryService;
110 * The Scenario DAO. Later injected by Spring.
113 @Qualifier("scenarioDAO")
114 private transient ScenarioDAO _scenarioDAO;
117 * The PublicationService. Later injected by Spring.
120 @Qualifier("publicationService")
121 private transient PublicationService _publicationService;
124 * The StepService. Later injected by Spring.
127 @Qualifier("stepService")
128 private transient StepService _stepService;
131 * The SimulationContextService. Later injected by Spring.
134 @Qualifier("simulationContextService")
135 private transient SimulationContextService _simulationContextService;
138 * The ProjectSettingsService. Later injected by Spring.
141 @Qualifier("projectSettings")
142 private transient ProjectSettingsService _projectSettings;
145 * The StepsConfigService. Later injected by Spring.
148 @Qualifier("stepsConfigService")
149 private transient StepsConfigService _stepsConfigService;
152 * The DocumentTypeService. Later injected by Spring.
155 @Qualifier("documentTypeService")
156 private transient DocumentTypeService _documentTypeService;
159 * The KnowledgeElementTypeService. Later injected by Spring.
162 @Qualifier("knowledgeElementTypeService")
163 private transient KnowledgeElementTypeService _knowledgeElementTypeService;
166 * The UserDAO. Later injected by Spring.
169 @Qualifier("userDAO")
170 private transient UserDAO _userDAO;
173 * The StudyService. Later injected by Spring.
176 @Qualifier("studyService")
177 private transient StudyService _studyService;
180 * The StudyDAO. Later injected by Spring.
183 @Qualifier("studyDAO")
184 private transient StudyDAO _studyDAO;
187 * The ValidationCycleDAO. Later injected by Spring.
190 @Qualifier("validationCycleDAO")
191 private transient ValidationCycleDAO _validationCycleDAO;
194 * The ProjectElementService. Later injected by Spring.
197 @Qualifier("projectElementService")
198 private transient ProjectElementService _projectElementService;
201 * Test of getting a scenario content for building siman-salome.conf.<BR>
202 * <B>Description :</B> <BR>
203 * <i>Create a scenario and try to get an info for it.</i><BR>
204 * <B>Action : </B><BR>
205 * <i>1. call the method for an existing scenario id.</i><BR>
206 * <i>2. call the method for a not existing scenario id.</i><BR>
207 * <B>Test data : </B><BR>
208 * <i>no input parameters</i><BR>
209 * <i>no input parameters</i><BR>
211 * <B>Outcome results:</B><BR>
214 * <li>result DTO must contain list of all documents and files<BR>
216 * <li>Exception is thrown<BR>
221 * @throws InvalidPropertyException
222 * if an invalid property is used when creating objects
223 * @throws MultiplyDefinedException
224 * when trying to create an object with already existing id
225 * @throws MissedPropertyException
226 * if a mandatory property is not defined for an object to be created
227 * @throws IOException
228 * if scenario creation is failed
229 * @throws SQLException
230 * if scenario creation is failed
232 @Test(groups = { "checkout", "sevice", "functional", "business" })
233 public void testGetScenarioInfo() throws InvalidPropertyException,
234 MissedPropertyException, MultiplyDefinedException, IOException,
236 LOG.debug(">>>>> BEGIN testGetScenarioInfo()");
237 startNestedTransaction();
239 long scenarioId = createScenario();
240 // Call DAO's create method for a good transient knowledge element.
241 List<StepDTO> steps = _scenarioService.getScenarioInfo(scenarioId);
242 Assert.assertNotNull(steps, "List of steps must not be null.");
243 Assert.assertTrue(steps.size() > 0, "No steps are read.");
245 List<Step> projSteps = _stepsConfigService.getStepsOf(Scenario.class);
246 Assert.assertEquals(steps.size(), projSteps.size(),
247 "Not all steps are listed.");
249 for (StepDTO step : steps) {
250 LOG.debug("check the step " + step.getNumber() + ":\n" + step);
251 Assert.assertNotNull(step, "Step DTO must not be null.");
252 Assert.assertNotNull(step.getKey(), "Step name must not be null.");
253 Assert.assertFalse(step.getKey().isEmpty(),
254 "Step name must not empty.");
255 Assert.assertTrue(step.getNumber() > 0,
256 "Step number must be positive integer.");
257 Assert.assertNotNull(step.getDocs(),
258 "Step documents list must not be null.");
260 Step aProjStep = null;
261 for (Step projStep : projSteps) {
262 if (projStep.getNumber() == step.getNumber()) {
263 aProjStep = projStep;
268 List<DocumentType> dtypes = _documentTypeService
269 .selectTypesOf(aProjStep);
270 for (DocumentType dtype : dtypes) {
271 Assert.assertTrue(step.getDocs().size() > 0,
272 "Step documents list must not be empty.");
273 String docName = "document" + docIndex;
274 for (DocumentDTO doc : step.getDocs()) {
275 if (docName.equals(doc.getTitle())) {
276 Assert.assertTrue(doc.getId() > 0,
277 "Document id must be positive integer.");
278 Assert.assertEquals(doc.getTitle(), docName);
279 Assert.assertNotNull(doc.getFiles(),
280 "Document files list must not be null.");
282 .assertTrue(doc.getFiles().size() > 1,
283 "Document must have more then 1 attached file.");
285 for (FileDTO file : doc.getFiles()) {
286 Assert.assertNotNull(file.getPath(),
287 "File path must not be null.");
288 Assert.assertFalse(file.getPath().isEmpty(),
289 "File path must not be empty.");
291 * <mappings> <document type="geometry"> <import format="brep"/> <!-- Result Shape --> </document> <document
292 * type="model"> <import format="med"/> <!-- Result mesh without input parameters --> </document> <document
293 * type="loads"> <import format="c3m"/> <!-- Input data created interactively --> </document> <document
294 * type="results"> <import format="med"/> <!-- Calculation results source file --> </document> </mappings>
296 // Check state and processing instruction
297 String fileFormat = file.getPath().substring(
298 file.getPath().lastIndexOf('.') + 1);
300 * if (_projectSettings.doImport(dtype.getName(), fileFormat)) { Assert.assertTrue(file.isResult(), "The file
301 * must be a result file."); } else { Assert.assertFalse(file.isResult(), "The file must be a source file."); }
302 */if ((docIndex % 2) == 0) { // New
303 Assert.assertEquals(file.getState(), 'Y',
304 "File state must be actual ('Y').");
305 if (_projectSettings.doImport(dtype.getName(),
307 Assert.assertEquals(file.getProcessing(),
309 "File must be imported.");
311 Assert.assertEquals(file.getProcessing(),
313 "File must be downloaded.");
316 Assert.assertEquals(file.getState(), 'O',
317 "File state must be outdated ('O').");
319 .assertEquals(file.getProcessing(),
321 "Outdated document should not be imported but downloaded.");
330 // Call DAO's get method for a not existing id.
332 steps = _scenarioService.getScenarioInfo(-1L);
333 // getHibernateTemplate().flush();
335 .fail("Getting an object with not existing id must be failed.");
336 } catch (Exception e) {
337 LOG.debug("Expected exception is thrown: "
338 + e.getClass().getSimpleName() + ": " + e.getMessage());
340 rollbackNestedTransaction();
341 LOG.debug(">>>>> END testGetScenarioInfo()");
345 * Test check-in scenario operation to be performed after SALOME session.<BR>
346 * <B>Description :</B> <BR>
347 * <i>Create a scenario and try to check-in it with some simulated SALOME results data.<BR>
348 * After check-in verify following points:
350 * <li>scenario is no more marked as checked out</li>
351 * <li>new document versions are created for checked in documents</li>
352 * <li>presentation of the previous version is removed</li>
353 * <li>uses relations are copied correctly</li>
354 * <li>files are moved correctly</li>
355 * <li>formats of files are new if they are according to the document's type on the study step</li>
356 * <li>new documents are created for new data</li>
357 * <li>new documents have correctly generated names</li>
358 * <li>uses relations are created correctly</li>
359 * <li>files are moved correctly</li>
362 * <B>Action : </B><BR>
363 * <i>1. call the method for an existing scenario id.</i><BR>
364 * <i>2. call the method for a not existing scenario id.</i><BR>
365 * <B>Test data : </B><BR>
366 * <i>no input parameters</i><BR>
367 * <i>no input parameters</i><BR>
369 * <B>Outcome results:</B><BR>
372 * <li>New version of existing documents must be created and new documents must be imported for documents with zero id. Correct
373 * relations must be created.<BR>
375 * <li>Exception is thrown<BR>
380 * @throws InvalidPropertyException
381 * if an invalid property is used when creating objects
382 * @throws MultiplyDefinedException
383 * when trying to create an object with already existing id
384 * @throws MissedPropertyException
385 * if a mandatory property is not defined for an object to be created
386 * @throws IOException
387 * if scenario creation is failed
388 * @throws SQLException
389 * if scenario creation is failed
390 * @throws NotApplicableException
392 * @throws MismatchException
395 @Test(groups = { "checkin", "sevice", "functional", "business" })
396 public void testCheckin() throws InvalidPropertyException,
397 MissedPropertyException, MultiplyDefinedException, IOException,
398 SQLException, MismatchException, NotApplicableException {
399 LOG.debug(">>>>> BEGIN testCheckin()");
400 startNestedTransaction();
402 _projectSettings.getAllSteps().clear(); // Clear config to be able to load it again
403 _projectSettings.configure("classpath:test/som.xml");
404 getHibernateTemplate().flush();
405 long scenarioId = createScenario();
406 Scenario aScen = _scenarioDAO.get(scenarioId);
407 User user = aScen.getAuthor();
408 long userId = user.getIndex();
410 // ////////////////////////////////////////////////////////
411 // Call checkin method for empty list of modules.
414 List<StepDTO> steps = _scenarioService.getScenarioInfo(scenarioId);
415 _scenarioService.checkout(aScen, user);
416 _scenarioDAO.flush();
417 // Check that scenario is no more marked as checked out
418 aScen = _scenarioDAO.get(scenarioId);
419 Assert.assertTrue(aScen.isCheckedout(),
420 "Scenario is not marked as checked out after checkout.");
422 // Prepare test data for checkin
423 // Checkin only two first steps (geom and mesh)
424 List<StepDTO> stepsToCheckin = new ArrayList<StepDTO>();
426 _scenarioService.checkin(scenarioId, userId, stepsToCheckin);
428 _scenarioDAO.flush();
429 // Check that scenario is no more marked as checked out
430 aScen = _scenarioDAO.get(scenarioId);
431 Assert.assertFalse(aScen.isCheckedout(),
432 "Scenario is still marked as checked out after checkin.");
434 // ////////////////////////////////////////////////////////
435 // Call checkin method for good prepared transient data.
438 steps = _scenarioService.getScenarioInfo(scenarioId);
439 _scenarioService.checkout(aScen, user);
441 // Remember modification dates of all attached files
442 Map<Long, Date> dates = new HashMap<Long, Date>();
443 for (Publication p : aScen.getDocums()) {
444 for (Relation r : p.value().getRelations(ConvertsRelation.class)) {
445 org.splat.dal.bo.som.File attach = ((ConvertsRelation) r)
447 dates.put(attach.getIndex(), attach.getDate());
451 // Prepare test data for checkin
452 // Checkin only two first steps (geom and mesh)
453 for (StepDTO step : steps) {
454 // Prepare GEOM: checkin actual brep
455 StepDTO stepToCheckin = createDocDTOForModule(null, "GEOM", "brep",
456 userId, step, stepsToCheckin);
457 createDocDTOForModule(stepToCheckin, "SMESH", "med", userId, step,
461 _scenarioService.checkin(scenarioId, userId, stepsToCheckin);
463 _scenarioDAO.flush();
464 // Check that scenario is no more marked as checked out
465 aScen = _scenarioDAO.get(scenarioId);
466 Assert.assertFalse(aScen.isCheckedout(),
467 "Scenario is still marked as checked out after checkin.");
468 boolean modifDatesChecked = false;
469 // Check that new document versions are created for checked in documents
470 for (StepDTO step : stepsToCheckin) {
471 for (DocumentDTO docDTO : step.getDocs()) {
472 if ((docDTO.getId() != 0) && (docDTO.getId() != null)) {
473 boolean found = false;
474 Document prevDoc = null;
475 Document curDoc = null;
476 Publication newPub = null;
477 for (Publication pub : aScen.getDocums()) {
478 prevDoc = pub.value().getPreviousVersion();
479 if (prevDoc != null) {
480 found = (prevDoc.getIndex() == docDTO.getId());
481 if (found) { // Found next published version of the checked in document
486 if (pub.value().getIndex() == docDTO.getId()) {
487 // Document version was not changed, old document is still published
488 curDoc = pub.value();
492 Assert.assertTrue(found || (curDoc != null),
493 "New version or new attached file of the existing checked in document \""
494 + docDTO.getTitle() + "\" (id="
496 + ") is not found in the scenario.");
497 // If previous version is found then the format must be the same
498 String newFormat = docDTO.getFiles().get(0).getPath()
500 docDTO.getFiles().get(0).getPath()
501 .lastIndexOf('.') + 1);
503 Assert.assertEquals(prevDoc.getFormat(), newFormat,
504 "Formats of versions must be same");
505 Assert.assertFalse(aScen.publishes(prevDoc));
506 // Check that presentation of the previous version is removed
507 checkFiles(docDTO, newPub);
509 // Formats of files are new if they are according to the document's type on the study step
510 if ("py".equals(prevDoc.getFormat())
511 && "geometry".equals(prevDoc.getType()
513 Assert.assertEquals(newPub.value().getFormat(),
515 Assert.assertEquals(newPub.getSourceFile()
516 .getFormat(), "brep");
517 Assert.assertEquals(newPub.getSourceFile()
518 .getRelativePath().substring(
519 newPub.getSourceFile()
521 .lastIndexOf('.') + 1),
525 // Check that uses relations are copied correctly
527 // 1. Get all uses relations of the previous document version
528 for (Relation rel : prevDoc
529 .getRelations(UsesRelation.class)) {
530 Document used = ((UsesRelation) rel).getTo();
531 // 2.1. Get the latest version of the document published in this scenario
532 Publication toBeUsed = aScen.getPublication(used);
533 if (toBeUsed == null) {
534 // Find the latest published version
535 for (Publication lastPub : aScen.getDocums()) {
536 if ((lastPub.value().getPreviousVersion() != null)
538 .getPreviousVersion()
546 if ((toBeUsed != null) && (!toBeUsed.isOutdated())) {
547 // 2.2. For each used document check that its latest not outdated version
548 // is used by the new checked in document version.
549 checkUsesRelation(newPub, toBeUsed);
552 // 1. Get all usedBy relations of the previous document version
553 for (Relation rel : prevDoc
554 .getRelations(UsedByRelation.class)) {
555 Document using = ((UsedByRelation) rel).getTo();
556 // Check that not checked in dependent documents became outdated
557 Publication usingPub = aScen.getPublication(using);
558 if (usingPub != null) { // if the document using the old version is still published
559 Assert.assertTrue(usingPub.isOutdated(),
560 "Not checked in dependent document "
561 + using.getTitle() + " ("
562 + using.getType().getName()
563 + ") must become outdated.");
567 // Otherwise the new file format must differ from the previous one
568 // and the new file must be attached to the same document
569 org.splat.dal.bo.som.File attFile = curDoc
570 .getAttachedFile(newFormat);
571 Assert.assertNotNull(attFile, "File "
572 + docDTO.getFiles().get(0).getPath()
573 + " must be attached to the document "
574 + docDTO.getTitle() + "#" + docDTO.getId());
575 Assert.assertTrue(attFile.asFile().exists(), "File "
576 + docDTO.getFiles().get(0).getPath()
577 + " attached to the document "
578 + docDTO.getTitle() + "#" + docDTO.getId()
580 LOG.debug("Source format: " + curDoc.getFormat()
581 + ", new format: " + newFormat);
582 // Check that attachment with the same format is not duplicated.
584 for (Relation conv : curDoc
585 .getRelations(ConvertsRelation.class)) {
586 if (newFormat.equals(((ConvertsRelation) conv)
587 .getTo().getFormat())) {
592 .assertEquals(attachNb, 1,
593 "Attachment with the same format must be only one.");
595 // Check that the attached file date is updated
596 if (dates.containsKey(attFile.getIndex())) {
598 .assertTrue(attFile.getDate().compareTo(
599 dates.get(attFile.getIndex())) > 0,
600 "Attachment modification date is not updated.");
601 modifDatesChecked = true;
606 // Check that new documents are created for new data
607 boolean found = false;
608 Publication newPub = null;
609 for (Publication pub : aScen.getDocums()) {
610 if (pub.value().getPreviousVersion() == null) {
611 found = (pub.value().getTitle().startsWith(pub
612 .value().getType().getName()));
613 if (found) { // Found next published version of the checked in document
614 String fcontent = Files.readFile(pub
615 .getSourceFile().asFile());
616 found = fcontent.contains(docDTO.getTitle());
619 .debug("Found new document with generated title: "
620 + pub.value().getTitle());
627 Assert.assertTrue(found,
628 "New document is not created for checked in document \""
629 + docDTO.getTitle() + "\".");
631 // Check that uses relations are created correctly
632 Assert.assertTrue(newPub.value().getTitle().startsWith(
633 newPub.value().getType().getName() + "_"),
634 "Document title newPub.value().getTitle() must start with "
635 + newPub.value().getType().getName() + "_");
637 // 1. Find the document type used by this document type
638 Set<DocumentType> usedTypes = newPub.value().getType()
640 // 2. Find documents of used types in the current study step and previous study steps
641 for (Publication pub : aScen.getDocums()) {
642 if ((pub.getStep().getNumber() <= step.getNumber())
643 && (!pub.isOutdated())
644 && usedTypes.contains(pub.value().getType())) {
645 // 3. Check that there is uses relation to the found document
646 // if it is not outdated.
647 checkUsesRelation(newPub, pub);
651 // Check that files are moved correctly
652 checkFiles(docDTO, newPub);
660 "No modification date is checked because no files were attached when attachment with same extension already exists.");
662 // ///////////////////////////////////////////////////////////
663 // Call checkin method for a not existing id.
665 _scenarioService.checkin(-1, userId, stepsToCheckin);
667 .fail("Check in for scenario with not existing id must be failed.");
668 } catch (Exception e) {
669 LOG.debug("Expected exception is thrown: "
670 + e.getClass().getSimpleName() + ": " + e.getMessage());
673 // Test checkin with empty list of steps
674 stepsToCheckin.clear();
675 _scenarioService.checkin(scenarioId, userId, stepsToCheckin);
677 rollbackNestedTransaction();
678 LOG.debug(">>>>> END testCheckin()");
682 * Check if there is uses relation from the newPub to pub.
685 * the new publication
687 * the publication to be used
689 private void checkUsesRelation(final Publication newPub,
690 final Publication pub) {
691 boolean uses = false;
692 boolean usesExist = false;
693 for (Publication usesPub : newPub.getRelations(UsesRelation.class)) {
695 uses = (usesPub.equals(pub));
700 Assert.assertTrue(usesExist && uses, "The created document "
701 + newPub.value().getTitle() + "("
702 + newPub.value().getType().getName() + ")"
703 + " has no uses relation to the document "
704 + pub.value().getTitle() + "("
705 + pub.value().getType().getName() + ")");
709 * Check that files are moved correctly.
712 * checked in document DTO
714 * the created document publication
716 private void checkFiles(final DocumentDTO docDTO, final Publication newPub) {
717 // Check that original files are deleted
718 for (int j = 0; j < docDTO.getFiles().size(); j++) {
719 FileDTO fileDTO = docDTO.getFiles().get(j);
720 Assert.assertFalse(new File(fileDTO.getPath()).exists(), "File"
722 + " was not removed from downloads directory.");
723 String format = fileDTO.getPath().substring(
724 fileDTO.getPath().lastIndexOf('.') + 1);
726 // TODO: Check file by its internal content
727 Assert.assertTrue(newPub.getSourceFile().exists(), "File "
728 + newPub.getSourceFile().asFile().getAbsolutePath()
729 + " for the document " + docDTO.getTitle()
730 + " was not created.");
734 * Prepare a document with a file for check-in.
737 * step DTO with data for check-in
745 * checked out stepDTO
746 * @param stepsToCheckin
748 * @throws IOException
749 * if file creation failed
750 * @return step DTO with data prepared for check-in (stepTo or new if stepTo is null)
752 private StepDTO createDocDTOForModule(final StepDTO stepTo,
753 final String module, final String format, final long userId,
754 final StepDTO stepFrom, final List<StepDTO> stepsToCheckin)
756 StepDTO stepToCheckin = stepTo;
757 if (stepToCheckin == null) {
758 stepToCheckin = new StepDTO();
760 if (module.equals(stepFrom.getModule())) {
761 stepsToCheckin.add(stepToCheckin);
762 stepToCheckin.setNumber(stepFrom.getNumber());
763 for (DocumentDTO doc : stepFrom.getDocs()) {
764 if (doc.getFiles().get(0).getState() != 'O') {
765 DocumentDTO docToCheckin = stepToCheckin.addDoc(
766 doc.getId(), doc.getTitle());
767 for (FileDTO file : doc.getFiles()) {
768 if (file.getPath().endsWith(format)
769 || (file.getPath().endsWith("py") && (format
770 .equals("brep") || format.equals("med")))) {
771 // Create a file in the download directory
772 docToCheckin.addFile(createDownloadedFile(userId,
773 doc.getTitle() + "_result", format));
779 stepToCheckin.addDoc(0, "newdoc" + stepFrom.getNumber()).addFile(
780 createDownloadedFile(userId, "newdoc"
781 + stepFrom.getNumber(), "brep"));
783 return stepToCheckin;
787 * Create a file in the user's repository downloads directory.
795 * @return created file DTO
796 * @throws IOException
797 * if file creation failed
799 private FileDTO createDownloadedFile(final long userId, final String name,
800 final String format) throws IOException {
801 // Create a file in the download directory
802 return createDownloadedFile(userId, name + "." + format);
806 * Create a file in the user's repository downloads directory.
812 * @return created file DTO
813 * @throws IOException
814 * if file creation failed
816 private FileDTO createDownloadedFile(final long userId, final String fname)
818 // Create a file in the download directory
819 String filePath = getDownloadPath(userId) + fname;
820 FileWriter fw = new FileWriter(filePath);
821 fw.write("Simulation of " + fname + " file for checkin at "
824 return new FileDTO(filePath);
828 * Create a persistent scenario for tests.
830 * @return a persistent scenario
831 * @throws InvalidPropertyException
832 * if an invalid property is used when creating objects
833 * @throws MultiplyDefinedException
834 * when trying to create an object with already existing id
835 * @throws MissedPropertyException
836 * if a mandatory property is not defined for an object to be created
837 * @throws IOException
838 * if document creation is failed
839 * @throws SQLException
840 * if project settings loading is failed
842 private long createScenario() throws InvalidPropertyException,
843 MissedPropertyException, MultiplyDefinedException, IOException,
845 // Create a scenario for tests
846 HibernateTemplate ht = getHibernateTemplate();
848 Database.getInstance().reset();
849 _projectSettings.getAllSteps().clear(); // Clear config to be able to load it again
850 // Load workflow customization
852 _projectSettings.configure("classpath:test/som.xml");
853 } catch (FileNotFoundException e) {
854 Assert.fail("Can't find som.xml: ", e);
856 List<Step> steps = _stepsConfigService.getStepsOf(Scenario.class);
857 Assert.assertTrue(steps.size() > 0, "No steps are created.");
859 // Create a test user
860 User.Properties uprop = new User.Properties();
861 uprop.setUsername("TST_Username").setName("TST_SimanUnitTestsUser")
862 .setFirstName("TST_FirstName").setDisplayName("TST_test.user")
863 .addRole("TST_user").setMailAddress(
864 "noreply@salome-platform.org");
865 uprop.disableCheck();
866 User anAuthor = new User(uprop);
867 ht.saveOrUpdate(anAuthor);
869 // Create a test study
870 Study.Properties stprops = new Study.Properties().setReference(
871 "TST_SID_01").setTitle("TST_Study").setManager(anAuthor);
872 Study aStudy = new Study(stprops);
873 ht.saveOrUpdate(aStudy);
875 // Create a test scenario
876 Scenario.Properties sprops = new Scenario.Properties().setTitle(
877 "TST_Scenario").setManager(anAuthor).setOwnerStudy(aStudy);
878 Scenario aScenario = new Scenario(sprops);
879 aStudy.getScenariiList().add(aScenario);
880 ht.saveOrUpdate(anAuthor);
881 ht.saveOrUpdate(aStudy);
882 ht.saveOrUpdate(aScenario);
884 // Create documents for each scenario step
885 Document.Properties dprop = new Document.Properties().setAuthor(
886 anAuthor).setDate(new Date());
888 Publication usedPub = null;
889 Map<Long, Long> usedMap = new HashMap<Long, Long>();
890 for (Step step : steps) {
891 LOG.debug("Create scenario step: " + i);
893 org.splat.som.Step aScStep = new org.splat.som.Step(step, aScenario);
894 List<DocumentType> dtypes = _documentTypeService
895 .selectTypesOf(step);
896 for (DocumentType dtype : dtypes) {
897 // Create a document published in the scenario
898 // document<i>: document type[0] - first type used on the step
899 // <source-file>.brep
900 // <attached-file>.med
901 dprop.setName("document" + i++).setType(dtype);
903 * if (step.getNumber() > 3) { dprop.setFormat("med"); } else {
904 */dprop.setFormat("py");
906 dprop.setLocalPath(dprop.getName() + "." + dprop.getFormat());
907 Publication pub = createDoc(aScenario, aScStep, dprop, "med",
909 if (usedPub != null) {
910 pub.addDependency(usedPub);
911 ht.saveOrUpdate(pub.value());
913 usedMap.put(pub.getIndex(), usedPub.getIndex());
917 // Create another document with outdated publication
918 dprop.setName("document" + i++).setType(dtype).setFormat("py");
919 dprop.setLocalPath(dprop.getName() + "." + dprop.getFormat());
920 createDoc(aScenario, aScStep, dprop, "med", true);
923 if (dtypes.size() <= 0) {
924 LOG.debug("No document types are found for scenario step " + i);
928 // Check that the scenario and its documents have been created correctly.
930 Assert.assertNotNull(ht.find("from Document"),
931 "No documents in the database.");
932 Assert.assertTrue(ht.find("from Document").size() > 0,
933 "No documents in the database.");
935 Assert.assertNotNull(ht.find("from Publication where owner="
936 + aScenario.getIndex()), "No publications in the database.");
938 ht.find("from Publication where owner=" + aScenario.getIndex())
939 .size() > 0, "No publications in the database.");
941 for (Publication p : (List<Publication>) ht
942 .find("from Publication where owner=" + aScenario.getIndex())) {
943 LOG.debug("Publication found: [id=" + p.getIndex() + ", owner="
944 + p.getOwner().getIndex() + ", doc=" + p.value().getIndex()
946 Assert.assertEquals(p.getOwner().getIndex(), aScenario.getIndex(),
947 "The publication was not attached to the scenario.");
950 // Remove the scenario from the current hibernate session.
952 // Check that the scenario is created in the database.
953 Scenario aScen = ht.load(Scenario.class, aScenario.getIndex());
954 Assert.assertNotNull(aScen, "Scenario was not saved in the database.");
955 Assert.assertTrue(aScen.getDocums().size() > 0,
956 "No publications in the scenario.");
958 Assert.assertTrue(i > 0,
959 "More then one document must be in the database");
961 // Check created uses relations
963 .assertTrue(usedMap.size() > 0,
964 "Uses relations must be created.");
965 boolean foundAny = false;
966 for (Long usingId : usedMap.keySet()) {
967 for (Publication pub : aScen.getDocums()) {
968 if (pub.getIndex() == usingId) {
969 boolean found = false;
970 for (Publication used : aScen.getDocums()) {
971 found = (used.getIndex() == usedMap.get(usingId));
976 Assert.assertTrue(found,
977 "Uses relation was not created in the database.");
978 foundAny = foundAny || found;
982 Assert.assertTrue(foundAny,
983 "No Uses relation was created in the database.");
985 return aScenario.getIndex();
989 * Create a document published in the scenario. <BR>
991 * document type[0] - first type used on the step <BR>
992 * <source-file>.brep <BR>
993 * <attached-file>.med
996 * the scenario to add the document to
998 * scenario step where the document to be published
1000 * document properties
1001 * @param attachedFileExt
1002 * extension of the secon attached (exported) file
1004 * outdated document flag
1005 * @return the publication of the created document
1006 * @throws IOException
1007 * @throws MultiplyDefinedException
1008 * @throws InvalidPropertyException
1009 * @throws MissedPropertyException
1011 private Publication createDoc(final Scenario aScenario,
1012 final org.splat.som.Step aScStep, final Properties dprop,
1013 final String attachedFileExt, final boolean isOutdated)
1014 throws MissedPropertyException, InvalidPropertyException,
1015 MultiplyDefinedException, IOException {
1016 // Create a document published in the scenario
1017 // document<i>: document type[0] - first type used on the step
1018 // <source-file>.brep
1019 // <attached-file>.med
1020 createDownloadedFile(aScenario.getAuthor().getIndex(), dprop
1022 Publication pub = _stepService.createDocument(aScStep, dprop);
1023 Assert.assertNotNull(pub.getOwner(),
1024 "The publication must be attached to the scenario.");
1025 Assert.assertEquals(pub.getOwner().getIndex(), aScenario.getIndex(),
1026 "The publication was not attached to the scenario.");
1032 HibernateTemplate ht = getHibernateTemplate();
1033 ht.saveOrUpdate(pub);
1036 createDownloadedFile(aScenario.getAuthor().getIndex(), dprop
1037 .getLocalPath().substring(0,
1038 dprop.getLocalPath().lastIndexOf(".") - 1),
1040 ht.save(pub.value());
1041 ht.saveOrUpdate(_publicationService.attach(pub, attachedFileExt));
1047 * Test study creation.<BR>
1048 * <B>Description :</B> <BR>
1049 * <i>Create a study.</i><BR>
1050 * <B>Action : </B><BR>
1051 * <i>1. call the method for a not existing product.</i><BR>
1052 * <i>2. call the method for an existing username and an existing product.</i><BR>
1053 * <i>3. call the method for a not existing username expecting an exception.</i><BR>
1054 * <B>Test data : </B><BR>
1055 * <i>no input parameters</i><BR>
1057 * <B>Outcome results:</B><BR>
1060 * <li>1: The new study must be created. The new product simulation context must be created.</li>
1061 * <li>2: The new study must be created.</li>
1062 * <li>3: The new study must not be created. Exception must be thrown.</li>
1066 * @throws IOException
1067 * if application configuration loading is failed
1068 * @throws SQLException
1069 * if application configuration loading is failed
1070 * @throws BusinessException
1071 * if test data creation is failed
1073 @Test(groups = { "study", "sevice", "functional", "business" })
1074 public void testCreateStudy() throws BusinessException, IOException,
1076 LOG.debug(">>>>> BEGIN testCreateStudy()");
1077 startNestedTransaction();
1079 Database.getInstance().reset();
1080 _projectSettings.getAllSteps().clear(); // Clear config to be able to load it again
1081 _projectSettings.configure("classpath:test/som.xml");
1083 // Create a test user
1084 User.Properties uprop = new User.Properties();
1085 uprop.setUsername("TST_Username").setName("TST_SimanUnitTestsUser")
1086 .setFirstName("TST_FirstName").setDisplayName("TST_test.user")
1087 .addRole("TST_user").setMailAddress(
1088 "noreply@salome-platform.org");
1089 uprop.disableCheck();
1090 User anAuthor = new User(uprop);
1092 getHibernateTemplate().saveOrUpdate(anAuthor);
1093 KnowledgeElementType ucase = _knowledgeElementTypeService
1094 .selectType("usecase");
1095 Assert.assertNotNull(ucase,
1096 "Knowledge type 'usecase' must be created in the database.");
1097 SimulationContextType prodtype = _simulationContextService
1098 .selectType("product");
1100 .assertNotNull(prodtype,
1101 "Simulation context type 'product' must be created in the database.");
1105 uprop.setUsername("TST_Admin").setName("TST_SimanUnitTestsAdmin")
1106 .setFirstName("TST_AdminFirstName").setDisplayName(
1107 "TST_test.admin").addRole("TST_user,sysadmin")
1108 .setMailAddress("noreply@salome-platform.org");
1109 uprop.disableCheck();
1111 getHibernateTemplate().saveOrUpdate(new User(uprop));
1112 getHibernateTemplate().flush();
1114 Study.Properties sprop = new Study.Properties();
1115 sprop.setTitle("Test study creation").setManager(anAuthor);
1116 Scenario.Properties oprop = new Scenario.Properties();
1117 oprop.setTitle("Test scenario for the created study");
1119 // Addition of the entered project context
1120 SimulationContext.Properties cprop = new SimulationContext.Properties();
1121 // Input of new project context
1122 cprop.setType(_simulationContextService.selectType("product"))
1123 .setValue("Test Simulation Context: Product");
1124 Study study = _scenarioService.createStudy(sprop, oprop, cprop);
1126 Assert.assertNotNull(study);
1127 Assert.assertTrue(study.getIndex() > 0);
1129 rollbackNestedTransaction();
1130 LOG.debug(">>>>> END testCreateStudy()");
1134 * Test study creation.<BR>
1135 * <B>Description :</B> <BR>
1136 * <i>Create a study.</i><BR>
1137 * <B>Action : </B><BR>
1138 * <i>1. call the method for a not existing product.</i><BR>
1139 * <i>2. call the method for an existing username and an existing product.</i><BR>
1140 * <i>3. call the method for a not existing username expecting an exception.</i><BR>
1141 * <B>Test data : </B><BR>
1142 * <i>no input parameters</i><BR>
1144 * <B>Outcome results:</B><BR>
1147 * <li>1: The new study must be created. The new product simulation context must be created.</li>
1148 * <li>2: The new study must be created.</li>
1149 * <li>3: The new study must not be created. Exception must be thrown.</li>
1153 * @throws IOException
1154 * if application configuration loading is failed
1155 * @throws SQLException
1156 * if application configuration loading is failed
1157 * @throws BusinessException
1158 * if test data creation is failed
1160 @Test(groups = { "study", "sevice", "functional", "business" })
1161 public void testCreateStudyFromPython() throws IOException, SQLException,
1163 LOG.debug(">>>>> BEGIN testCreateStudyFromPython()");
1164 startNestedTransaction();
1166 HibernateTemplate ht = getHibernateTemplate();
1168 Database.getInstance().reset();
1169 _projectSettings.getAllSteps().clear(); // Clear config to be able to load it again
1170 _projectSettings.configure("classpath:test/som.xml");
1172 // Create a test user
1173 User goodUser = TestEntitiesGenerator.getTestUser("goodUser");
1174 _userDAO.create(goodUser);
1175 SimulationContextType prodtype = _simulationContextService
1176 .selectType("product");
1178 .assertNotNull(prodtype,
1179 "Simulation context type 'product' must be created in the database.");
1181 String productName = "New Test Product " + new Date().toString();
1185 long studyId1 = _scenarioService.createStudy("goodUser",
1186 "Test Study 1", productName, "Test description");
1187 Assert.assertTrue(studyId1 > 0);
1192 _scenarioService.createStudy("badbadUser", "Test Study 2",
1193 productName, "Test description");
1194 Assert.fail("Study must not be created for not existing user.");
1195 } catch (InvalidPropertyException ipe) {
1196 LOG.debug("Expected exception: " + ipe.getMessage());
1201 long studyId3 = _scenarioService.createStudy("goodUser",
1202 "Test Study 3", productName, "Test description");
1203 Assert.assertTrue(studyId3 > 0);
1205 // Check that the simulation context is the same
1206 Study study1 = _studyService.selectStudy(studyId1);
1207 Study study3 = _studyService.selectStudy(studyId3);
1208 Assert.assertEquals(study1.SimulationContextIterator().next(), study3
1209 .SimulationContextIterator().next());
1211 // Check the title of the created scenario
1212 String scTitle = study1.getScenarii()[0].getTitle();
1213 Assert.assertEquals(scTitle, I18nUtils
1214 .getMessageLocaleDefault("label.scenario")
1216 Assert.assertFalse(scTitle.equals("label.scenario 1"));
1218 rollbackNestedTransaction();
1219 LOG.debug(">>>>> END testCreateStudyFromPython()");
1223 * Test study content copy.<BR>
1224 * <B>Description :</B> <BR>
1225 * <i>Create a study.</i><BR>
1226 * <B>Action : </B><BR>
1227 * <i>1. call the method for a not existing source study.</i><BR>
1228 * <i>2. call the method for a not existing source scenario with not evolving step.</i><BR>
1229 * <i>3. call the method for a not existing source scenario with evolving step.</i><BR>
1230 * <i>4. call the method for an existing source scenario with evolving step.</i><BR>
1231 * <B>Test data : </B><BR>
1232 * <i>no input parameters</i><BR>
1234 * <B>Outcome results:</B><BR>
1237 * <li>1: Exception must be thrown.</li>
1238 * <li>2: The study content must be copied.</li>
1239 * <li>3: Exception must be thrown.</li>
1240 * <li>4: The study content must be copied.</li>
1244 * @throws IOException
1245 * if application configuration loading is failed
1246 * @throws SQLException
1247 * if application configuration loading is failed
1248 * @throws BusinessException
1249 * if test data creation is failed
1251 @Test(groups = { "study", "sevice", "functional", "business" })
1252 public void testCopyStudyContent() throws IOException, SQLException,
1254 LOG.debug(">>>>> BEGIN testCopyStudyContent()");
1255 startNestedTransaction();
1257 HibernateTemplate ht = getHibernateTemplate();
1259 Database.getInstance().reset();
1260 _projectSettings.getAllSteps().clear(); // Clear config to be able to load it again
1261 _projectSettings.configure("classpath:test/som.xml");
1263 User goodUser = TestEntitiesGenerator.getTestUser("GoodUser");
1264 _userDAO.create(goodUser);
1265 User otherUser = TestEntitiesGenerator.getTestUser("otherUser");
1266 _userDAO.create(otherUser);
1268 // Create private study
1269 Study aStudy = TestEntitiesGenerator.getTestStudy(goodUser);
1270 aStudy.setTitle("0.This is private study");
1271 Long studyId = _studyDAO.create(aStudy);
1273 // Add a scenario to the study
1274 Scenario scen = TestEntitiesGenerator.getTestScenario(aStudy);
1275 _scenarioDAO.create(scen);
1277 // Add a second scenario to the study
1278 scen = TestEntitiesGenerator.getTestScenario(aStudy);
1279 Long aScenId = _scenarioDAO.create(scen);
1282 // Add a validation cycle with otherUser as a reviewer
1283 ValidationCycle.Properties vprop = new ValidationCycle.Properties();
1284 DocumentType dtype = _documentTypeService.selectType("minutes");
1285 vprop.setDocumentType(dtype);
1286 vprop.setActor(ValidationStep.REVIEW, otherUser);
1287 ValidationCycle cycle = new ValidationCycle(aStudy, vprop);
1288 _validationCycleDAO.create(cycle);
1289 ValidationCycleRelation link = cycle.getContext();
1290 aStudy.addRelation(link);
1293 // Add documents to the first study activity
1294 // Add a converts relations
1295 Map<Integer, org.splat.som.Step> stSteps = _projectElementService
1296 .getStepsMap(aStudy);
1297 org.splat.som.Step aStep = stSteps.get(1);
1298 Publication pub1 = addDoc(aStudy, aStep, "document1", dtype);
1299 Publication pub2 = addDoc(aStudy, aStep, "document2", dtype);
1300 Publication pub3 = addDoc(aStudy, aStep, "document3", dtype);
1303 LOG.debug("pub1 version doc: " + pub1.value().getTitle() + " ["
1304 + pub1.value().getReference() + "]" + " ["
1305 + pub1.value().getRid() + "]");
1306 LOG.debug("pub2 version doc: " + pub2.value().getTitle() + " ["
1307 + pub2.value().getReference() + "]" + " ["
1308 + pub2.value().getRid() + "]");
1309 LOG.debug("pub3 version doc: " + pub3.value().getTitle() + " ["
1310 + pub3.value().getReference() + "]" + " ["
1311 + pub3.value().getRid() + "]");
1316 LOG.debug("Before versioning:");
1317 for (Publication doc : _projectElementService.getFirstStep(aStudy)
1318 .getAllDocuments()) {
1319 LOG.debug("Study doc: " + doc.value().getTitle() + " ["
1320 + doc.value().getReference() + "]" + " ["
1321 + doc.value().getRid() + "]");
1323 // Add a version relations
1324 Publication pub31 = version(pub3);
1327 // LOG.debug("pub31 version doc: " + pub31.value().getTitle() + " ["
1328 // + pub31.value().getReference() + "]" + " ["
1329 // + pub31.value().getRid() + "]");
1330 // ht.saveOrUpdate(aStudy);
1332 // LOG.debug("After versioning:");
1333 // for (Publication doc : aStudy.getDocums()) {
1334 // LOG.debug("Study doc: " + doc.value().getTitle() + " ["
1335 // + doc.value().getReference() + "]" + " ["
1336 // + doc.value().getRid() + "]");
1339 // Add documents to the first scenario activity
1340 Map<Integer, org.splat.som.Step> scSteps = _projectElementService
1342 aStep = scSteps.get(2);
1343 Publication spub1 = addDoc(scen, aStep, "sdocument1", dtype);
1344 Publication spub2 = addDoc(scen, aStep, "sdocument2", dtype);
1345 Publication spub3 = addDoc(scen, aStep, "sdocument3", dtype);
1346 LOG.debug("spub1 version doc: " + spub1.value().getTitle() + " ["
1347 + spub1.value().getReference() + "]" + " ["
1348 + spub1.value().getRid() + "]");
1349 LOG.debug("spub2 version doc: " + spub2.value().getTitle() + " ["
1350 + spub2.value().getReference() + "]" + " ["
1351 + spub2.value().getRid() + "]");
1352 LOG.debug("spub3 version doc: " + spub3.value().getTitle() + " ["
1353 + spub3.value().getReference() + "]" + " ["
1354 + spub3.value().getRid() + "]");
1357 // Create a scenario document version
1358 Publication spub31 = version(spub3);
1359 // LOG.debug("spub31 version doc: " + spub31.value().getTitle() + " ["
1360 // + spub31.value().getReference() + "]" + " ["
1361 // + spub31.value().getRid() + "]");
1364 // Add uses relations
1365 pub2.addDependency(pub1);
1366 ht.saveOrUpdate(pub2.value());
1367 pub3.addDependency(pub2);
1368 ht.saveOrUpdate(pub3.value());
1370 spub2.addDependency(pub1);
1371 spub2.addDependency(spub1);
1372 spub2.addDependency(pub2);
1373 spub2.addDependency(pub3);
1374 ht.saveOrUpdate(spub2.value());
1375 spub3.addDependency(spub2);
1376 ht.saveOrUpdate(spub3.value());
1377 spub31.addDependency(pub31);
1378 ht.saveOrUpdate(spub31.value());
1381 // Create target study1
1382 Study aStudy1 = TestEntitiesGenerator.getTestStudy(goodUser);
1383 aStudy1.setTitle("1.This is a target study1");
1384 aStudy1.setReference("tst1");
1385 Long studyId1 = _studyDAO.create(aStudy1);
1387 // Add a scenario to the study
1388 Scenario scen1 = TestEntitiesGenerator.getTestScenario(aStudy1);
1389 _scenarioDAO.create(scen1);
1392 // Create target study2
1393 Study aStudy2 = TestEntitiesGenerator.getTestStudy(goodUser);
1394 aStudy2.setTitle("2.This is a target study2");
1395 aStudy2.setReference("tst2");
1396 Long studyId2 = _studyDAO.create(aStudy2);
1398 // Add a scenario to the study
1399 Scenario scen2 = TestEntitiesGenerator.getTestScenario(aStudy2);
1400 _scenarioDAO.create(scen2);
1404 // //////////////////// TEST CALL /////////////////////////////////////
1405 // 1. call the method for a not existing source study.
1407 _scenarioService.copyStudyContent(-1, -1, -1, -1);
1408 Assert.fail("Exception must be thrown for not existing study id.");
1409 } catch (InvalidParameterException e) {
1410 LOG.debug("Expected exception: " + e.getClass().getSimpleName()
1411 + ": " + e.getMessage());
1417 // 2. call the method for a not existing source scenario with not evolving step.
1418 _scenarioService.copyStudyContent(studyId, -1, 1, studyId1);
1423 aStudy = _studyService.selectStudy(studyId);
1424 aStudy1 = _studyService.selectStudy(studyId1);
1425 for (Publication pub : aStudy.getDocums()) {
1426 // Find the same document in the created copy of the study
1427 Publication found = null;
1428 for (Publication newPub : aStudy1.getDocums()) {
1429 if (pub.value().getTitle().equals(newPub.value().getTitle())
1430 && pub.value().getType().equals(
1431 newPub.value().getType())) {
1436 Assert.assertNotNull(found, "The document "
1437 + pub.value().getTitle() + "is not copied");
1438 // Check that all files are copied (source and attached)
1441 // 3. call the method for a not existing source scenario with evolving step.
1443 _scenarioService.copyStudyContent(studyId, -1, 2, studyId2);
1445 .fail("Exception must be thrown for not existing scenario id and evolving step.");
1446 } catch (InvalidParameterException e) {
1447 LOG.debug("Expected exception: " + e.getClass().getSimpleName()
1448 + ": " + e.getMessage());
1454 // 4. call the method for an existing source scenario with evolving step.
1455 _scenarioService.copyStudyContent(studyId, aScenId, 9, studyId2);
1458 rollbackNestedTransaction();
1459 LOG.debug(">>>>> END testCopyStudyContent()");
1463 * Test assigning a simulation context to a study.<BR>
1464 * <B>Description :</B> <BR>
1465 * <i>Create a study and assign a simulation context to it.</i><BR>
1466 * <B>Action : </B><BR>
1467 * <i>1. call the method for not existing study id.</i><BR>
1468 * <i>2. call the method for not existing context type and context value.</i><BR>
1469 * <i>3. call the method for existing context type and context value.</i><BR>
1470 * <i>4. call the method for existing context type and not existing context value.</i><BR>
1471 * <i>5. call the method for empty context type.</i><BR>
1472 * <i>6. call the method for empty context value.</i><BR>
1473 * <B>Test data : </B><BR>
1474 * <i>no input parameters</i><BR>
1476 * <B>Outcome results:</B><BR>
1479 * <li>1: Exception must be thrown.</li>
1480 * <li>2: The new context type and value must be created. The new context must be assigned to the study first step.</li>
1481 * <li>3: The existing context must be assigned to the study first step.</li>
1482 * <li>4: The new context value must be created. The new context must be assigned to the study first step.</li>
1483 * <li>5: Exception must be thrown.</li>
1484 * <li>6: Exception must be thrown.</li>
1488 * @throws IOException
1489 * if application configuration loading is failed
1490 * @throws SQLException
1491 * if application configuration loading is failed
1492 * @throws BusinessException
1493 * if test data creation is failed
1495 @Test(groups = { "study", "sevice", "functional", "business" })
1496 public void testAssignStudyContextFromPython() throws IOException,
1497 SQLException, BusinessException {
1498 LOG.debug(">>>>> BEGIN testAssignStudyContextFromPython()");
1499 startNestedTransaction();
1501 HibernateTemplate ht = getHibernateTemplate();
1503 Database.getInstance().reset();
1504 _projectSettings.getAllSteps().clear(); // Clear config to be able to load it again
1505 _projectSettings.configure("classpath:test/som.xml");
1507 // Create a test user
1508 User goodUser = TestEntitiesGenerator.getTestUser("goodUser");
1509 _userDAO.create(goodUser);
1510 SimulationContextType prodtype = _simulationContextService
1511 .selectType("product");
1513 .assertNotNull(prodtype,
1514 "Simulation context type 'product' must be created in the database.");
1516 String productName = "New Test Product " + new Date().toString();
1520 long studyId1 = _scenarioService.createStudy("goodUser",
1521 "Test Study 1", productName, "Test description");
1522 Assert.assertTrue(studyId1 > 0);
1527 // //////// START OF TESTS
1528 // 1. call the method for not existing study id.</i><BR>
1530 _scenarioService.assignStudyContext(-1L, "new context type",
1531 "new context value");
1532 Assert.fail("Not existing study must not be found.");
1533 } catch (InvalidPropertyException ipe) {
1534 LOG.debug("Expected exception: " + ipe.getMessage());
1537 // 2. call the method for not existing context type and context value.</i><BR>
1538 _scenarioService.assignStudyContext(studyId1, "new context type",
1539 "new context value");
1544 // Check the assigned simulation context
1545 checkCtx(studyId1, "new context type", "new context value");
1547 // 3. call the method for existing context type and context value.</i><BR>
1548 _scenarioService.assignStudyContext(studyId1, "new context type",
1549 "new context value");
1554 // Check the assigned simulation context
1555 checkCtx(studyId1, "new context type", "new context value");
1557 // 4. call the method for existing context type and not existing context value.</i><BR>
1558 _scenarioService.assignStudyContext(studyId1, "new context type",
1559 "new context value1");
1564 // Check the assigned simulation context
1565 checkCtx(studyId1, "new context type", "new context value1");
1567 // 5. call the method for empty context type.</i><BR>
1569 _scenarioService.assignStudyContext(studyId1, "",
1570 "new context value");
1571 Assert.fail("Empty context type name must be forbidden.");
1572 } catch (InvalidPropertyException ipe) {
1573 LOG.debug("Expected exception: " + ipe.getMessage());
1575 // 6. call the method for empty context value.</i><BR>
1577 _scenarioService.assignStudyContext(studyId1, "new context type",
1579 Assert.fail("Empty context value must be forbidden.");
1580 } catch (InvalidPropertyException ipe) {
1581 LOG.debug("Expected exception: " + ipe.getMessage());
1584 rollbackNestedTransaction();
1585 LOG.debug(">>>>> END testAssignStudyContextFromPython()");
1589 * Test getting a study scenarios DTO list.<BR>
1590 * <B>Description :</B> <BR>
1591 * <i>Create a study and get its scenarios DTO list.</i><BR>
1592 * <B>Action : </B><BR>
1593 * <i>1. call the method for not existing study id.</i><BR>
1594 * <i>2. call the method for a study with one scenario.</i><BR>
1595 * <i>3. call the method for a study with several scenarios.</i><BR>
1596 * <B>Test data : </B><BR>
1597 * <i>no input parameters</i><BR>
1599 * <B>Outcome results:</B><BR>
1602 * <li>1: The returned list of DTO must be empty.</li>
1603 * <li>2: The returned list of DTO must contain one scenario DTO.</li>
1604 * <li>3: The returned list of DTO must contain several scenario DTOs.</li>
1608 * @throws IOException
1609 * if application configuration loading is failed
1610 * @throws SQLException
1611 * if application configuration loading is failed
1612 * @throws BusinessException
1613 * if test data creation is failed
1615 @Test(groups = { "study", "sevice", "functional", "business" })
1616 public void testGetStudyScenarios() throws IOException, SQLException,
1618 LOG.debug(">>>>> BEGIN testGetStudyScenarios()");
1619 startNestedTransaction();
1621 HibernateTemplate ht = getHibernateTemplate();
1623 Database.getInstance().reset();
1624 _projectSettings.getAllSteps().clear(); // Clear config to be able to load it again
1625 _projectSettings.configure("classpath:test/som.xml");
1627 // Create a test user
1628 User goodUser = TestEntitiesGenerator.getTestUser("goodUser");
1629 _userDAO.create(goodUser);
1630 Study study = TestEntitiesGenerator.getTestStudy(goodUser);
1631 long studyId1 = _studyDAO.create(study);
1633 Scenario scen = TestEntitiesGenerator.getTestScenario(study,
1635 long id11 = _scenarioDAO.create(scen);
1637 study = TestEntitiesGenerator.getTestStudy(goodUser);
1638 long studyId2 = _studyDAO.create(study);
1640 scen = TestEntitiesGenerator.getTestScenario(study, "test scen21");
1641 long id21 = _scenarioDAO.create(scen);
1643 scen = TestEntitiesGenerator.getTestScenario(study, "test scen22");
1644 long id22 = _scenarioDAO.create(scen);
1646 scen = TestEntitiesGenerator.getTestScenario(study, "test scen23");
1647 long id23 = _scenarioDAO.create(scen);
1651 // //////// START OF TESTS
1652 // 1. call the method for not existing study id.
1653 List<ScenarioDTO> scens = _scenarioService.getStudyScenarios(-1L);
1655 Assert.assertNotNull(scens);
1656 Assert.assertTrue(scens.isEmpty());
1658 // 2. call the method for a study with one scenario.
1659 scens = _scenarioService.getStudyScenarios(studyId1);
1663 Assert.assertNotNull(scens);
1664 Assert.assertEquals(scens.size(), 1);
1665 Assert.assertEquals(scens.get(0).getIndex().longValue(), id11);
1666 Assert.assertEquals(scens.get(0).getTitle(), "test scen11");
1668 // 3. call the method for a study with several scenarios.
1669 scens = _scenarioService.getStudyScenarios(studyId2);
1670 Assert.assertEquals(scens.size(), 3);
1671 Assert.assertEquals(scens.get(0).getIndex().longValue(), id21);
1672 Assert.assertEquals(scens.get(0).getTitle(), "test scen21");
1673 Assert.assertEquals(scens.get(1).getIndex().longValue(), id22);
1674 Assert.assertEquals(scens.get(1).getTitle(), "test scen22");
1675 Assert.assertEquals(scens.get(2).getIndex().longValue(), id23);
1676 Assert.assertEquals(scens.get(2).getTitle(), "test scen23");
1681 rollbackNestedTransaction();
1682 LOG.debug(">>>>> END testGetStudyScenarios()");
1686 * Check if the context is assigned to the study.
1691 * the context type name
1695 private void checkCtx(final long studyId1, final String ctxType,
1696 final String ctxValue) {
1697 // Check the assigned simulation context
1698 Study study1 = _studyService.selectStudy(studyId1);
1699 Iterator<SimulationContext> it = study1.SimulationContextIterator();
1700 SimulationContext ctx;
1701 boolean isFound = false;
1702 while ((!isFound) && it.hasNext()) {
1704 isFound = ctx.getType().getName().equals(ctxType)
1705 && ctx.getValue().equals(ctxValue);
1707 Assert.assertTrue(isFound, "Context must be assigned to the study.");