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 // Check that scenario is no more marked as checked out
374 aScen = _scenarioDAO.get(scenarioId);
375 Assert.assertFalse(aScen.isCheckedout(),
376 "Scenario is still marked as checked out after checkin.");
377 // Check that new document versions are created for checked in documents
378 boolean caseFound = false;
379 for (StepDTO step : stepsToCheckin) {
380 for (DocumentDTO docDTO : step.getDocs()) {
381 if ((docDTO.getId() != 0) && (docDTO.getId() != null)) {
382 boolean found = false;
383 Document prevDoc = null;
384 Publication newPub = null;
385 for (Publication pub : aScen.getDocums()) {
386 prevDoc = pub.value().getPreviousVersion();
387 if (prevDoc != null) {
388 found = (prevDoc.getIndex() == docDTO.getId());
389 if (found) { // Found next published version of the checked in document
395 Assert.assertTrue(found,
396 "New version of the existing checked in document \""
397 + docDTO.getTitle() + "\" (id="
399 + ") is not found in the scenario.");
400 // Check that presentation of the previous version is removed
401 Assert.assertFalse(aScen.publishes(prevDoc));
402 checkFiles(docDTO, newPub);
404 // Formats of files are new if they are according to the document's type on the study step
405 if ("py".equals(prevDoc.getFormat())
406 && "geometry".equals(prevDoc.getType().getName())) {
407 Assert.assertEquals(newPub.value().getFormat(), "brep");
408 Assert.assertEquals(newPub.getSourceFile().getFormat(),
410 Assert.assertEquals(newPub.getSourceFile()
411 .getRelativePath().substring(
412 newPub.getSourceFile()
413 .getRelativePath().lastIndexOf(
417 // Check that uses relations are copied correctly
419 // 1. Get all uses relations of the previous document version
420 for (Relation rel : prevDoc
421 .getRelations(UsesRelation.class)) {
422 Document used = ((UsesRelation) rel).getTo();
423 // 2.1. Get the latest version of the document published in this scenario
424 Publication toBeUsed = aScen.getPublication(used);
425 if (toBeUsed == null) {
426 // Find the latest published version
427 for (Publication lastPub : aScen.getDocums()) {
428 if ((lastPub.value().getPreviousVersion() != null)
430 .getPreviousVersion()
431 .getIndex() == used.getIndex())) {
437 if ((toBeUsed != null) && (!toBeUsed.isOutdated())) {
438 // 2.2. For each used document check that its latest not outdated version
439 // is used by the new checked in document version.
440 checkUsesRelation(newPub, toBeUsed);
443 // 1. Get all usedBy relations of the previous document version
444 for (Relation rel : prevDoc
445 .getRelations(UsedByRelation.class)) {
446 Document using = ((UsedByRelation) rel).getTo();
447 // Check that not checked in dependent documents became outdated
448 Publication usingPub = aScen.getPublication(using);
449 if (usingPub != null) { // if the document using the old version is still published
450 Assert.assertTrue(usingPub.isOutdated(),
451 "Not checked in dependent document "
452 + using.getTitle() + " ("
453 + using.getType().getName()
454 + ") must become outdated.");
460 // Check that new documents are created for new data
461 boolean found = false;
462 Publication newPub = null;
463 for (Publication pub : aScen.getDocums()) {
464 if (pub.value().getPreviousVersion() == null) {
465 found = (pub.value().getTitle().startsWith(pub
466 .value().getType().getName()));
467 if (found) { // Found next published version of the checked in document
468 String fcontent = Files.readFile(pub
469 .getSourceFile().asFile());
470 found = fcontent.contains(docDTO.getTitle());
473 .debug("Found new document with generated title: "
474 + pub.value().getTitle());
481 Assert.assertTrue(found,
482 "New document is not created for checked in document \""
483 + docDTO.getTitle() + "\".");
485 // Check that uses relations are created correctly
486 Assert.assertTrue(newPub.value().getTitle().startsWith(
487 newPub.value().getType().getName() + "_"),
488 "Document title newPub.value().getTitle() must start with "
489 + newPub.value().getType().getName() + "_");
491 // 1. Find the document type used by this document type
492 Set<DocumentType> usedTypes = newPub.value().getType()
494 // 2. Find documents of used types in the current study step and previous study steps
495 for (Publication pub : aScen.getDocums()) {
496 if ((pub.getStep().getNumber() <= step.getNumber())
497 && (!pub.isOutdated())
498 && usedTypes.contains(pub.value().getType())) {
499 // 3. Check that there is uses relation to the found document
500 // if it is not outdated.
501 checkUsesRelation(newPub, pub);
505 // Check that files are moved correctly
506 checkFiles(docDTO, newPub);
510 Assert.assertTrue(caseFound,
511 "Not checked in dependent documents must become outdated.");
513 // ///////////////////////////////////////////////////////////
514 // Call checkin method for a not existing id.
516 _scenarioService.checkin(-1, userId, stepsToCheckin);
518 .fail("Check in for scenario with not existing id must be failed.");
519 } catch (Exception e) {
520 LOG.debug("Expected exception is thrown: "
521 + e.getClass().getSimpleName() + ": " + e.getMessage());
524 // Test checkin with empty list of steps
525 stepsToCheckin.clear();
526 _scenarioService.checkin(scenarioId, userId, stepsToCheckin);
528 rollbackNestedTransaction();
529 LOG.debug(">>>>> END testCheckin()");
533 * Check if there is uses relation from the newPub to pub.
536 * the new publication
538 * the publication to be used
540 private void checkUsesRelation(final Publication newPub,
541 final Publication pub) {
542 boolean uses = false;
543 boolean usesExist = false;
544 for (Publication usesPub : newPub.getRelations(UsesRelation.class)) {
546 uses = (usesPub.equals(pub));
551 Assert.assertTrue(usesExist && uses, "The created document "
552 + newPub.value().getTitle() + "("
553 + newPub.value().getType().getName() + ")"
554 + " has no uses relation to the document "
555 + pub.value().getTitle() + "("
556 + pub.value().getType().getName() + ")");
560 * Check that files are moved correctly.
563 * checked in document DTO
565 * the created document publication
567 private void checkFiles(final DocumentDTO docDTO, final Publication newPub) {
568 // Check that original files are deleted
569 for (int j = 0; j < docDTO.getFiles().size(); j++) {
570 FileDTO fileDTO = docDTO.getFiles().get(j);
571 Assert.assertFalse(new File(fileDTO.getPath()).exists(), "File"
573 + " was not removed from downloads directory.");
574 String format = fileDTO.getPath().substring(
575 fileDTO.getPath().lastIndexOf('.') + 1);
577 // TODO: Check file by its internal content
578 Assert.assertTrue(newPub.getSourceFile().exists(), "File "
579 + newPub.getSourceFile().asFile().getAbsolutePath()
580 + " for the document " + docDTO.getTitle()
581 + " was not created.");
585 * Prepare a document with a file for check-in.
588 * step DTO with data for check-in
596 * checked out stepDTO
597 * @param stepsToCheckin
599 * @throws IOException
600 * if file creation failed
601 * @return step DTO with data prepared for check-in (stepTo or new if stepTo is null)
603 private StepDTO createDocDTOForModule(final StepDTO stepTo,
604 final String module, final String format, final long userId,
605 final StepDTO stepFrom, final List<StepDTO> stepsToCheckin)
607 StepDTO stepToCheckin = stepTo;
608 if (stepToCheckin == null) {
609 stepToCheckin = new StepDTO();
611 if (module.equals(stepFrom.getModule())) {
612 stepsToCheckin.add(stepToCheckin);
613 stepToCheckin.setNumber(stepFrom.getNumber());
614 for (DocumentDTO doc : stepFrom.getDocs()) {
615 if (doc.getFiles().get(0).getState() != 'O') {
616 DocumentDTO docToCheckin = stepToCheckin.addDoc(
617 doc.getId(), doc.getTitle());
618 for (FileDTO file : doc.getFiles()) {
619 if (file.getPath().endsWith(format)
620 || (file.getPath().endsWith("py") && format
622 // Create a file in the download directory
623 docToCheckin.addFile(createDownloadedFile(userId,
624 doc.getTitle() + "_result", format));
630 stepToCheckin.addDoc(0, "newdoc" + stepFrom.getNumber()).addFile(
631 createDownloadedFile(userId, "newdoc"
632 + stepFrom.getNumber(), "brep"));
634 return stepToCheckin;
638 * Create a file in the user's repository downloads directory.
646 * @return created file DTO
647 * @throws IOException
648 * if file creation failed
650 private FileDTO createDownloadedFile(final long userId, final String name,
651 final String format) throws IOException {
652 // Create a file in the download directory
653 String filePath = getDownloadPath(userId) + name + "." + format;
654 FileWriter fw = new FileWriter(filePath);
655 fw.write("Simulation of " + name + "." + format
656 + " file for checkin at " + new Date());
658 return new FileDTO(filePath);
662 * Get path to the user's downloads directory. The directory is created if it is not exist yet.
666 * @return absolute path to downloads directory followed by slash
668 private String getDownloadPath(final long userId) {
669 // Prepare download directory
670 File tmpDir = _repositoryService.getDownloadDirectory(userId);
671 if (!tmpDir.exists()) {
672 Assert.assertTrue(tmpDir.mkdir(),
673 "Can't create temporary directory: "
674 + tmpDir.getAbsolutePath());
677 return tmpDir.getAbsolutePath() + "/";
681 * Create a persistent scenario for tests.
683 * @return a persistent scenario
684 * @throws InvalidPropertyException
685 * if an invalid property is used when creating objects
686 * @throws MultiplyDefinedException
687 * when trying to create an object with already existing id
688 * @throws MissedPropertyException
689 * if a mandatory property is not defined for an object to be created
690 * @throws IOException
691 * if document creation is failed
692 * @throws SQLException
693 * if project settings loading is failed
695 private long createScenario() throws InvalidPropertyException,
696 MissedPropertyException, MultiplyDefinedException, IOException,
698 // Create a scenario for tests
699 HibernateTemplate ht = getHibernateTemplate();
701 Database.getInstance().reset();
702 _projectSettings.getAllSteps().clear(); // Clear config to be able to load it again
703 // Load workflow customization
705 _projectSettings.configure(ClassLoader.getSystemResource(
706 "test/som.xml").getPath());
707 } catch (FileNotFoundException e) {
708 Assert.fail("Can't find som.xml: ", e);
710 List<Step> steps = _projectSettings.getStepsOf(Scenario.class);
711 Assert.assertTrue(steps.size() > 0, "No steps are created.");
713 // Create a test user
714 User.Properties uprop = new User.Properties();
715 uprop.setUsername("TST_Username").setName("TST_SimanUnitTestsUser")
716 .setFirstName("TST_FirstName").setDisplayName("TST_test.user")
717 .addRole("TST_user").setMailAddress(
718 "noreply@salome-platform.org");
719 uprop.disableCheck();
720 User anAuthor = new User(uprop);
721 ht.saveOrUpdate(anAuthor);
723 // Create a test study
724 Study.Properties stprops = new Study.Properties().setReference(
725 "TST_SID_01").setTitle("TST_Study").setManager(anAuthor);
726 Study aStudy = new Study(stprops);
727 ht.saveOrUpdate(aStudy);
729 // Create a test scenario
730 Scenario.Properties sprops = new Scenario.Properties().setTitle(
731 "TST_Scenario").setManager(anAuthor).setOwnerStudy(aStudy);
732 Scenario aScenario = new Scenario(sprops);
733 aStudy.getScenariiList().add(aScenario);
734 ht.saveOrUpdate(anAuthor);
735 ht.saveOrUpdate(aStudy);
736 ht.saveOrUpdate(aScenario);
738 // Create documents for each scenario step
739 Document.Properties dprop = new Document.Properties().setAuthor(
740 anAuthor).setDate(new Date());
742 Publication usedPub = null;
743 Map<Long, Long> usedMap = new HashMap<Long, Long>();
744 for (Step step : steps) {
745 LOG.debug("Create scenario step: " + i);
747 org.splat.som.Step aScStep = new org.splat.som.Step(step, aScenario);
748 List<DocumentType> dtypes = _documentTypeService
749 .selectTypesOf(step);
750 for (DocumentType dtype : dtypes) {
751 // Create a document published in the scenario
752 // document<i>: document type[0] - first type used on the step
753 // <source-file>.brep
754 // <attached-file>.med
755 dprop.setName("document" + i++).setType(dtype);
756 if (step.getNumber() > 3) {
757 dprop.setFormat("med");
759 dprop.setFormat("py");
761 Publication pub = createDoc(aScenario, aScStep, dprop, "med",
763 if (usedPub != null) {
764 pub.addDependency(usedPub);
765 ht.saveOrUpdate(pub.value());
767 usedMap.put(pub.getIndex(), usedPub.getIndex());
771 // Create another document with outdated publication
772 dprop.setName("document" + i++).setType(dtype).setFormat("py");
773 createDoc(aScenario, aScStep, dprop, "med", true);
776 if (dtypes.size() <= 0) {
777 LOG.debug("No document types are found for scenario step " + i);
781 // Check that the scenario and its documents have been created correctly.
783 Assert.assertNotNull(ht.find("from Document"),
784 "No documents in the database.");
785 Assert.assertTrue(ht.find("from Document").size() > 0,
786 "No documents in the database.");
788 Assert.assertNotNull(ht.find("from Publication where owner="
789 + aScenario.getIndex()), "No publications in the database.");
791 ht.find("from Publication where owner=" + aScenario.getIndex())
792 .size() > 0, "No publications in the database.");
794 for (Publication p : (List<Publication>) ht
795 .find("from Publication where owner=" + aScenario.getIndex())) {
796 LOG.debug("Publication found: [id=" + p.getIndex() + ", owner="
797 + p.getOwner().getIndex() + ", doc=" + p.value().getIndex()
799 Assert.assertEquals(p.getOwner().getIndex(), aScenario.getIndex(),
800 "The publication was not attached to the scenario.");
803 // Remove the scenario from the current hibernate session.
805 // Check that the scenario is created in the database.
806 Scenario aScen = ht.load(Scenario.class, aScenario.getIndex());
807 Assert.assertNotNull(aScen, "Scenario was not saved in the database.");
808 Assert.assertTrue(aScen.getDocums().size() > 0,
809 "No publications in the scenario.");
811 Assert.assertTrue(i > 0,
812 "More then one document must be in the database");
814 // Check created uses relations
816 .assertTrue(usedMap.size() > 0,
817 "Uses relations must be created.");
818 boolean foundAny = false;
819 for (Long usingId : usedMap.keySet()) {
820 for (Publication pub : aScen.getDocums()) {
821 if (pub.getIndex() == usingId) {
822 boolean found = false;
823 for (Publication used : aScen.getDocums()) {
824 found = (used.getIndex() == usedMap.get(usingId));
829 Assert.assertTrue(found,
830 "Uses relation was not created in the database.");
831 foundAny = foundAny || found;
835 Assert.assertTrue(foundAny,
836 "No Uses relation was created in the database.");
838 return aScenario.getIndex();
842 * Create a document published in the scenario. <BR>
844 * document type[0] - first type used on the step <BR>
845 * <source-file>.brep <BR>
846 * <attached-file>.med
849 * the scenario to add the document to
851 * scenario step where the document to be published
853 * document properties
854 * @param attachedFileExt
855 * extension of the secon attached (exported) file
857 * outdated document flag
858 * @return the publication of the created document
859 * @throws IOException
860 * @throws MultiplyDefinedException
861 * @throws InvalidPropertyException
862 * @throws MissedPropertyException
864 private Publication createDoc(final Scenario aScenario,
865 final org.splat.som.Step aScStep, final Properties dprop,
866 final String attachedFileExt, final boolean isOutdated)
867 throws MissedPropertyException, InvalidPropertyException,
868 MultiplyDefinedException, IOException {
869 // Create a document published in the scenario
870 // document<i>: document type[0] - first type used on the step
871 // <source-file>.brep
872 // <attached-file>.med
873 Publication pub = _stepService.createDocument(aScStep, dprop);
874 Assert.assertNotNull(pub.getOwner(),
875 "The publication must be attached to the scenario.");
876 Assert.assertEquals(pub.getOwner().getIndex(), aScenario.getIndex(),
877 "The publication was not attached to the scenario.");
883 HibernateTemplate ht = getHibernateTemplate();
884 ht.saveOrUpdate(pub);
887 ht.save(pub.value());
888 ht.saveOrUpdate(_publicationService.attach(pub, attachedFileExt));
894 * Test check-in scenario operation to be performed after SALOME session.<BR>
895 * <B>Description :</B> <BR>
896 * <i>Create a scenario and try to check-in it with some simulated SALOME results data.<BR>
897 * After check-in verify following points:
899 * <li>scenario is no more marked as checked out</li>
900 * <li>new document versions are created for checked in documents</li>
901 * <li>presentation of the previous version is removed</li>
902 * <li>uses relations are copied correctly</li>
903 * <li>files are moved correctly</li>
904 * <li>new documents are created for new data</li>
905 * <li>uses relations are created correctly</li>
906 * <li>files are moved correctly</li>
909 * <B>Action : </B><BR>
910 * <i>1. call the method for an existing scenario id.</i><BR>
911 * <i>2. call the method for a not existing scenario id.</i><BR>
912 * <B>Test data : </B><BR>
913 * <i>no input parameters</i><BR>
914 * <i>no input parameters</i><BR>
916 * <B>Outcome results:</B><BR>
919 * <li>New version of existing documents must be created and new documents must be imported for documents with zero id. Correct
920 * relations must be created.<BR>
922 * <li>Exception is thrown<BR>
927 * @throws InvalidPropertyException
928 * if an invalid property is used when creating objects
929 * @throws MultiplyDefinedException
930 * when trying to create an object with already existing id
931 * @throws MissedPropertyException
932 * if a mandatory property is not defined for an object to be created
933 * @throws IOException
934 * if scenario creation is failed
935 * @throws SQLException
936 * if scenario creation is failed
937 * @throws NotApplicableException
939 * @throws MismatchException
942 @Test(groups = { "study", "sevice", "functional", "business" })
943 public void testCreateStudy() throws InvalidPropertyException,
944 MissedPropertyException, MultiplyDefinedException, IOException,
945 SQLException, MismatchException, NotApplicableException {
946 LOG.debug(">>>>> BEGIN testCreateStudy()");
947 startNestedTransaction();
949 Database.getInstance().reset();
950 _projectSettings.getAllSteps().clear(); // Clear config to be able to load it again
951 _projectSettings.configure(ClassLoader
952 .getSystemResource("test/som.xml").getPath());
954 // Create a test user
955 User.Properties uprop = new User.Properties();
956 uprop.setUsername("TST_Username").setName("TST_SimanUnitTestsUser")
957 .setFirstName("TST_FirstName").setDisplayName("TST_test.user")
958 .addRole("TST_user").setMailAddress(
959 "noreply@salome-platform.org");
960 uprop.disableCheck();
961 User anAuthor = new User(uprop);
963 getHibernateTemplate().saveOrUpdate(anAuthor);
964 KnowledgeElementType ucase = _knowledgeElementTypeService
965 .selectType("usecase");
966 Assert.assertNotNull(ucase,
967 "Knowledge type 'usecase' must be created in the database.");
968 SimulationContextType prodtype = _simulationContextService
969 .selectType("product");
971 .assertNotNull(prodtype,
972 "Simulation context type 'product' must be created in the database.");
976 uprop.setUsername("TST_Admin").setName("TST_SimanUnitTestsAdmin")
977 .setFirstName("TST_AdminFirstName").setDisplayName(
978 "TST_test.admin").addRole("TST_user,sysadmin")
979 .setMailAddress("noreply@salome-platform.org");
980 uprop.disableCheck();
982 getHibernateTemplate().saveOrUpdate(new User(uprop));
983 getHibernateTemplate().flush();
985 Study.Properties sprop = new Study.Properties();
986 sprop.setTitle("Test study creation").setManager(anAuthor);
987 Scenario.Properties oprop = new Scenario.Properties();
988 oprop.setTitle("Test scenario for the created study");
990 // Addition of the entered project context
991 SimulationContext.Properties cprop = new SimulationContext.Properties();
992 // Input of new project context
993 cprop.setType(_simulationContextService.selectType("product"))
994 .setValue("Test Simulation Context: Product");
995 Study study = _scenarioService.createStudy(sprop, oprop, cprop);
997 rollbackNestedTransaction();
998 LOG.debug(">>>>> END testCreateStudy()");