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();
354 // ////////////////////////////////////////////////////////
355 // Call checkin method for empty list of modules.
358 List<StepDTO> steps = _scenarioService.getScenarioInfo(scenarioId);
359 _scenarioService.checkout(aScen, user);
360 _scenarioDAO.flush();
361 // Check that scenario is no more marked as checked out
362 aScen = _scenarioDAO.get(scenarioId);
363 Assert.assertTrue(aScen.isCheckedout(),
364 "Scenario is not marked as checked out after checkout.");
366 // Prepare test data for checkin
367 // Checkin only two first steps (geom and mesh)
368 List<StepDTO> stepsToCheckin = new ArrayList<StepDTO>();
370 _scenarioService.checkin(scenarioId, userId, stepsToCheckin);
372 _scenarioDAO.flush();
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.");
380 // ////////////////////////////////////////////////////////
381 // Call checkin method for good prepared transient data.
384 steps = _scenarioService.getScenarioInfo(scenarioId);
385 _scenarioService.checkout(aScen, user);
387 // Prepare test data for checkin
388 // Checkin only two first steps (geom and mesh)
389 for (StepDTO step : steps) {
390 // Prepare GEOM: checkin actual brep
391 StepDTO stepToCheckin = createDocDTOForModule(null, "GEOM", "brep",
392 userId, step, stepsToCheckin);
393 createDocDTOForModule(stepToCheckin, "SMESH", "med", userId, step,
397 _scenarioService.checkin(scenarioId, userId, stepsToCheckin);
399 _scenarioDAO.flush();
400 // Check that scenario is no more marked as checked out
401 aScen = _scenarioDAO.get(scenarioId);
402 Assert.assertFalse(aScen.isCheckedout(),
403 "Scenario is still marked as checked out after checkin.");
404 // Check that new document versions are created for checked in documents
405 boolean caseFound = false;
406 for (StepDTO step : stepsToCheckin) {
407 for (DocumentDTO docDTO : step.getDocs()) {
408 if ((docDTO.getId() != 0) && (docDTO.getId() != null)) {
409 boolean found = false;
410 Document prevDoc = null;
411 Document curDoc = null;
412 Publication newPub = null;
413 for (Publication pub : aScen.getDocums()) {
414 prevDoc = pub.value().getPreviousVersion();
415 if (prevDoc != null) {
416 found = (prevDoc.getIndex() == docDTO.getId());
417 if (found) { // Found next published version of the checked in document
422 if (pub.value().getIndex() == docDTO.getId()) {
423 // Document version was not changed, old document is still published
424 curDoc = pub.value();
428 Assert.assertTrue(found || (curDoc != null),
429 "New version or new attached file of the existing checked in document \""
430 + docDTO.getTitle() + "\" (id="
432 + ") is not found in the scenario.");
433 // If previous version is found then the format must be the same
434 String newFormat = docDTO.getFiles().get(0).getPath()
436 docDTO.getFiles().get(0).getPath()
437 .lastIndexOf('.') + 1);
439 Assert.assertEquals(prevDoc.getFormat(), newFormat,
440 "Formats of versions must be same");
441 Assert.assertFalse(aScen.publishes(prevDoc));
442 // Check that presentation of the previous version is removed
443 checkFiles(docDTO, newPub);
445 // Formats of files are new if they are according to the document's type on the study step
446 if ("py".equals(prevDoc.getFormat())
447 && "geometry".equals(prevDoc.getType().getName())) {
448 Assert.assertEquals(newPub.value().getFormat(), "brep");
449 Assert.assertEquals(newPub.getSourceFile().getFormat(),
451 Assert.assertEquals(newPub.getSourceFile()
452 .getRelativePath().substring(
453 newPub.getSourceFile()
454 .getRelativePath().lastIndexOf(
458 // Check that uses relations are copied correctly
460 // 1. Get all uses relations of the previous document version
461 for (Relation rel : prevDoc
462 .getRelations(UsesRelation.class)) {
463 Document used = ((UsesRelation) rel).getTo();
464 // 2.1. Get the latest version of the document published in this scenario
465 Publication toBeUsed = aScen.getPublication(used);
466 if (toBeUsed == null) {
467 // Find the latest published version
468 for (Publication lastPub : aScen.getDocums()) {
469 if ((lastPub.value().getPreviousVersion() != null)
471 .getPreviousVersion()
472 .getIndex() == used.getIndex())) {
478 if ((toBeUsed != null) && (!toBeUsed.isOutdated())) {
479 // 2.2. For each used document check that its latest not outdated version
480 // is used by the new checked in document version.
481 checkUsesRelation(newPub, toBeUsed);
484 // 1. Get all usedBy relations of the previous document version
485 for (Relation rel : prevDoc
486 .getRelations(UsedByRelation.class)) {
487 Document using = ((UsedByRelation) rel).getTo();
488 // Check that not checked in dependent documents became outdated
489 Publication usingPub = aScen.getPublication(using);
490 if (usingPub != null) { // if the document using the old version is still published
491 Assert.assertTrue(usingPub.isOutdated(),
492 "Not checked in dependent document "
493 + using.getTitle() + " ("
494 + using.getType().getName()
495 + ") must become outdated.");
500 // Otherwise the new file format must differ from the previous one
501 // and the new file must be attached to the same document
502 org.splat.dal.bo.som.File attFile = curDoc
503 .getAttachedFile(newFormat);
504 Assert.assertNotNull(attFile, "File "
505 + docDTO.getFiles().get(0).getPath()
506 + " must be attached to the document "
507 + docDTO.getTitle() + "#" + docDTO.getId());
508 Assert.assertTrue(attFile.asFile().exists(), "File "
509 + docDTO.getFiles().get(0).getPath()
510 + " attached to the document "
511 + docDTO.getTitle() + "#" + docDTO.getId() + " doesn't exist");
516 // Check that new documents are created for new data
517 boolean found = false;
518 Publication newPub = null;
519 for (Publication pub : aScen.getDocums()) {
520 if (pub.value().getPreviousVersion() == null) {
521 found = (pub.value().getTitle().startsWith(pub
522 .value().getType().getName()));
523 if (found) { // Found next published version of the checked in document
524 String fcontent = Files.readFile(pub
525 .getSourceFile().asFile());
526 found = fcontent.contains(docDTO.getTitle());
529 .debug("Found new document with generated title: "
530 + pub.value().getTitle());
537 Assert.assertTrue(found,
538 "New document is not created for checked in document \""
539 + docDTO.getTitle() + "\".");
541 // Check that uses relations are created correctly
542 Assert.assertTrue(newPub.value().getTitle().startsWith(
543 newPub.value().getType().getName() + "_"),
544 "Document title newPub.value().getTitle() must start with "
545 + newPub.value().getType().getName() + "_");
547 // 1. Find the document type used by this document type
548 Set<DocumentType> usedTypes = newPub.value().getType()
550 // 2. Find documents of used types in the current study step and previous study steps
551 for (Publication pub : aScen.getDocums()) {
552 if ((pub.getStep().getNumber() <= step.getNumber())
553 && (!pub.isOutdated())
554 && usedTypes.contains(pub.value().getType())) {
555 // 3. Check that there is uses relation to the found document
556 // if it is not outdated.
557 checkUsesRelation(newPub, pub);
561 // Check that files are moved correctly
562 checkFiles(docDTO, newPub);
566 Assert.assertTrue(caseFound,
567 "Not checked in dependent documents must become outdated.");
569 // ///////////////////////////////////////////////////////////
570 // Call checkin method for a not existing id.
572 _scenarioService.checkin(-1, userId, stepsToCheckin);
574 .fail("Check in for scenario with not existing id must be failed.");
575 } catch (Exception e) {
576 LOG.debug("Expected exception is thrown: "
577 + e.getClass().getSimpleName() + ": " + e.getMessage());
580 // Test checkin with empty list of steps
581 stepsToCheckin.clear();
582 _scenarioService.checkin(scenarioId, userId, stepsToCheckin);
584 rollbackNestedTransaction();
585 LOG.debug(">>>>> END testCheckin()");
589 * Check if there is uses relation from the newPub to pub.
592 * the new publication
594 * the publication to be used
596 private void checkUsesRelation(final Publication newPub,
597 final Publication pub) {
598 boolean uses = false;
599 boolean usesExist = false;
600 for (Publication usesPub : newPub.getRelations(UsesRelation.class)) {
602 uses = (usesPub.equals(pub));
607 Assert.assertTrue(usesExist && uses, "The created document "
608 + newPub.value().getTitle() + "("
609 + newPub.value().getType().getName() + ")"
610 + " has no uses relation to the document "
611 + pub.value().getTitle() + "("
612 + pub.value().getType().getName() + ")");
616 * Check that files are moved correctly.
619 * checked in document DTO
621 * the created document publication
623 private void checkFiles(final DocumentDTO docDTO, final Publication newPub) {
624 // Check that original files are deleted
625 for (int j = 0; j < docDTO.getFiles().size(); j++) {
626 FileDTO fileDTO = docDTO.getFiles().get(j);
627 Assert.assertFalse(new File(fileDTO.getPath()).exists(), "File"
629 + " was not removed from downloads directory.");
630 String format = fileDTO.getPath().substring(
631 fileDTO.getPath().lastIndexOf('.') + 1);
633 // TODO: Check file by its internal content
634 Assert.assertTrue(newPub.getSourceFile().exists(), "File "
635 + newPub.getSourceFile().asFile().getAbsolutePath()
636 + " for the document " + docDTO.getTitle()
637 + " was not created.");
641 * Prepare a document with a file for check-in.
644 * step DTO with data for check-in
652 * checked out stepDTO
653 * @param stepsToCheckin
655 * @throws IOException
656 * if file creation failed
657 * @return step DTO with data prepared for check-in (stepTo or new if stepTo is null)
659 private StepDTO createDocDTOForModule(final StepDTO stepTo,
660 final String module, final String format, final long userId,
661 final StepDTO stepFrom, final List<StepDTO> stepsToCheckin)
663 StepDTO stepToCheckin = stepTo;
664 if (stepToCheckin == null) {
665 stepToCheckin = new StepDTO();
667 if (module.equals(stepFrom.getModule())) {
668 stepsToCheckin.add(stepToCheckin);
669 stepToCheckin.setNumber(stepFrom.getNumber());
670 for (DocumentDTO doc : stepFrom.getDocs()) {
671 if (doc.getFiles().get(0).getState() != 'O') {
672 DocumentDTO docToCheckin = stepToCheckin.addDoc(
673 doc.getId(), doc.getTitle());
674 for (FileDTO file : doc.getFiles()) {
675 if (file.getPath().endsWith(format)
676 || (file.getPath().endsWith("py") && format
678 // Create a file in the download directory
679 docToCheckin.addFile(createDownloadedFile(userId,
680 doc.getTitle() + "_result", format));
686 stepToCheckin.addDoc(0, "newdoc" + stepFrom.getNumber()).addFile(
687 createDownloadedFile(userId, "newdoc"
688 + stepFrom.getNumber(), "brep"));
690 return stepToCheckin;
694 * Create a file in the user's repository downloads directory.
702 * @return created file DTO
703 * @throws IOException
704 * if file creation failed
706 private FileDTO createDownloadedFile(final long userId, final String name,
707 final String format) throws IOException {
708 // Create a file in the download directory
709 return createDownloadedFile(userId, name + "." + format);
713 * Create a file in the user's repository downloads directory.
719 * @return created file DTO
720 * @throws IOException
721 * if file creation failed
723 private FileDTO createDownloadedFile(final long userId, final String fname)
725 // Create a file in the download directory
726 String filePath = getDownloadPath(userId) + fname;
727 FileWriter fw = new FileWriter(filePath);
728 fw.write("Simulation of " + fname + " file for checkin at "
731 return new FileDTO(filePath);
735 * Get path to the user's downloads directory. The directory is created if it is not exist yet.
739 * @return absolute path to downloads directory followed by slash
741 private String getDownloadPath(final long userId) {
742 // Prepare download directory
743 File tmpDir = _repositoryService.getDownloadDirectory(userId);
744 if (!tmpDir.exists()) {
745 Assert.assertTrue(tmpDir.mkdir(),
746 "Can't create temporary directory: "
747 + tmpDir.getAbsolutePath());
750 return tmpDir.getAbsolutePath() + "/";
754 * Create a persistent scenario for tests.
756 * @return a persistent scenario
757 * @throws InvalidPropertyException
758 * if an invalid property is used when creating objects
759 * @throws MultiplyDefinedException
760 * when trying to create an object with already existing id
761 * @throws MissedPropertyException
762 * if a mandatory property is not defined for an object to be created
763 * @throws IOException
764 * if document creation is failed
765 * @throws SQLException
766 * if project settings loading is failed
768 private long createScenario() throws InvalidPropertyException,
769 MissedPropertyException, MultiplyDefinedException, IOException,
771 // Create a scenario for tests
772 HibernateTemplate ht = getHibernateTemplate();
774 Database.getInstance().reset();
775 _projectSettings.getAllSteps().clear(); // Clear config to be able to load it again
776 // Load workflow customization
778 _projectSettings.configure(ClassLoader.getSystemResource(
779 "test/som.xml").getPath());
780 } catch (FileNotFoundException e) {
781 Assert.fail("Can't find som.xml: ", e);
783 List<Step> steps = _projectSettings.getStepsOf(Scenario.class);
784 Assert.assertTrue(steps.size() > 0, "No steps are created.");
786 // Create a test user
787 User.Properties uprop = new User.Properties();
788 uprop.setUsername("TST_Username").setName("TST_SimanUnitTestsUser")
789 .setFirstName("TST_FirstName").setDisplayName("TST_test.user")
790 .addRole("TST_user").setMailAddress(
791 "noreply@salome-platform.org");
792 uprop.disableCheck();
793 User anAuthor = new User(uprop);
794 ht.saveOrUpdate(anAuthor);
796 // Create a test study
797 Study.Properties stprops = new Study.Properties().setReference(
798 "TST_SID_01").setTitle("TST_Study").setManager(anAuthor);
799 Study aStudy = new Study(stprops);
800 ht.saveOrUpdate(aStudy);
802 // Create a test scenario
803 Scenario.Properties sprops = new Scenario.Properties().setTitle(
804 "TST_Scenario").setManager(anAuthor).setOwnerStudy(aStudy);
805 Scenario aScenario = new Scenario(sprops);
806 aStudy.getScenariiList().add(aScenario);
807 ht.saveOrUpdate(anAuthor);
808 ht.saveOrUpdate(aStudy);
809 ht.saveOrUpdate(aScenario);
811 // Create documents for each scenario step
812 Document.Properties dprop = new Document.Properties().setAuthor(
813 anAuthor).setDate(new Date());
815 Publication usedPub = null;
816 Map<Long, Long> usedMap = new HashMap<Long, Long>();
817 for (Step step : steps) {
818 LOG.debug("Create scenario step: " + i);
820 org.splat.som.Step aScStep = new org.splat.som.Step(step, aScenario);
821 List<DocumentType> dtypes = _documentTypeService
822 .selectTypesOf(step);
823 for (DocumentType dtype : dtypes) {
824 // Create a document published in the scenario
825 // document<i>: document type[0] - first type used on the step
826 // <source-file>.brep
827 // <attached-file>.med
828 dprop.setName("document" + i++).setType(dtype);
829 if (step.getNumber() > 3) {
830 dprop.setFormat("med");
832 dprop.setFormat("py");
834 dprop.setLocalPath(dprop.getName() + "." + dprop.getFormat());
835 Publication pub = createDoc(aScenario, aScStep, dprop, "med",
837 if (usedPub != null) {
838 pub.addDependency(usedPub);
839 ht.saveOrUpdate(pub.value());
841 usedMap.put(pub.getIndex(), usedPub.getIndex());
845 // Create another document with outdated publication
846 dprop.setName("document" + i++).setType(dtype).setFormat("py");
847 dprop.setLocalPath(dprop.getName() + "." + dprop.getFormat());
848 createDoc(aScenario, aScStep, dprop, "med", true);
851 if (dtypes.size() <= 0) {
852 LOG.debug("No document types are found for scenario step " + i);
856 // Check that the scenario and its documents have been created correctly.
858 Assert.assertNotNull(ht.find("from Document"),
859 "No documents in the database.");
860 Assert.assertTrue(ht.find("from Document").size() > 0,
861 "No documents in the database.");
863 Assert.assertNotNull(ht.find("from Publication where owner="
864 + aScenario.getIndex()), "No publications in the database.");
866 ht.find("from Publication where owner=" + aScenario.getIndex())
867 .size() > 0, "No publications in the database.");
869 for (Publication p : (List<Publication>) ht
870 .find("from Publication where owner=" + aScenario.getIndex())) {
871 LOG.debug("Publication found: [id=" + p.getIndex() + ", owner="
872 + p.getOwner().getIndex() + ", doc=" + p.value().getIndex()
874 Assert.assertEquals(p.getOwner().getIndex(), aScenario.getIndex(),
875 "The publication was not attached to the scenario.");
878 // Remove the scenario from the current hibernate session.
880 // Check that the scenario is created in the database.
881 Scenario aScen = ht.load(Scenario.class, aScenario.getIndex());
882 Assert.assertNotNull(aScen, "Scenario was not saved in the database.");
883 Assert.assertTrue(aScen.getDocums().size() > 0,
884 "No publications in the scenario.");
886 Assert.assertTrue(i > 0,
887 "More then one document must be in the database");
889 // Check created uses relations
891 .assertTrue(usedMap.size() > 0,
892 "Uses relations must be created.");
893 boolean foundAny = false;
894 for (Long usingId : usedMap.keySet()) {
895 for (Publication pub : aScen.getDocums()) {
896 if (pub.getIndex() == usingId) {
897 boolean found = false;
898 for (Publication used : aScen.getDocums()) {
899 found = (used.getIndex() == usedMap.get(usingId));
904 Assert.assertTrue(found,
905 "Uses relation was not created in the database.");
906 foundAny = foundAny || found;
910 Assert.assertTrue(foundAny,
911 "No Uses relation was created in the database.");
913 return aScenario.getIndex();
917 * Create a document published in the scenario. <BR>
919 * document type[0] - first type used on the step <BR>
920 * <source-file>.brep <BR>
921 * <attached-file>.med
924 * the scenario to add the document to
926 * scenario step where the document to be published
928 * document properties
929 * @param attachedFileExt
930 * extension of the secon attached (exported) file
932 * outdated document flag
933 * @return the publication of the created document
934 * @throws IOException
935 * @throws MultiplyDefinedException
936 * @throws InvalidPropertyException
937 * @throws MissedPropertyException
939 private Publication createDoc(final Scenario aScenario,
940 final org.splat.som.Step aScStep, final Properties dprop,
941 final String attachedFileExt, final boolean isOutdated)
942 throws MissedPropertyException, InvalidPropertyException,
943 MultiplyDefinedException, IOException {
944 // Create a document published in the scenario
945 // document<i>: document type[0] - first type used on the step
946 // <source-file>.brep
947 // <attached-file>.med
948 createDownloadedFile(aScenario.getAuthor().getIndex(), dprop
950 Publication pub = _stepService.createDocument(aScStep, dprop);
951 Assert.assertNotNull(pub.getOwner(),
952 "The publication must be attached to the scenario.");
953 Assert.assertEquals(pub.getOwner().getIndex(), aScenario.getIndex(),
954 "The publication was not attached to the scenario.");
960 HibernateTemplate ht = getHibernateTemplate();
961 ht.saveOrUpdate(pub);
964 createDownloadedFile(aScenario.getAuthor().getIndex(), dprop
965 .getLocalPath().substring(0,
966 dprop.getLocalPath().lastIndexOf(".") - 1),
968 ht.save(pub.value());
969 ht.saveOrUpdate(_publicationService.attach(pub, attachedFileExt));
975 * Test check-in scenario operation to be performed after SALOME session.<BR>
976 * <B>Description :</B> <BR>
977 * <i>Create a scenario and try to check-in it with some simulated SALOME results data.<BR>
978 * After check-in verify following points:
980 * <li>scenario is no more marked as checked out</li>
981 * <li>new document versions are created for checked in documents</li>
982 * <li>presentation of the previous version is removed</li>
983 * <li>uses relations are copied correctly</li>
984 * <li>files are moved correctly</li>
985 * <li>new documents are created for new data</li>
986 * <li>uses relations are created correctly</li>
987 * <li>files are moved correctly</li>
990 * <B>Action : </B><BR>
991 * <i>1. call the method for an existing scenario id.</i><BR>
992 * <i>2. call the method for a not existing scenario id.</i><BR>
993 * <B>Test data : </B><BR>
994 * <i>no input parameters</i><BR>
995 * <i>no input parameters</i><BR>
997 * <B>Outcome results:</B><BR>
1000 * <li>New version of existing documents must be created and new documents must be imported for documents with zero id. Correct
1001 * relations must be created.<BR>
1003 * <li>Exception is thrown<BR>
1008 * @throws InvalidPropertyException
1009 * if an invalid property is used when creating objects
1010 * @throws MultiplyDefinedException
1011 * when trying to create an object with already existing id
1012 * @throws MissedPropertyException
1013 * if a mandatory property is not defined for an object to be created
1014 * @throws IOException
1015 * if scenario creation is failed
1016 * @throws SQLException
1017 * if scenario creation is failed
1018 * @throws NotApplicableException
1020 * @throws MismatchException
1023 @Test(groups = { "study", "sevice", "functional", "business" })
1024 public void testCreateStudy() throws InvalidPropertyException,
1025 MissedPropertyException, MultiplyDefinedException, IOException,
1026 SQLException, MismatchException, NotApplicableException {
1027 LOG.debug(">>>>> BEGIN testCreateStudy()");
1028 startNestedTransaction();
1030 Database.getInstance().reset();
1031 _projectSettings.getAllSteps().clear(); // Clear config to be able to load it again
1032 _projectSettings.configure(ClassLoader
1033 .getSystemResource("test/som.xml").getPath());
1035 // Create a test user
1036 User.Properties uprop = new User.Properties();
1037 uprop.setUsername("TST_Username").setName("TST_SimanUnitTestsUser")
1038 .setFirstName("TST_FirstName").setDisplayName("TST_test.user")
1039 .addRole("TST_user").setMailAddress(
1040 "noreply@salome-platform.org");
1041 uprop.disableCheck();
1042 User anAuthor = new User(uprop);
1044 getHibernateTemplate().saveOrUpdate(anAuthor);
1045 KnowledgeElementType ucase = _knowledgeElementTypeService
1046 .selectType("usecase");
1047 Assert.assertNotNull(ucase,
1048 "Knowledge type 'usecase' must be created in the database.");
1049 SimulationContextType prodtype = _simulationContextService
1050 .selectType("product");
1052 .assertNotNull(prodtype,
1053 "Simulation context type 'product' must be created in the database.");
1057 uprop.setUsername("TST_Admin").setName("TST_SimanUnitTestsAdmin")
1058 .setFirstName("TST_AdminFirstName").setDisplayName(
1059 "TST_test.admin").addRole("TST_user,sysadmin")
1060 .setMailAddress("noreply@salome-platform.org");
1061 uprop.disableCheck();
1063 getHibernateTemplate().saveOrUpdate(new User(uprop));
1064 getHibernateTemplate().flush();
1066 Study.Properties sprop = new Study.Properties();
1067 sprop.setTitle("Test study creation").setManager(anAuthor);
1068 Scenario.Properties oprop = new Scenario.Properties();
1069 oprop.setTitle("Test scenario for the created study");
1071 // Addition of the entered project context
1072 SimulationContext.Properties cprop = new SimulationContext.Properties();
1073 // Input of new project context
1074 cprop.setType(_simulationContextService.selectType("product"))
1075 .setValue("Test Simulation Context: Product");
1076 Study study = _scenarioService.createStudy(sprop, oprop, cprop);
1078 rollbackNestedTransaction();
1079 LOG.debug(">>>>> END testCreateStudy()");