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 for (StepDTO step : stepsToCheckin) {
406 for (DocumentDTO docDTO : step.getDocs()) {
407 if ((docDTO.getId() != 0) && (docDTO.getId() != null)) {
408 boolean found = false;
409 Document prevDoc = null;
410 Document curDoc = null;
411 Publication newPub = null;
412 for (Publication pub : aScen.getDocums()) {
413 prevDoc = pub.value().getPreviousVersion();
414 if (prevDoc != null) {
415 found = (prevDoc.getIndex() == docDTO.getId());
416 if (found) { // Found next published version of the checked in document
421 if (pub.value().getIndex() == docDTO.getId()) {
422 // Document version was not changed, old document is still published
423 curDoc = pub.value();
427 Assert.assertTrue(found || (curDoc != null),
428 "New version or new attached file of the existing checked in document \""
429 + docDTO.getTitle() + "\" (id="
431 + ") is not found in the scenario.");
432 // If previous version is found then the format must be the same
433 String newFormat = docDTO.getFiles().get(0).getPath()
435 docDTO.getFiles().get(0).getPath()
436 .lastIndexOf('.') + 1);
438 Assert.assertEquals(prevDoc.getFormat(), newFormat,
439 "Formats of versions must be same");
440 Assert.assertFalse(aScen.publishes(prevDoc));
441 // Check that presentation of the previous version is removed
442 checkFiles(docDTO, newPub);
444 // Formats of files are new if they are according to the document's type on the study step
445 if ("py".equals(prevDoc.getFormat())
446 && "geometry".equals(prevDoc.getType().getName())) {
447 Assert.assertEquals(newPub.value().getFormat(), "brep");
448 Assert.assertEquals(newPub.getSourceFile().getFormat(),
450 Assert.assertEquals(newPub.getSourceFile()
451 .getRelativePath().substring(
452 newPub.getSourceFile()
453 .getRelativePath().lastIndexOf(
457 // Check that uses relations are copied correctly
459 // 1. Get all uses relations of the previous document version
460 for (Relation rel : prevDoc
461 .getRelations(UsesRelation.class)) {
462 Document used = ((UsesRelation) rel).getTo();
463 // 2.1. Get the latest version of the document published in this scenario
464 Publication toBeUsed = aScen.getPublication(used);
465 if (toBeUsed == null) {
466 // Find the latest published version
467 for (Publication lastPub : aScen.getDocums()) {
468 if ((lastPub.value().getPreviousVersion() != null)
470 .getPreviousVersion()
471 .getIndex() == used.getIndex())) {
477 if ((toBeUsed != null) && (!toBeUsed.isOutdated())) {
478 // 2.2. For each used document check that its latest not outdated version
479 // is used by the new checked in document version.
480 checkUsesRelation(newPub, toBeUsed);
483 // 1. Get all usedBy relations of the previous document version
484 for (Relation rel : prevDoc
485 .getRelations(UsedByRelation.class)) {
486 Document using = ((UsedByRelation) rel).getTo();
487 // Check that not checked in dependent documents became outdated
488 Publication usingPub = aScen.getPublication(using);
489 if (usingPub != null) { // if the document using the old version is still published
490 Assert.assertTrue(usingPub.isOutdated(),
491 "Not checked in dependent document "
492 + using.getTitle() + " ("
493 + using.getType().getName()
494 + ") must become outdated.");
498 // Otherwise the new file format must differ from the previous one
499 // and the new file must be attached to the same document
500 org.splat.dal.bo.som.File attFile = curDoc
501 .getAttachedFile(newFormat);
502 Assert.assertNotNull(attFile, "File "
503 + docDTO.getFiles().get(0).getPath()
504 + " must be attached to the document "
505 + docDTO.getTitle() + "#" + docDTO.getId());
506 Assert.assertTrue(attFile.asFile().exists(), "File "
507 + docDTO.getFiles().get(0).getPath()
508 + " attached to the document "
509 + docDTO.getTitle() + "#" + docDTO.getId() + " doesn't exist");
510 LOG.debug("Source format: " + curDoc.getFormat() + ", new format: " + newFormat);
515 // Check that new documents are created for new data
516 boolean found = false;
517 Publication newPub = null;
518 for (Publication pub : aScen.getDocums()) {
519 if (pub.value().getPreviousVersion() == null) {
520 found = (pub.value().getTitle().startsWith(pub
521 .value().getType().getName()));
522 if (found) { // Found next published version of the checked in document
523 String fcontent = Files.readFile(pub
524 .getSourceFile().asFile());
525 found = fcontent.contains(docDTO.getTitle());
528 .debug("Found new document with generated title: "
529 + pub.value().getTitle());
536 Assert.assertTrue(found,
537 "New document is not created for checked in document \""
538 + docDTO.getTitle() + "\".");
540 // Check that uses relations are created correctly
541 Assert.assertTrue(newPub.value().getTitle().startsWith(
542 newPub.value().getType().getName() + "_"),
543 "Document title newPub.value().getTitle() must start with "
544 + newPub.value().getType().getName() + "_");
546 // 1. Find the document type used by this document type
547 Set<DocumentType> usedTypes = newPub.value().getType()
549 // 2. Find documents of used types in the current study step and previous study steps
550 for (Publication pub : aScen.getDocums()) {
551 if ((pub.getStep().getNumber() <= step.getNumber())
552 && (!pub.isOutdated())
553 && usedTypes.contains(pub.value().getType())) {
554 // 3. Check that there is uses relation to the found document
555 // if it is not outdated.
556 checkUsesRelation(newPub, pub);
560 // Check that files are moved correctly
561 checkFiles(docDTO, newPub);
566 // ///////////////////////////////////////////////////////////
567 // Call checkin method for a not existing id.
569 _scenarioService.checkin(-1, userId, stepsToCheckin);
571 .fail("Check in for scenario with not existing id must be failed.");
572 } catch (Exception e) {
573 LOG.debug("Expected exception is thrown: "
574 + e.getClass().getSimpleName() + ": " + e.getMessage());
577 // Test checkin with empty list of steps
578 stepsToCheckin.clear();
579 _scenarioService.checkin(scenarioId, userId, stepsToCheckin);
581 rollbackNestedTransaction();
582 LOG.debug(">>>>> END testCheckin()");
586 * Check if there is uses relation from the newPub to pub.
589 * the new publication
591 * the publication to be used
593 private void checkUsesRelation(final Publication newPub,
594 final Publication pub) {
595 boolean uses = false;
596 boolean usesExist = false;
597 for (Publication usesPub : newPub.getRelations(UsesRelation.class)) {
599 uses = (usesPub.equals(pub));
604 Assert.assertTrue(usesExist && uses, "The created document "
605 + newPub.value().getTitle() + "("
606 + newPub.value().getType().getName() + ")"
607 + " has no uses relation to the document "
608 + pub.value().getTitle() + "("
609 + pub.value().getType().getName() + ")");
613 * Check that files are moved correctly.
616 * checked in document DTO
618 * the created document publication
620 private void checkFiles(final DocumentDTO docDTO, final Publication newPub) {
621 // Check that original files are deleted
622 for (int j = 0; j < docDTO.getFiles().size(); j++) {
623 FileDTO fileDTO = docDTO.getFiles().get(j);
624 Assert.assertFalse(new File(fileDTO.getPath()).exists(), "File"
626 + " was not removed from downloads directory.");
627 String format = fileDTO.getPath().substring(
628 fileDTO.getPath().lastIndexOf('.') + 1);
630 // TODO: Check file by its internal content
631 Assert.assertTrue(newPub.getSourceFile().exists(), "File "
632 + newPub.getSourceFile().asFile().getAbsolutePath()
633 + " for the document " + docDTO.getTitle()
634 + " was not created.");
638 * Prepare a document with a file for check-in.
641 * step DTO with data for check-in
649 * checked out stepDTO
650 * @param stepsToCheckin
652 * @throws IOException
653 * if file creation failed
654 * @return step DTO with data prepared for check-in (stepTo or new if stepTo is null)
656 private StepDTO createDocDTOForModule(final StepDTO stepTo,
657 final String module, final String format, final long userId,
658 final StepDTO stepFrom, final List<StepDTO> stepsToCheckin)
660 StepDTO stepToCheckin = stepTo;
661 if (stepToCheckin == null) {
662 stepToCheckin = new StepDTO();
664 if (module.equals(stepFrom.getModule())) {
665 stepsToCheckin.add(stepToCheckin);
666 stepToCheckin.setNumber(stepFrom.getNumber());
667 for (DocumentDTO doc : stepFrom.getDocs()) {
668 if (doc.getFiles().get(0).getState() != 'O') {
669 DocumentDTO docToCheckin = stepToCheckin.addDoc(
670 doc.getId(), doc.getTitle());
671 for (FileDTO file : doc.getFiles()) {
672 if (file.getPath().endsWith(format)
673 || (file.getPath().endsWith("py") && (format
674 .equals("brep") || format
676 // Create a file in the download directory
677 docToCheckin.addFile(createDownloadedFile(userId,
678 doc.getTitle() + "_result", format));
684 stepToCheckin.addDoc(0, "newdoc" + stepFrom.getNumber()).addFile(
685 createDownloadedFile(userId, "newdoc"
686 + stepFrom.getNumber(), "brep"));
688 return stepToCheckin;
692 * Create a file in the user's repository downloads directory.
700 * @return created file DTO
701 * @throws IOException
702 * if file creation failed
704 private FileDTO createDownloadedFile(final long userId, final String name,
705 final String format) throws IOException {
706 // Create a file in the download directory
707 return createDownloadedFile(userId, name + "." + format);
711 * Create a file in the user's repository downloads directory.
717 * @return created file DTO
718 * @throws IOException
719 * if file creation failed
721 private FileDTO createDownloadedFile(final long userId, final String fname)
723 // Create a file in the download directory
724 String filePath = getDownloadPath(userId) + fname;
725 FileWriter fw = new FileWriter(filePath);
726 fw.write("Simulation of " + fname + " file for checkin at "
729 return new FileDTO(filePath);
733 * Get path to the user's downloads directory. The directory is created if it is not exist yet.
737 * @return absolute path to downloads directory followed by slash
739 private String getDownloadPath(final long userId) {
740 // Prepare download directory
741 File tmpDir = _repositoryService.getDownloadDirectory(userId);
742 if (!tmpDir.exists()) {
743 Assert.assertTrue(tmpDir.mkdir(),
744 "Can't create temporary directory: "
745 + tmpDir.getAbsolutePath());
748 return tmpDir.getAbsolutePath() + "/";
752 * Create a persistent scenario for tests.
754 * @return a persistent scenario
755 * @throws InvalidPropertyException
756 * if an invalid property is used when creating objects
757 * @throws MultiplyDefinedException
758 * when trying to create an object with already existing id
759 * @throws MissedPropertyException
760 * if a mandatory property is not defined for an object to be created
761 * @throws IOException
762 * if document creation is failed
763 * @throws SQLException
764 * if project settings loading is failed
766 private long createScenario() throws InvalidPropertyException,
767 MissedPropertyException, MultiplyDefinedException, IOException,
769 // Create a scenario for tests
770 HibernateTemplate ht = getHibernateTemplate();
772 Database.getInstance().reset();
773 _projectSettings.getAllSteps().clear(); // Clear config to be able to load it again
774 // Load workflow customization
776 _projectSettings.configure(ClassLoader.getSystemResource(
777 "test/som.xml").getPath());
778 } catch (FileNotFoundException e) {
779 Assert.fail("Can't find som.xml: ", e);
781 List<Step> steps = _projectSettings.getStepsOf(Scenario.class);
782 Assert.assertTrue(steps.size() > 0, "No steps are created.");
784 // Create a test user
785 User.Properties uprop = new User.Properties();
786 uprop.setUsername("TST_Username").setName("TST_SimanUnitTestsUser")
787 .setFirstName("TST_FirstName").setDisplayName("TST_test.user")
788 .addRole("TST_user").setMailAddress(
789 "noreply@salome-platform.org");
790 uprop.disableCheck();
791 User anAuthor = new User(uprop);
792 ht.saveOrUpdate(anAuthor);
794 // Create a test study
795 Study.Properties stprops = new Study.Properties().setReference(
796 "TST_SID_01").setTitle("TST_Study").setManager(anAuthor);
797 Study aStudy = new Study(stprops);
798 ht.saveOrUpdate(aStudy);
800 // Create a test scenario
801 Scenario.Properties sprops = new Scenario.Properties().setTitle(
802 "TST_Scenario").setManager(anAuthor).setOwnerStudy(aStudy);
803 Scenario aScenario = new Scenario(sprops);
804 aStudy.getScenariiList().add(aScenario);
805 ht.saveOrUpdate(anAuthor);
806 ht.saveOrUpdate(aStudy);
807 ht.saveOrUpdate(aScenario);
809 // Create documents for each scenario step
810 Document.Properties dprop = new Document.Properties().setAuthor(
811 anAuthor).setDate(new Date());
813 Publication usedPub = null;
814 Map<Long, Long> usedMap = new HashMap<Long, Long>();
815 for (Step step : steps) {
816 LOG.debug("Create scenario step: " + i);
818 org.splat.som.Step aScStep = new org.splat.som.Step(step, aScenario);
819 List<DocumentType> dtypes = _documentTypeService
820 .selectTypesOf(step);
821 for (DocumentType dtype : dtypes) {
822 // Create a document published in the scenario
823 // document<i>: document type[0] - first type used on the step
824 // <source-file>.brep
825 // <attached-file>.med
826 dprop.setName("document" + i++).setType(dtype);
827 /* if (step.getNumber() > 3) {
828 dprop.setFormat("med");
830 */ dprop.setFormat("py");
832 dprop.setLocalPath(dprop.getName() + "." + dprop.getFormat());
833 Publication pub = createDoc(aScenario, aScStep, dprop, "med",
835 if (usedPub != null) {
836 pub.addDependency(usedPub);
837 ht.saveOrUpdate(pub.value());
839 usedMap.put(pub.getIndex(), usedPub.getIndex());
843 // Create another document with outdated publication
844 dprop.setName("document" + i++).setType(dtype).setFormat("py");
845 dprop.setLocalPath(dprop.getName() + "." + dprop.getFormat());
846 createDoc(aScenario, aScStep, dprop, "med", true);
849 if (dtypes.size() <= 0) {
850 LOG.debug("No document types are found for scenario step " + i);
854 // Check that the scenario and its documents have been created correctly.
856 Assert.assertNotNull(ht.find("from Document"),
857 "No documents in the database.");
858 Assert.assertTrue(ht.find("from Document").size() > 0,
859 "No documents in the database.");
861 Assert.assertNotNull(ht.find("from Publication where owner="
862 + aScenario.getIndex()), "No publications in the database.");
864 ht.find("from Publication where owner=" + aScenario.getIndex())
865 .size() > 0, "No publications in the database.");
867 for (Publication p : (List<Publication>) ht
868 .find("from Publication where owner=" + aScenario.getIndex())) {
869 LOG.debug("Publication found: [id=" + p.getIndex() + ", owner="
870 + p.getOwner().getIndex() + ", doc=" + p.value().getIndex()
872 Assert.assertEquals(p.getOwner().getIndex(), aScenario.getIndex(),
873 "The publication was not attached to the scenario.");
876 // Remove the scenario from the current hibernate session.
878 // Check that the scenario is created in the database.
879 Scenario aScen = ht.load(Scenario.class, aScenario.getIndex());
880 Assert.assertNotNull(aScen, "Scenario was not saved in the database.");
881 Assert.assertTrue(aScen.getDocums().size() > 0,
882 "No publications in the scenario.");
884 Assert.assertTrue(i > 0,
885 "More then one document must be in the database");
887 // Check created uses relations
889 .assertTrue(usedMap.size() > 0,
890 "Uses relations must be created.");
891 boolean foundAny = false;
892 for (Long usingId : usedMap.keySet()) {
893 for (Publication pub : aScen.getDocums()) {
894 if (pub.getIndex() == usingId) {
895 boolean found = false;
896 for (Publication used : aScen.getDocums()) {
897 found = (used.getIndex() == usedMap.get(usingId));
902 Assert.assertTrue(found,
903 "Uses relation was not created in the database.");
904 foundAny = foundAny || found;
908 Assert.assertTrue(foundAny,
909 "No Uses relation was created in the database.");
911 return aScenario.getIndex();
915 * Create a document published in the scenario. <BR>
917 * document type[0] - first type used on the step <BR>
918 * <source-file>.brep <BR>
919 * <attached-file>.med
922 * the scenario to add the document to
924 * scenario step where the document to be published
926 * document properties
927 * @param attachedFileExt
928 * extension of the secon attached (exported) file
930 * outdated document flag
931 * @return the publication of the created document
932 * @throws IOException
933 * @throws MultiplyDefinedException
934 * @throws InvalidPropertyException
935 * @throws MissedPropertyException
937 private Publication createDoc(final Scenario aScenario,
938 final org.splat.som.Step aScStep, final Properties dprop,
939 final String attachedFileExt, final boolean isOutdated)
940 throws MissedPropertyException, InvalidPropertyException,
941 MultiplyDefinedException, IOException {
942 // Create a document published in the scenario
943 // document<i>: document type[0] - first type used on the step
944 // <source-file>.brep
945 // <attached-file>.med
946 createDownloadedFile(aScenario.getAuthor().getIndex(), dprop
948 Publication pub = _stepService.createDocument(aScStep, dprop);
949 Assert.assertNotNull(pub.getOwner(),
950 "The publication must be attached to the scenario.");
951 Assert.assertEquals(pub.getOwner().getIndex(), aScenario.getIndex(),
952 "The publication was not attached to the scenario.");
958 HibernateTemplate ht = getHibernateTemplate();
959 ht.saveOrUpdate(pub);
962 createDownloadedFile(aScenario.getAuthor().getIndex(), dprop
963 .getLocalPath().substring(0,
964 dprop.getLocalPath().lastIndexOf(".") - 1),
966 ht.save(pub.value());
967 ht.saveOrUpdate(_publicationService.attach(pub, attachedFileExt));
973 * Test check-in scenario operation to be performed after SALOME session.<BR>
974 * <B>Description :</B> <BR>
975 * <i>Create a scenario and try to check-in it with some simulated SALOME results data.<BR>
976 * After check-in verify following points:
978 * <li>scenario is no more marked as checked out</li>
979 * <li>new document versions are created for checked in documents</li>
980 * <li>presentation of the previous version is removed</li>
981 * <li>uses relations are copied correctly</li>
982 * <li>files are moved correctly</li>
983 * <li>new documents are created for new data</li>
984 * <li>uses relations are created correctly</li>
985 * <li>files are moved correctly</li>
988 * <B>Action : </B><BR>
989 * <i>1. call the method for an existing scenario id.</i><BR>
990 * <i>2. call the method for a not existing scenario id.</i><BR>
991 * <B>Test data : </B><BR>
992 * <i>no input parameters</i><BR>
993 * <i>no input parameters</i><BR>
995 * <B>Outcome results:</B><BR>
998 * <li>New version of existing documents must be created and new documents must be imported for documents with zero id. Correct
999 * relations must be created.<BR>
1001 * <li>Exception is thrown<BR>
1006 * @throws InvalidPropertyException
1007 * if an invalid property is used when creating objects
1008 * @throws MultiplyDefinedException
1009 * when trying to create an object with already existing id
1010 * @throws MissedPropertyException
1011 * if a mandatory property is not defined for an object to be created
1012 * @throws IOException
1013 * if scenario creation is failed
1014 * @throws SQLException
1015 * if scenario creation is failed
1016 * @throws NotApplicableException
1018 * @throws MismatchException
1021 @Test(groups = { "study", "sevice", "functional", "business" })
1022 public void testCreateStudy() throws InvalidPropertyException,
1023 MissedPropertyException, MultiplyDefinedException, IOException,
1024 SQLException, MismatchException, NotApplicableException {
1025 LOG.debug(">>>>> BEGIN testCreateStudy()");
1026 startNestedTransaction();
1028 Database.getInstance().reset();
1029 _projectSettings.getAllSteps().clear(); // Clear config to be able to load it again
1030 _projectSettings.configure(ClassLoader
1031 .getSystemResource("test/som.xml").getPath());
1033 // Create a test user
1034 User.Properties uprop = new User.Properties();
1035 uprop.setUsername("TST_Username").setName("TST_SimanUnitTestsUser")
1036 .setFirstName("TST_FirstName").setDisplayName("TST_test.user")
1037 .addRole("TST_user").setMailAddress(
1038 "noreply@salome-platform.org");
1039 uprop.disableCheck();
1040 User anAuthor = new User(uprop);
1042 getHibernateTemplate().saveOrUpdate(anAuthor);
1043 KnowledgeElementType ucase = _knowledgeElementTypeService
1044 .selectType("usecase");
1045 Assert.assertNotNull(ucase,
1046 "Knowledge type 'usecase' must be created in the database.");
1047 SimulationContextType prodtype = _simulationContextService
1048 .selectType("product");
1050 .assertNotNull(prodtype,
1051 "Simulation context type 'product' must be created in the database.");
1055 uprop.setUsername("TST_Admin").setName("TST_SimanUnitTestsAdmin")
1056 .setFirstName("TST_AdminFirstName").setDisplayName(
1057 "TST_test.admin").addRole("TST_user,sysadmin")
1058 .setMailAddress("noreply@salome-platform.org");
1059 uprop.disableCheck();
1061 getHibernateTemplate().saveOrUpdate(new User(uprop));
1062 getHibernateTemplate().flush();
1064 Study.Properties sprop = new Study.Properties();
1065 sprop.setTitle("Test study creation").setManager(anAuthor);
1066 Scenario.Properties oprop = new Scenario.Properties();
1067 oprop.setTitle("Test scenario for the created study");
1069 // Addition of the entered project context
1070 SimulationContext.Properties cprop = new SimulationContext.Properties();
1071 // Input of new project context
1072 cprop.setType(_simulationContextService.selectType("product"))
1073 .setValue("Test Simulation Context: Product");
1074 Study study = _scenarioService.createStudy(sprop, oprop, cprop);
1076 rollbackNestedTransaction();
1077 LOG.debug(">>>>> END testCreateStudy()");