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.List;
23 import org.splat.dal.bo.kernel.Relation;
24 import org.splat.dal.bo.kernel.User;
25 import org.splat.dal.bo.som.Document;
26 import org.splat.dal.bo.som.DocumentType;
27 import org.splat.dal.bo.som.KnowledgeElementType;
28 import org.splat.dal.bo.som.Publication;
29 import org.splat.dal.bo.som.Scenario;
30 import org.splat.dal.bo.som.SimulationContext;
31 import org.splat.dal.bo.som.SimulationContextType;
32 import org.splat.dal.bo.som.Study;
33 import org.splat.dal.bo.som.UsedByRelation;
34 import org.splat.dal.bo.som.UsesRelation;
35 import org.splat.dal.bo.som.Document.Properties;
36 import org.splat.dal.dao.som.Database;
37 import org.splat.dal.dao.som.ScenarioDAO;
38 import org.splat.kernel.InvalidPropertyException;
39 import org.splat.kernel.MismatchException;
40 import org.splat.kernel.MissedPropertyException;
41 import org.splat.kernel.MultiplyDefinedException;
42 import org.splat.kernel.NotApplicableException;
43 import org.splat.log.AppLogger;
44 import org.splat.service.DocumentTypeService;
45 import org.splat.service.KnowledgeElementTypeService;
46 import org.splat.service.PublicationService;
47 import org.splat.service.ScenarioService;
48 import org.splat.service.SimulationContextService;
49 import org.splat.service.StepService;
50 import org.splat.service.dto.DocumentDTO;
51 import org.splat.service.dto.FileDTO;
52 import org.splat.service.dto.StepDTO;
53 import org.splat.service.technical.ProjectSettingsService;
54 import org.splat.service.technical.RepositoryService;
55 import org.splat.service.technical.ProjectSettingsService.Step;
56 import org.springframework.beans.factory.annotation.Autowired;
57 import org.springframework.beans.factory.annotation.Qualifier;
58 import org.springframework.orm.hibernate3.HibernateTemplate;
59 import org.testng.Assert;
60 import org.testng.annotations.Test;
61 import org.testng.reporters.Files;
63 import test.splat.common.BaseTest;
66 * Test class for ScenarioService.
68 * @author <a href="mailto:roman.kozlov@opencascade.com">Roman Kozlov (RKV)</a>
71 public class TestScenarioService extends BaseTest {
74 * Logger for the class.
76 private static final AppLogger LOG = AppLogger
77 .getLogger(TestScenarioService.class);
80 * The tested ScenarioService. Later injected by Spring.
83 @Qualifier("scenarioService")
84 private transient ScenarioService _scenarioService;
87 * The RepositoryService. Later injected by Spring.
90 @Qualifier("repositoryService")
91 private transient RepositoryService _repositoryService;
94 * The Scenario DAO. Later injected by Spring.
97 @Qualifier("scenarioDAO")
98 private transient ScenarioDAO _scenarioDAO;
101 * The PublicationService. Later injected by Spring.
104 @Qualifier("publicationService")
105 private transient PublicationService _publicationService;
108 * The StepService. Later injected by Spring.
111 @Qualifier("stepService")
112 private transient StepService _stepService;
115 * The SimulationContextService. Later injected by Spring.
118 @Qualifier("simulationContextService")
119 private transient SimulationContextService _simulationContextService;
122 * The ProjectSettingsService. Later injected by Spring.
125 @Qualifier("projectSettings")
126 private transient ProjectSettingsService _projectSettings;
129 * The DocumentTypeService. Later injected by Spring.
132 @Qualifier("documentTypeService")
133 private transient DocumentTypeService _documentTypeService;
136 * The KnowledgeElementTypeService. Later injected by Spring.
139 @Qualifier("knowledgeElementTypeService")
140 private transient KnowledgeElementTypeService _knowledgeElementTypeService;
143 * Test of getting a scenario content for building siman-salome.conf.<BR>
144 * <B>Description :</B> <BR>
145 * <i>Create a scenario and try to get an info for it.</i><BR>
146 * <B>Action : </B><BR>
147 * <i>1. call the method for an existing scenario id.</i><BR>
148 * <i>2. call the method for a not existing scenario id.</i><BR>
149 * <B>Test data : </B><BR>
150 * <i>no input parameters</i><BR>
151 * <i>no input parameters</i><BR>
153 * <B>Outcome results:</B><BR>
156 * <li>result DTO must contain list of all documents and files<BR>
158 * <li>Exception is thrown<BR>
163 * @throws InvalidPropertyException
164 * if an invalid property is used when creating objects
165 * @throws MultiplyDefinedException
166 * when trying to create an object with already existing id
167 * @throws MissedPropertyException
168 * if a mandatory property is not defined for an object to be created
169 * @throws IOException
170 * if scenario creation is failed
171 * @throws SQLException
172 * if scenario creation is failed
174 @Test(groups = { "checkout", "sevice", "functional", "business" })
175 public void testGetScenarioInfo() throws InvalidPropertyException,
176 MissedPropertyException, MultiplyDefinedException, IOException,
178 LOG.debug(">>>>> BEGIN testGetScenarioInfo()");
179 startNestedTransaction();
181 long scenarioId = createScenario();
182 // Call DAO's create method for a good transient knowledge element.
183 List<StepDTO> steps = _scenarioService.getScenarioInfo(scenarioId);
184 Assert.assertNotNull(steps, "List of steps must not be null.");
185 Assert.assertTrue(steps.size() > 0, "No steps are read.");
187 List<Step> projSteps = _projectSettings.getStepsOf(Scenario.class);
188 Assert.assertEquals(steps.size(), projSteps.size(),
189 "Not all steps are listed.");
191 for (StepDTO step : steps) {
192 LOG.debug("check the step " + step.getNumber() + ":\n" + step);
193 Assert.assertNotNull(step, "Step DTO must not be null.");
194 Assert.assertNotNull(step.getKey(), "Step name must not be null.");
195 Assert.assertFalse(step.getKey().isEmpty(),
196 "Step name must not empty.");
197 Assert.assertTrue(step.getNumber() > 0,
198 "Step number must be positive integer.");
199 Assert.assertNotNull(step.getDocs(),
200 "Step documents list must not be null.");
202 Step aProjStep = null;
203 for (Step projStep : projSteps) {
204 if (projStep.getNumber() == step.getNumber()) {
205 aProjStep = projStep;
210 List<DocumentType> dtypes = _documentTypeService
211 .selectTypesOf(aProjStep);
212 for (DocumentType dtype : dtypes) {
213 Assert.assertTrue(step.getDocs().size() > 0,
214 "Step documents list must not be empty.");
215 String docName = "document" + docIndex;
216 for (DocumentDTO doc : step.getDocs()) {
217 if (docName.equals(doc.getTitle())) {
218 Assert.assertTrue(doc.getId() > 0,
219 "Document id must be positive integer.");
220 Assert.assertEquals(doc.getTitle(), docName);
221 Assert.assertNotNull(doc.getFiles(),
222 "Document files list must not be null.");
224 .assertTrue(doc.getFiles().size() > 1,
225 "Document must have more then 1 attached file.");
227 for (FileDTO file : doc.getFiles()) {
228 Assert.assertNotNull(file.getPath(),
229 "File path must not be null.");
230 Assert.assertFalse(file.getPath().isEmpty(),
231 "File path must not be empty.");
233 * <mappings> <document type="geometry"> <import format="brep"/> <!-- Result Shape --> </document> <document
234 * type="model"> <import format="med"/> <!-- Result mesh without input parameters --> </document> <document
235 * type="loads"> <import format="c3m"/> <!-- Input data created interactively --> </document> <document
236 * type="results"> <import format="med"/> <!-- Calculation results source file --> </document> </mappings>
238 // Check state and processing instruction
239 String fileFormat = file.getPath().substring(
240 file.getPath().lastIndexOf('.') + 1);
242 * if (_projectSettings.doImport(dtype.getName(), fileFormat)) { Assert.assertTrue(file.isResult(), "The file
243 * must be a result file."); } else { Assert.assertFalse(file.isResult(), "The file must be a source file."); }
244 */if ((docIndex % 2) == 0) { // New
245 Assert.assertEquals(file.getState(), 'Y',
246 "File state must be actual ('Y').");
247 if (_projectSettings.doImport(dtype.getName(),
249 Assert.assertEquals(file.getProcessing(),
251 "File must be imported.");
253 Assert.assertEquals(file.getProcessing(),
255 "File must be downloaded.");
258 Assert.assertEquals(file.getState(), 'O',
259 "File state must be outdated ('O').");
261 .assertEquals(file.getProcessing(),
263 "Outdated document should not be imported but downloaded.");
272 // Call DAO's get method for a not existing id.
274 steps = _scenarioService.getScenarioInfo(-1L);
275 // getHibernateTemplate().flush();
277 .fail("Getting an object with not existing id must be failed.");
278 } catch (Exception e) {
279 LOG.debug("Expected exception is thrown: "
280 + e.getClass().getSimpleName() + ": " + e.getMessage());
282 rollbackNestedTransaction();
283 LOG.debug(">>>>> END testGetScenarioInfo()");
287 * Test check-in scenario operation to be performed after SALOME session.<BR>
288 * <B>Description :</B> <BR>
289 * <i>Create a scenario and try to check-in it with some simulated SALOME results data.<BR>
290 * After check-in verify following points:
292 * <li>scenario is no more marked as checked out</li>
293 * <li>new document versions are created for checked in documents</li>
294 * <li>presentation of the previous version is removed</li>
295 * <li>uses relations are copied correctly</li>
296 * <li>files are moved correctly</li>
297 * <li>formats of files are new if they are according to the document's type on the study step</li>
298 * <li>new documents are created for new data</li>
299 * <li>new documents have correctly generated names</li>
300 * <li>uses relations are created correctly</li>
301 * <li>files are moved correctly</li>
304 * <B>Action : </B><BR>
305 * <i>1. call the method for an existing scenario id.</i><BR>
306 * <i>2. call the method for a not existing scenario id.</i><BR>
307 * <B>Test data : </B><BR>
308 * <i>no input parameters</i><BR>
309 * <i>no input parameters</i><BR>
311 * <B>Outcome results:</B><BR>
314 * <li>New version of existing documents must be created and new documents must be imported for documents with zero id. Correct
315 * relations must be created.<BR>
317 * <li>Exception is thrown<BR>
322 * @throws InvalidPropertyException
323 * if an invalid property is used when creating objects
324 * @throws MultiplyDefinedException
325 * when trying to create an object with already existing id
326 * @throws MissedPropertyException
327 * if a mandatory property is not defined for an object to be created
328 * @throws IOException
329 * if scenario creation is failed
330 * @throws SQLException
331 * if scenario creation is failed
332 * @throws NotApplicableException
334 * @throws MismatchException
337 @Test(groups = { "checkin", "sevice", "functional", "business" })
338 public void testCheckin() throws InvalidPropertyException,
339 MissedPropertyException, MultiplyDefinedException, IOException,
340 SQLException, MismatchException, NotApplicableException {
341 LOG.debug(">>>>> BEGIN testCheckin()");
342 startNestedTransaction();
344 _projectSettings.getAllSteps().clear(); // Clear config to be able to load it again
345 _projectSettings.configure(ClassLoader
346 .getSystemResource("test/som.xml").getPath());
347 getHibernateTemplate().flush();
348 long scenarioId = createScenario();
349 Scenario aScen = _scenarioDAO.get(scenarioId);
350 User user = aScen.getAuthor();
351 long userId = user.getIndex();
353 // ////////////////////////////////////////////////////////
354 // Call checkin method for good prepared transient data.
357 List<StepDTO> steps = _scenarioService.getScenarioInfo(scenarioId);
358 _scenarioService.checkout(aScen, user);
360 // Prepare test data for checkin
361 // Checkin only two first steps (geom and mesh)
362 List<StepDTO> stepsToCheckin = new ArrayList<StepDTO>();
363 for (StepDTO step : steps) {
364 // Prepare GEOM: checkin actual brep
365 StepDTO stepToCheckin = createDocDTOForModule(null, "GEOM", "brep",
366 userId, step, stepsToCheckin);
367 createDocDTOForModule(stepToCheckin, "SMESH", "med", userId, step,
371 _scenarioService.checkin(scenarioId, userId, stepsToCheckin);
373 _scenarioDAO.flush();
374 // Check that scenario is no more marked as checked out
375 aScen = _scenarioDAO.get(scenarioId);
376 Assert.assertFalse(aScen.isCheckedout(),
377 "Scenario is still marked as checked out after checkin.");
378 // Check that new document versions are created for checked in documents
379 boolean caseFound = false;
380 for (StepDTO step : stepsToCheckin) {
381 for (DocumentDTO docDTO : step.getDocs()) {
382 if ((docDTO.getId() != 0) && (docDTO.getId() != null)) {
383 boolean found = false;
384 Document prevDoc = null;
385 Publication newPub = null;
386 for (Publication pub : aScen.getDocums()) {
387 prevDoc = pub.value().getPreviousVersion();
388 if (prevDoc != null) {
389 found = (prevDoc.getIndex() == docDTO.getId());
390 if (found) { // Found next published version of the checked in document
396 Assert.assertTrue(found,
397 "New version of the existing checked in document \""
398 + docDTO.getTitle() + "\" (id="
400 + ") is not found in the scenario.");
401 // Check that presentation of the previous version is removed
402 Assert.assertFalse(aScen.publishes(prevDoc));
403 checkFiles(docDTO, newPub);
405 // Formats of files are new if they are according to the document's type on the study step
406 if ("py".equals(prevDoc.getFormat())
407 && "geometry".equals(prevDoc.getType().getName())) {
408 Assert.assertEquals(newPub.value().getFormat(), "brep");
409 Assert.assertEquals(newPub.getSourceFile().getFormat(),
411 Assert.assertEquals(newPub.getSourceFile()
412 .getRelativePath().substring(
413 newPub.getSourceFile()
414 .getRelativePath().lastIndexOf(
418 // Check that uses relations are copied correctly
420 // 1. Get all uses relations of the previous document version
421 for (Relation rel : prevDoc
422 .getRelations(UsesRelation.class)) {
423 Document used = ((UsesRelation) rel).getTo();
424 // 2.1. Get the latest version of the document published in this scenario
425 Publication toBeUsed = aScen.getPublication(used);
426 if (toBeUsed == null) {
427 // Find the latest published version
428 for (Publication lastPub : aScen.getDocums()) {
429 if ((lastPub.value().getPreviousVersion() != null)
431 .getPreviousVersion()
432 .getIndex() == used.getIndex())) {
438 if ((toBeUsed != null) && (!toBeUsed.isOutdated())) {
439 // 2.2. For each used document check that its latest not outdated version
440 // is used by the new checked in document version.
441 checkUsesRelation(newPub, toBeUsed);
444 // 1. Get all usedBy relations of the previous document version
445 for (Relation rel : prevDoc
446 .getRelations(UsedByRelation.class)) {
447 Document using = ((UsedByRelation) rel).getTo();
448 // Check that not checked in dependent documents became outdated
449 Publication usingPub = aScen.getPublication(using);
450 if (usingPub != null) { // if the document using the old version is still published
451 Assert.assertTrue(usingPub.isOutdated(),
452 "Not checked in dependent document "
453 + using.getTitle() + " ("
454 + using.getType().getName()
455 + ") must become outdated.");
461 // Check that new documents are created for new data
462 boolean found = false;
463 Publication newPub = null;
464 for (Publication pub : aScen.getDocums()) {
465 if (pub.value().getPreviousVersion() == null) {
466 found = (pub.value().getTitle().startsWith(pub
467 .value().getType().getName()));
468 if (found) { // Found next published version of the checked in document
469 String fcontent = Files.readFile(pub
470 .getSourceFile().asFile());
471 found = fcontent.contains(docDTO.getTitle());
474 .debug("Found new document with generated title: "
475 + pub.value().getTitle());
482 Assert.assertTrue(found,
483 "New document is not created for checked in document \""
484 + docDTO.getTitle() + "\".");
486 // Check that uses relations are created correctly
487 Assert.assertTrue(newPub.value().getTitle().startsWith(
488 newPub.value().getType().getName() + "_"),
489 "Document title newPub.value().getTitle() must start with "
490 + newPub.value().getType().getName() + "_");
492 // 1. Find the document type used by this document type
493 Set<DocumentType> usedTypes = newPub.value().getType()
495 // 2. Find documents of used types in the current study step and previous study steps
496 for (Publication pub : aScen.getDocums()) {
497 if ((pub.getStep().getNumber() <= step.getNumber())
498 && (!pub.isOutdated())
499 && usedTypes.contains(pub.value().getType())) {
500 // 3. Check that there is uses relation to the found document
501 // if it is not outdated.
502 checkUsesRelation(newPub, pub);
506 // Check that files are moved correctly
507 checkFiles(docDTO, newPub);
511 Assert.assertTrue(caseFound,
512 "Not checked in dependent documents must become outdated.");
514 // ///////////////////////////////////////////////////////////
515 // Call checkin method for a not existing id.
517 _scenarioService.checkin(-1, userId, stepsToCheckin);
519 .fail("Check in for scenario with not existing id must be failed.");
520 } catch (Exception e) {
521 LOG.debug("Expected exception is thrown: "
522 + e.getClass().getSimpleName() + ": " + e.getMessage());
525 // Test checkin with empty list of steps
526 stepsToCheckin.clear();
527 _scenarioService.checkin(scenarioId, userId, stepsToCheckin);
529 rollbackNestedTransaction();
530 LOG.debug(">>>>> END testCheckin()");
534 * Check if there is uses relation from the newPub to pub.
537 * the new publication
539 * the publication to be used
541 private void checkUsesRelation(final Publication newPub,
542 final Publication pub) {
543 boolean uses = false;
544 boolean usesExist = false;
545 for (Publication usesPub : newPub.getRelations(UsesRelation.class)) {
547 uses = (usesPub.equals(pub));
552 Assert.assertTrue(usesExist && uses, "The created document "
553 + newPub.value().getTitle() + "("
554 + newPub.value().getType().getName() + ")"
555 + " has no uses relation to the document "
556 + pub.value().getTitle() + "("
557 + pub.value().getType().getName() + ")");
561 * Check that files are moved correctly.
564 * checked in document DTO
566 * the created document publication
568 private void checkFiles(final DocumentDTO docDTO, final Publication newPub) {
569 // Check that original files are deleted
570 for (int j = 0; j < docDTO.getFiles().size(); j++) {
571 FileDTO fileDTO = docDTO.getFiles().get(j);
572 Assert.assertFalse(new File(fileDTO.getPath()).exists(), "File"
574 + " was not removed from downloads directory.");
575 String format = fileDTO.getPath().substring(
576 fileDTO.getPath().lastIndexOf('.') + 1);
578 // TODO: Check file by its internal content
579 Assert.assertTrue(newPub.getSourceFile().exists(), "File "
580 + newPub.getSourceFile().asFile().getAbsolutePath()
581 + " for the document " + docDTO.getTitle()
582 + " was not created.");
586 * Prepare a document with a file for check-in.
589 * step DTO with data for check-in
597 * checked out stepDTO
598 * @param stepsToCheckin
600 * @throws IOException
601 * if file creation failed
602 * @return step DTO with data prepared for check-in (stepTo or new if stepTo is null)
604 private StepDTO createDocDTOForModule(final StepDTO stepTo,
605 final String module, final String format, final long userId,
606 final StepDTO stepFrom, final List<StepDTO> stepsToCheckin)
608 StepDTO stepToCheckin = stepTo;
609 if (stepToCheckin == null) {
610 stepToCheckin = new StepDTO();
612 if (module.equals(stepFrom.getModule())) {
613 stepsToCheckin.add(stepToCheckin);
614 stepToCheckin.setNumber(stepFrom.getNumber());
615 for (DocumentDTO doc : stepFrom.getDocs()) {
616 if (doc.getFiles().get(0).getState() != 'O') {
617 DocumentDTO docToCheckin = stepToCheckin.addDoc(
618 doc.getId(), doc.getTitle());
619 for (FileDTO file : doc.getFiles()) {
620 if (file.getPath().endsWith(format)
621 || (file.getPath().endsWith("py") && format
623 // Create a file in the download directory
624 docToCheckin.addFile(createDownloadedFile(userId,
625 doc.getTitle() + "_result", format));
631 stepToCheckin.addDoc(0, "newdoc" + stepFrom.getNumber()).addFile(
632 createDownloadedFile(userId, "newdoc"
633 + stepFrom.getNumber(), "brep"));
635 return stepToCheckin;
639 * Create a file in the user's repository downloads directory.
647 * @return created file DTO
648 * @throws IOException
649 * if file creation failed
651 private FileDTO createDownloadedFile(final long userId, final String name,
652 final String format) throws IOException {
653 // Create a file in the download directory
654 return createDownloadedFile(userId, name + "." + format);
658 * Create a file in the user's repository downloads directory.
664 * @return created file DTO
665 * @throws IOException
666 * if file creation failed
668 private FileDTO createDownloadedFile(final long userId, final String fname)
670 // Create a file in the download directory
671 String filePath = getDownloadPath(userId) + fname;
672 FileWriter fw = new FileWriter(filePath);
673 fw.write("Simulation of " + fname + " file for checkin at "
676 return new FileDTO(filePath);
680 * Get path to the user's downloads directory. The directory is created if it is not exist yet.
684 * @return absolute path to downloads directory followed by slash
686 private String getDownloadPath(final long userId) {
687 // Prepare download directory
688 File tmpDir = _repositoryService.getDownloadDirectory(userId);
689 if (!tmpDir.exists()) {
690 Assert.assertTrue(tmpDir.mkdir(),
691 "Can't create temporary directory: "
692 + tmpDir.getAbsolutePath());
695 return tmpDir.getAbsolutePath() + "/";
699 * Create a persistent scenario for tests.
701 * @return a persistent scenario
702 * @throws InvalidPropertyException
703 * if an invalid property is used when creating objects
704 * @throws MultiplyDefinedException
705 * when trying to create an object with already existing id
706 * @throws MissedPropertyException
707 * if a mandatory property is not defined for an object to be created
708 * @throws IOException
709 * if document creation is failed
710 * @throws SQLException
711 * if project settings loading is failed
713 private long createScenario() throws InvalidPropertyException,
714 MissedPropertyException, MultiplyDefinedException, IOException,
716 // Create a scenario for tests
717 HibernateTemplate ht = getHibernateTemplate();
719 Database.getInstance().reset();
720 _projectSettings.getAllSteps().clear(); // Clear config to be able to load it again
721 // Load workflow customization
723 _projectSettings.configure(ClassLoader.getSystemResource(
724 "test/som.xml").getPath());
725 } catch (FileNotFoundException e) {
726 Assert.fail("Can't find som.xml: ", e);
728 List<Step> steps = _projectSettings.getStepsOf(Scenario.class);
729 Assert.assertTrue(steps.size() > 0, "No steps are created.");
731 // Create a test user
732 User.Properties uprop = new User.Properties();
733 uprop.setUsername("TST_Username").setName("TST_SimanUnitTestsUser")
734 .setFirstName("TST_FirstName").setDisplayName("TST_test.user")
735 .addRole("TST_user").setMailAddress(
736 "noreply@salome-platform.org");
737 uprop.disableCheck();
738 User anAuthor = new User(uprop);
739 ht.saveOrUpdate(anAuthor);
741 // Create a test study
742 Study.Properties stprops = new Study.Properties().setReference(
743 "TST_SID_01").setTitle("TST_Study").setManager(anAuthor);
744 Study aStudy = new Study(stprops);
745 ht.saveOrUpdate(aStudy);
747 // Create a test scenario
748 Scenario.Properties sprops = new Scenario.Properties().setTitle(
749 "TST_Scenario").setManager(anAuthor).setOwnerStudy(aStudy);
750 Scenario aScenario = new Scenario(sprops);
751 aStudy.getScenariiList().add(aScenario);
752 ht.saveOrUpdate(anAuthor);
753 ht.saveOrUpdate(aStudy);
754 ht.saveOrUpdate(aScenario);
756 // Create documents for each scenario step
757 Document.Properties dprop = new Document.Properties().setAuthor(
758 anAuthor).setDate(new Date());
760 Publication usedPub = null;
761 Map<Long, Long> usedMap = new HashMap<Long, Long>();
762 for (Step step : steps) {
763 LOG.debug("Create scenario step: " + i);
765 org.splat.som.Step aScStep = new org.splat.som.Step(step, aScenario);
766 List<DocumentType> dtypes = _documentTypeService
767 .selectTypesOf(step);
768 for (DocumentType dtype : dtypes) {
769 // Create a document published in the scenario
770 // document<i>: document type[0] - first type used on the step
771 // <source-file>.brep
772 // <attached-file>.med
773 dprop.setName("document" + i++).setType(dtype);
774 if (step.getNumber() > 3) {
775 dprop.setFormat("med");
777 dprop.setFormat("py");
779 dprop.setLocalPath(dprop.getName() + "." + dprop.getFormat());
780 Publication pub = createDoc(aScenario, aScStep, dprop, "med",
782 if (usedPub != null) {
783 pub.addDependency(usedPub);
784 ht.saveOrUpdate(pub.value());
786 usedMap.put(pub.getIndex(), usedPub.getIndex());
790 // Create another document with outdated publication
791 dprop.setName("document" + i++).setType(dtype).setFormat("py");
792 dprop.setLocalPath(dprop.getName() + "." + dprop.getFormat());
793 createDoc(aScenario, aScStep, dprop, "med", true);
796 if (dtypes.size() <= 0) {
797 LOG.debug("No document types are found for scenario step " + i);
801 // Check that the scenario and its documents have been created correctly.
803 Assert.assertNotNull(ht.find("from Document"),
804 "No documents in the database.");
805 Assert.assertTrue(ht.find("from Document").size() > 0,
806 "No documents in the database.");
808 Assert.assertNotNull(ht.find("from Publication where owner="
809 + aScenario.getIndex()), "No publications in the database.");
811 ht.find("from Publication where owner=" + aScenario.getIndex())
812 .size() > 0, "No publications in the database.");
814 for (Publication p : (List<Publication>) ht
815 .find("from Publication where owner=" + aScenario.getIndex())) {
816 LOG.debug("Publication found: [id=" + p.getIndex() + ", owner="
817 + p.getOwner().getIndex() + ", doc=" + p.value().getIndex()
819 Assert.assertEquals(p.getOwner().getIndex(), aScenario.getIndex(),
820 "The publication was not attached to the scenario.");
823 // Remove the scenario from the current hibernate session.
825 // Check that the scenario is created in the database.
826 Scenario aScen = ht.load(Scenario.class, aScenario.getIndex());
827 Assert.assertNotNull(aScen, "Scenario was not saved in the database.");
828 Assert.assertTrue(aScen.getDocums().size() > 0,
829 "No publications in the scenario.");
831 Assert.assertTrue(i > 0,
832 "More then one document must be in the database");
834 // Check created uses relations
836 .assertTrue(usedMap.size() > 0,
837 "Uses relations must be created.");
838 boolean foundAny = false;
839 for (Long usingId : usedMap.keySet()) {
840 for (Publication pub : aScen.getDocums()) {
841 if (pub.getIndex() == usingId) {
842 boolean found = false;
843 for (Publication used : aScen.getDocums()) {
844 found = (used.getIndex() == usedMap.get(usingId));
849 Assert.assertTrue(found,
850 "Uses relation was not created in the database.");
851 foundAny = foundAny || found;
855 Assert.assertTrue(foundAny,
856 "No Uses relation was created in the database.");
858 return aScenario.getIndex();
862 * Create a document published in the scenario. <BR>
864 * document type[0] - first type used on the step <BR>
865 * <source-file>.brep <BR>
866 * <attached-file>.med
869 * the scenario to add the document to
871 * scenario step where the document to be published
873 * document properties
874 * @param attachedFileExt
875 * extension of the secon attached (exported) file
877 * outdated document flag
878 * @return the publication of the created document
879 * @throws IOException
880 * @throws MultiplyDefinedException
881 * @throws InvalidPropertyException
882 * @throws MissedPropertyException
884 private Publication createDoc(final Scenario aScenario,
885 final org.splat.som.Step aScStep, final Properties dprop,
886 final String attachedFileExt, final boolean isOutdated)
887 throws MissedPropertyException, InvalidPropertyException,
888 MultiplyDefinedException, IOException {
889 // Create a document published in the scenario
890 // document<i>: document type[0] - first type used on the step
891 // <source-file>.brep
892 // <attached-file>.med
893 createDownloadedFile(aScenario.getAuthor().getIndex(), dprop
895 Publication pub = _stepService.createDocument(aScStep, dprop);
896 Assert.assertNotNull(pub.getOwner(),
897 "The publication must be attached to the scenario.");
898 Assert.assertEquals(pub.getOwner().getIndex(), aScenario.getIndex(),
899 "The publication was not attached to the scenario.");
905 HibernateTemplate ht = getHibernateTemplate();
906 ht.saveOrUpdate(pub);
909 createDownloadedFile(aScenario.getAuthor().getIndex(), dprop
910 .getLocalPath().substring(0,
911 dprop.getLocalPath().lastIndexOf(".") - 1),
913 ht.save(pub.value());
914 ht.saveOrUpdate(_publicationService.attach(pub, attachedFileExt));
920 * Test check-in scenario operation to be performed after SALOME session.<BR>
921 * <B>Description :</B> <BR>
922 * <i>Create a scenario and try to check-in it with some simulated SALOME results data.<BR>
923 * After check-in verify following points:
925 * <li>scenario is no more marked as checked out</li>
926 * <li>new document versions are created for checked in documents</li>
927 * <li>presentation of the previous version is removed</li>
928 * <li>uses relations are copied correctly</li>
929 * <li>files are moved correctly</li>
930 * <li>new documents are created for new data</li>
931 * <li>uses relations are created correctly</li>
932 * <li>files are moved correctly</li>
935 * <B>Action : </B><BR>
936 * <i>1. call the method for an existing scenario id.</i><BR>
937 * <i>2. call the method for a not existing scenario id.</i><BR>
938 * <B>Test data : </B><BR>
939 * <i>no input parameters</i><BR>
940 * <i>no input parameters</i><BR>
942 * <B>Outcome results:</B><BR>
945 * <li>New version of existing documents must be created and new documents must be imported for documents with zero id. Correct
946 * relations must be created.<BR>
948 * <li>Exception is thrown<BR>
953 * @throws InvalidPropertyException
954 * if an invalid property is used when creating objects
955 * @throws MultiplyDefinedException
956 * when trying to create an object with already existing id
957 * @throws MissedPropertyException
958 * if a mandatory property is not defined for an object to be created
959 * @throws IOException
960 * if scenario creation is failed
961 * @throws SQLException
962 * if scenario creation is failed
963 * @throws NotApplicableException
965 * @throws MismatchException
968 @Test(groups = { "study", "sevice", "functional", "business" })
969 public void testCreateStudy() throws InvalidPropertyException,
970 MissedPropertyException, MultiplyDefinedException, IOException,
971 SQLException, MismatchException, NotApplicableException {
972 LOG.debug(">>>>> BEGIN testCreateStudy()");
973 startNestedTransaction();
975 Database.getInstance().reset();
976 _projectSettings.getAllSteps().clear(); // Clear config to be able to load it again
977 _projectSettings.configure(ClassLoader
978 .getSystemResource("test/som.xml").getPath());
980 // Create a test user
981 User.Properties uprop = new User.Properties();
982 uprop.setUsername("TST_Username").setName("TST_SimanUnitTestsUser")
983 .setFirstName("TST_FirstName").setDisplayName("TST_test.user")
984 .addRole("TST_user").setMailAddress(
985 "noreply@salome-platform.org");
986 uprop.disableCheck();
987 User anAuthor = new User(uprop);
989 getHibernateTemplate().saveOrUpdate(anAuthor);
990 KnowledgeElementType ucase = _knowledgeElementTypeService
991 .selectType("usecase");
992 Assert.assertNotNull(ucase,
993 "Knowledge type 'usecase' must be created in the database.");
994 SimulationContextType prodtype = _simulationContextService
995 .selectType("product");
997 .assertNotNull(prodtype,
998 "Simulation context type 'product' must be created in the database.");
1002 uprop.setUsername("TST_Admin").setName("TST_SimanUnitTestsAdmin")
1003 .setFirstName("TST_AdminFirstName").setDisplayName(
1004 "TST_test.admin").addRole("TST_user,sysadmin")
1005 .setMailAddress("noreply@salome-platform.org");
1006 uprop.disableCheck();
1008 getHibernateTemplate().saveOrUpdate(new User(uprop));
1009 getHibernateTemplate().flush();
1011 Study.Properties sprop = new Study.Properties();
1012 sprop.setTitle("Test study creation").setManager(anAuthor);
1013 Scenario.Properties oprop = new Scenario.Properties();
1014 oprop.setTitle("Test scenario for the created study");
1016 // Addition of the entered project context
1017 SimulationContext.Properties cprop = new SimulationContext.Properties();
1018 // Input of new project context
1019 cprop.setType(_simulationContextService.selectType("product"))
1020 .setValue("Test Simulation Context: Product");
1021 Study study = _scenarioService.createStudy(sprop, oprop, cprop);
1023 rollbackNestedTransaction();
1024 LOG.debug(">>>>> END testCreateStudy()");