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 Document curDoc = null;
386 Publication newPub = null;
387 for (Publication pub : aScen.getDocums()) {
388 prevDoc = pub.value().getPreviousVersion();
389 if (prevDoc != null) {
390 found = (prevDoc.getIndex() == docDTO.getId());
391 if (found) { // Found next published version of the checked in document
396 if (pub.value().getIndex() == docDTO.getId()) {
397 // Document version was not changed, old document is still published
398 curDoc = pub.value();
402 Assert.assertTrue(found || (curDoc != null),
403 "New version or new attached file of the existing checked in document \""
404 + docDTO.getTitle() + "\" (id="
406 + ") is not found in the scenario.");
407 // If previous version is found then the format must be the same
408 String newFormat = docDTO.getFiles().get(0).getPath()
410 docDTO.getFiles().get(0).getPath()
411 .lastIndexOf('.') + 1);
413 Assert.assertEquals(prevDoc.getFormat(), newFormat,
414 "Formats of versions must be same");
415 Assert.assertFalse(aScen.publishes(prevDoc));
416 // Check that presentation of the previous version is removed
417 checkFiles(docDTO, newPub);
419 // Formats of files are new if they are according to the document's type on the study step
420 if ("py".equals(prevDoc.getFormat())
421 && "geometry".equals(prevDoc.getType().getName())) {
422 Assert.assertEquals(newPub.value().getFormat(), "brep");
423 Assert.assertEquals(newPub.getSourceFile().getFormat(),
425 Assert.assertEquals(newPub.getSourceFile()
426 .getRelativePath().substring(
427 newPub.getSourceFile()
428 .getRelativePath().lastIndexOf(
432 // Check that uses relations are copied correctly
434 // 1. Get all uses relations of the previous document version
435 for (Relation rel : prevDoc
436 .getRelations(UsesRelation.class)) {
437 Document used = ((UsesRelation) rel).getTo();
438 // 2.1. Get the latest version of the document published in this scenario
439 Publication toBeUsed = aScen.getPublication(used);
440 if (toBeUsed == null) {
441 // Find the latest published version
442 for (Publication lastPub : aScen.getDocums()) {
443 if ((lastPub.value().getPreviousVersion() != null)
445 .getPreviousVersion()
446 .getIndex() == used.getIndex())) {
452 if ((toBeUsed != null) && (!toBeUsed.isOutdated())) {
453 // 2.2. For each used document check that its latest not outdated version
454 // is used by the new checked in document version.
455 checkUsesRelation(newPub, toBeUsed);
458 // 1. Get all usedBy relations of the previous document version
459 for (Relation rel : prevDoc
460 .getRelations(UsedByRelation.class)) {
461 Document using = ((UsedByRelation) rel).getTo();
462 // Check that not checked in dependent documents became outdated
463 Publication usingPub = aScen.getPublication(using);
464 if (usingPub != null) { // if the document using the old version is still published
465 Assert.assertTrue(usingPub.isOutdated(),
466 "Not checked in dependent document "
467 + using.getTitle() + " ("
468 + using.getType().getName()
469 + ") must become outdated.");
474 // Otherwise the new file format must differ from the previous one
475 // and the new file must be attached to the same document
476 org.splat.dal.bo.som.File attFile = curDoc
477 .getAttachedFile(newFormat);
478 Assert.assertNotNull(attFile, "File "
479 + docDTO.getFiles().get(0).getPath()
480 + " must be attached to the document "
481 + docDTO.getTitle() + "#" + docDTO.getId());
482 Assert.assertTrue(attFile.asFile().exists(), "File "
483 + docDTO.getFiles().get(0).getPath()
484 + " attached to the document "
485 + docDTO.getTitle() + "#" + docDTO.getId() + " doesn't exist");
490 // Check that new documents are created for new data
491 boolean found = false;
492 Publication newPub = null;
493 for (Publication pub : aScen.getDocums()) {
494 if (pub.value().getPreviousVersion() == null) {
495 found = (pub.value().getTitle().startsWith(pub
496 .value().getType().getName()));
497 if (found) { // Found next published version of the checked in document
498 String fcontent = Files.readFile(pub
499 .getSourceFile().asFile());
500 found = fcontent.contains(docDTO.getTitle());
503 .debug("Found new document with generated title: "
504 + pub.value().getTitle());
511 Assert.assertTrue(found,
512 "New document is not created for checked in document \""
513 + docDTO.getTitle() + "\".");
515 // Check that uses relations are created correctly
516 Assert.assertTrue(newPub.value().getTitle().startsWith(
517 newPub.value().getType().getName() + "_"),
518 "Document title newPub.value().getTitle() must start with "
519 + newPub.value().getType().getName() + "_");
521 // 1. Find the document type used by this document type
522 Set<DocumentType> usedTypes = newPub.value().getType()
524 // 2. Find documents of used types in the current study step and previous study steps
525 for (Publication pub : aScen.getDocums()) {
526 if ((pub.getStep().getNumber() <= step.getNumber())
527 && (!pub.isOutdated())
528 && usedTypes.contains(pub.value().getType())) {
529 // 3. Check that there is uses relation to the found document
530 // if it is not outdated.
531 checkUsesRelation(newPub, pub);
535 // Check that files are moved correctly
536 checkFiles(docDTO, newPub);
540 Assert.assertTrue(caseFound,
541 "Not checked in dependent documents must become outdated.");
543 // ///////////////////////////////////////////////////////////
544 // Call checkin method for a not existing id.
546 _scenarioService.checkin(-1, userId, stepsToCheckin);
548 .fail("Check in for scenario with not existing id must be failed.");
549 } catch (Exception e) {
550 LOG.debug("Expected exception is thrown: "
551 + e.getClass().getSimpleName() + ": " + e.getMessage());
554 // Test checkin with empty list of steps
555 stepsToCheckin.clear();
556 _scenarioService.checkin(scenarioId, userId, stepsToCheckin);
558 rollbackNestedTransaction();
559 LOG.debug(">>>>> END testCheckin()");
563 * Check if there is uses relation from the newPub to pub.
566 * the new publication
568 * the publication to be used
570 private void checkUsesRelation(final Publication newPub,
571 final Publication pub) {
572 boolean uses = false;
573 boolean usesExist = false;
574 for (Publication usesPub : newPub.getRelations(UsesRelation.class)) {
576 uses = (usesPub.equals(pub));
581 Assert.assertTrue(usesExist && uses, "The created document "
582 + newPub.value().getTitle() + "("
583 + newPub.value().getType().getName() + ")"
584 + " has no uses relation to the document "
585 + pub.value().getTitle() + "("
586 + pub.value().getType().getName() + ")");
590 * Check that files are moved correctly.
593 * checked in document DTO
595 * the created document publication
597 private void checkFiles(final DocumentDTO docDTO, final Publication newPub) {
598 // Check that original files are deleted
599 for (int j = 0; j < docDTO.getFiles().size(); j++) {
600 FileDTO fileDTO = docDTO.getFiles().get(j);
601 Assert.assertFalse(new File(fileDTO.getPath()).exists(), "File"
603 + " was not removed from downloads directory.");
604 String format = fileDTO.getPath().substring(
605 fileDTO.getPath().lastIndexOf('.') + 1);
607 // TODO: Check file by its internal content
608 Assert.assertTrue(newPub.getSourceFile().exists(), "File "
609 + newPub.getSourceFile().asFile().getAbsolutePath()
610 + " for the document " + docDTO.getTitle()
611 + " was not created.");
615 * Prepare a document with a file for check-in.
618 * step DTO with data for check-in
626 * checked out stepDTO
627 * @param stepsToCheckin
629 * @throws IOException
630 * if file creation failed
631 * @return step DTO with data prepared for check-in (stepTo or new if stepTo is null)
633 private StepDTO createDocDTOForModule(final StepDTO stepTo,
634 final String module, final String format, final long userId,
635 final StepDTO stepFrom, final List<StepDTO> stepsToCheckin)
637 StepDTO stepToCheckin = stepTo;
638 if (stepToCheckin == null) {
639 stepToCheckin = new StepDTO();
641 if (module.equals(stepFrom.getModule())) {
642 stepsToCheckin.add(stepToCheckin);
643 stepToCheckin.setNumber(stepFrom.getNumber());
644 for (DocumentDTO doc : stepFrom.getDocs()) {
645 if (doc.getFiles().get(0).getState() != 'O') {
646 DocumentDTO docToCheckin = stepToCheckin.addDoc(
647 doc.getId(), doc.getTitle());
648 for (FileDTO file : doc.getFiles()) {
649 if (file.getPath().endsWith(format)
650 || (file.getPath().endsWith("py") && format
652 // Create a file in the download directory
653 docToCheckin.addFile(createDownloadedFile(userId,
654 doc.getTitle() + "_result", format));
660 stepToCheckin.addDoc(0, "newdoc" + stepFrom.getNumber()).addFile(
661 createDownloadedFile(userId, "newdoc"
662 + stepFrom.getNumber(), "brep"));
664 return stepToCheckin;
668 * Create a file in the user's repository downloads directory.
676 * @return created file DTO
677 * @throws IOException
678 * if file creation failed
680 private FileDTO createDownloadedFile(final long userId, final String name,
681 final String format) throws IOException {
682 // Create a file in the download directory
683 return createDownloadedFile(userId, name + "." + format);
687 * Create a file in the user's repository downloads directory.
693 * @return created file DTO
694 * @throws IOException
695 * if file creation failed
697 private FileDTO createDownloadedFile(final long userId, final String fname)
699 // Create a file in the download directory
700 String filePath = getDownloadPath(userId) + fname;
701 FileWriter fw = new FileWriter(filePath);
702 fw.write("Simulation of " + fname + " file for checkin at "
705 return new FileDTO(filePath);
709 * Get path to the user's downloads directory. The directory is created if it is not exist yet.
713 * @return absolute path to downloads directory followed by slash
715 private String getDownloadPath(final long userId) {
716 // Prepare download directory
717 File tmpDir = _repositoryService.getDownloadDirectory(userId);
718 if (!tmpDir.exists()) {
719 Assert.assertTrue(tmpDir.mkdir(),
720 "Can't create temporary directory: "
721 + tmpDir.getAbsolutePath());
724 return tmpDir.getAbsolutePath() + "/";
728 * Create a persistent scenario for tests.
730 * @return a persistent scenario
731 * @throws InvalidPropertyException
732 * if an invalid property is used when creating objects
733 * @throws MultiplyDefinedException
734 * when trying to create an object with already existing id
735 * @throws MissedPropertyException
736 * if a mandatory property is not defined for an object to be created
737 * @throws IOException
738 * if document creation is failed
739 * @throws SQLException
740 * if project settings loading is failed
742 private long createScenario() throws InvalidPropertyException,
743 MissedPropertyException, MultiplyDefinedException, IOException,
745 // Create a scenario for tests
746 HibernateTemplate ht = getHibernateTemplate();
748 Database.getInstance().reset();
749 _projectSettings.getAllSteps().clear(); // Clear config to be able to load it again
750 // Load workflow customization
752 _projectSettings.configure(ClassLoader.getSystemResource(
753 "test/som.xml").getPath());
754 } catch (FileNotFoundException e) {
755 Assert.fail("Can't find som.xml: ", e);
757 List<Step> steps = _projectSettings.getStepsOf(Scenario.class);
758 Assert.assertTrue(steps.size() > 0, "No steps are created.");
760 // Create a test user
761 User.Properties uprop = new User.Properties();
762 uprop.setUsername("TST_Username").setName("TST_SimanUnitTestsUser")
763 .setFirstName("TST_FirstName").setDisplayName("TST_test.user")
764 .addRole("TST_user").setMailAddress(
765 "noreply@salome-platform.org");
766 uprop.disableCheck();
767 User anAuthor = new User(uprop);
768 ht.saveOrUpdate(anAuthor);
770 // Create a test study
771 Study.Properties stprops = new Study.Properties().setReference(
772 "TST_SID_01").setTitle("TST_Study").setManager(anAuthor);
773 Study aStudy = new Study(stprops);
774 ht.saveOrUpdate(aStudy);
776 // Create a test scenario
777 Scenario.Properties sprops = new Scenario.Properties().setTitle(
778 "TST_Scenario").setManager(anAuthor).setOwnerStudy(aStudy);
779 Scenario aScenario = new Scenario(sprops);
780 aStudy.getScenariiList().add(aScenario);
781 ht.saveOrUpdate(anAuthor);
782 ht.saveOrUpdate(aStudy);
783 ht.saveOrUpdate(aScenario);
785 // Create documents for each scenario step
786 Document.Properties dprop = new Document.Properties().setAuthor(
787 anAuthor).setDate(new Date());
789 Publication usedPub = null;
790 Map<Long, Long> usedMap = new HashMap<Long, Long>();
791 for (Step step : steps) {
792 LOG.debug("Create scenario step: " + i);
794 org.splat.som.Step aScStep = new org.splat.som.Step(step, aScenario);
795 List<DocumentType> dtypes = _documentTypeService
796 .selectTypesOf(step);
797 for (DocumentType dtype : dtypes) {
798 // Create a document published in the scenario
799 // document<i>: document type[0] - first type used on the step
800 // <source-file>.brep
801 // <attached-file>.med
802 dprop.setName("document" + i++).setType(dtype);
803 if (step.getNumber() > 3) {
804 dprop.setFormat("med");
806 dprop.setFormat("py");
808 dprop.setLocalPath(dprop.getName() + "." + dprop.getFormat());
809 Publication pub = createDoc(aScenario, aScStep, dprop, "med",
811 if (usedPub != null) {
812 pub.addDependency(usedPub);
813 ht.saveOrUpdate(pub.value());
815 usedMap.put(pub.getIndex(), usedPub.getIndex());
819 // Create another document with outdated publication
820 dprop.setName("document" + i++).setType(dtype).setFormat("py");
821 dprop.setLocalPath(dprop.getName() + "." + dprop.getFormat());
822 createDoc(aScenario, aScStep, dprop, "med", true);
825 if (dtypes.size() <= 0) {
826 LOG.debug("No document types are found for scenario step " + i);
830 // Check that the scenario and its documents have been created correctly.
832 Assert.assertNotNull(ht.find("from Document"),
833 "No documents in the database.");
834 Assert.assertTrue(ht.find("from Document").size() > 0,
835 "No documents in the database.");
837 Assert.assertNotNull(ht.find("from Publication where owner="
838 + aScenario.getIndex()), "No publications in the database.");
840 ht.find("from Publication where owner=" + aScenario.getIndex())
841 .size() > 0, "No publications in the database.");
843 for (Publication p : (List<Publication>) ht
844 .find("from Publication where owner=" + aScenario.getIndex())) {
845 LOG.debug("Publication found: [id=" + p.getIndex() + ", owner="
846 + p.getOwner().getIndex() + ", doc=" + p.value().getIndex()
848 Assert.assertEquals(p.getOwner().getIndex(), aScenario.getIndex(),
849 "The publication was not attached to the scenario.");
852 // Remove the scenario from the current hibernate session.
854 // Check that the scenario is created in the database.
855 Scenario aScen = ht.load(Scenario.class, aScenario.getIndex());
856 Assert.assertNotNull(aScen, "Scenario was not saved in the database.");
857 Assert.assertTrue(aScen.getDocums().size() > 0,
858 "No publications in the scenario.");
860 Assert.assertTrue(i > 0,
861 "More then one document must be in the database");
863 // Check created uses relations
865 .assertTrue(usedMap.size() > 0,
866 "Uses relations must be created.");
867 boolean foundAny = false;
868 for (Long usingId : usedMap.keySet()) {
869 for (Publication pub : aScen.getDocums()) {
870 if (pub.getIndex() == usingId) {
871 boolean found = false;
872 for (Publication used : aScen.getDocums()) {
873 found = (used.getIndex() == usedMap.get(usingId));
878 Assert.assertTrue(found,
879 "Uses relation was not created in the database.");
880 foundAny = foundAny || found;
884 Assert.assertTrue(foundAny,
885 "No Uses relation was created in the database.");
887 return aScenario.getIndex();
891 * Create a document published in the scenario. <BR>
893 * document type[0] - first type used on the step <BR>
894 * <source-file>.brep <BR>
895 * <attached-file>.med
898 * the scenario to add the document to
900 * scenario step where the document to be published
902 * document properties
903 * @param attachedFileExt
904 * extension of the secon attached (exported) file
906 * outdated document flag
907 * @return the publication of the created document
908 * @throws IOException
909 * @throws MultiplyDefinedException
910 * @throws InvalidPropertyException
911 * @throws MissedPropertyException
913 private Publication createDoc(final Scenario aScenario,
914 final org.splat.som.Step aScStep, final Properties dprop,
915 final String attachedFileExt, final boolean isOutdated)
916 throws MissedPropertyException, InvalidPropertyException,
917 MultiplyDefinedException, IOException {
918 // Create a document published in the scenario
919 // document<i>: document type[0] - first type used on the step
920 // <source-file>.brep
921 // <attached-file>.med
922 createDownloadedFile(aScenario.getAuthor().getIndex(), dprop
924 Publication pub = _stepService.createDocument(aScStep, dprop);
925 Assert.assertNotNull(pub.getOwner(),
926 "The publication must be attached to the scenario.");
927 Assert.assertEquals(pub.getOwner().getIndex(), aScenario.getIndex(),
928 "The publication was not attached to the scenario.");
934 HibernateTemplate ht = getHibernateTemplate();
935 ht.saveOrUpdate(pub);
938 createDownloadedFile(aScenario.getAuthor().getIndex(), dprop
939 .getLocalPath().substring(0,
940 dprop.getLocalPath().lastIndexOf(".") - 1),
942 ht.save(pub.value());
943 ht.saveOrUpdate(_publicationService.attach(pub, attachedFileExt));
949 * Test check-in scenario operation to be performed after SALOME session.<BR>
950 * <B>Description :</B> <BR>
951 * <i>Create a scenario and try to check-in it with some simulated SALOME results data.<BR>
952 * After check-in verify following points:
954 * <li>scenario is no more marked as checked out</li>
955 * <li>new document versions are created for checked in documents</li>
956 * <li>presentation of the previous version is removed</li>
957 * <li>uses relations are copied correctly</li>
958 * <li>files are moved correctly</li>
959 * <li>new documents are created for new data</li>
960 * <li>uses relations are created correctly</li>
961 * <li>files are moved correctly</li>
964 * <B>Action : </B><BR>
965 * <i>1. call the method for an existing scenario id.</i><BR>
966 * <i>2. call the method for a not existing scenario id.</i><BR>
967 * <B>Test data : </B><BR>
968 * <i>no input parameters</i><BR>
969 * <i>no input parameters</i><BR>
971 * <B>Outcome results:</B><BR>
974 * <li>New version of existing documents must be created and new documents must be imported for documents with zero id. Correct
975 * relations must be created.<BR>
977 * <li>Exception is thrown<BR>
982 * @throws InvalidPropertyException
983 * if an invalid property is used when creating objects
984 * @throws MultiplyDefinedException
985 * when trying to create an object with already existing id
986 * @throws MissedPropertyException
987 * if a mandatory property is not defined for an object to be created
988 * @throws IOException
989 * if scenario creation is failed
990 * @throws SQLException
991 * if scenario creation is failed
992 * @throws NotApplicableException
994 * @throws MismatchException
997 @Test(groups = { "study", "sevice", "functional", "business" })
998 public void testCreateStudy() throws InvalidPropertyException,
999 MissedPropertyException, MultiplyDefinedException, IOException,
1000 SQLException, MismatchException, NotApplicableException {
1001 LOG.debug(">>>>> BEGIN testCreateStudy()");
1002 startNestedTransaction();
1004 Database.getInstance().reset();
1005 _projectSettings.getAllSteps().clear(); // Clear config to be able to load it again
1006 _projectSettings.configure(ClassLoader
1007 .getSystemResource("test/som.xml").getPath());
1009 // Create a test user
1010 User.Properties uprop = new User.Properties();
1011 uprop.setUsername("TST_Username").setName("TST_SimanUnitTestsUser")
1012 .setFirstName("TST_FirstName").setDisplayName("TST_test.user")
1013 .addRole("TST_user").setMailAddress(
1014 "noreply@salome-platform.org");
1015 uprop.disableCheck();
1016 User anAuthor = new User(uprop);
1018 getHibernateTemplate().saveOrUpdate(anAuthor);
1019 KnowledgeElementType ucase = _knowledgeElementTypeService
1020 .selectType("usecase");
1021 Assert.assertNotNull(ucase,
1022 "Knowledge type 'usecase' must be created in the database.");
1023 SimulationContextType prodtype = _simulationContextService
1024 .selectType("product");
1026 .assertNotNull(prodtype,
1027 "Simulation context type 'product' must be created in the database.");
1031 uprop.setUsername("TST_Admin").setName("TST_SimanUnitTestsAdmin")
1032 .setFirstName("TST_AdminFirstName").setDisplayName(
1033 "TST_test.admin").addRole("TST_user,sysadmin")
1034 .setMailAddress("noreply@salome-platform.org");
1035 uprop.disableCheck();
1037 getHibernateTemplate().saveOrUpdate(new User(uprop));
1038 getHibernateTemplate().flush();
1040 Study.Properties sprop = new Study.Properties();
1041 sprop.setTitle("Test study creation").setManager(anAuthor);
1042 Scenario.Properties oprop = new Scenario.Properties();
1043 oprop.setTitle("Test scenario for the created study");
1045 // Addition of the entered project context
1046 SimulationContext.Properties cprop = new SimulationContext.Properties();
1047 // Input of new project context
1048 cprop.setType(_simulationContextService.selectType("product"))
1049 .setValue("Test Simulation Context: Product");
1050 Study study = _scenarioService.createStudy(sprop, oprop, cprop);
1052 rollbackNestedTransaction();
1053 LOG.debug(">>>>> END testCreateStudy()");