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.ConvertsRelation;
26 import org.splat.dal.bo.som.Document;
27 import org.splat.dal.bo.som.DocumentType;
28 import org.splat.dal.bo.som.KnowledgeElementType;
29 import org.splat.dal.bo.som.Publication;
30 import org.splat.dal.bo.som.Scenario;
31 import org.splat.dal.bo.som.SimulationContext;
32 import org.splat.dal.bo.som.SimulationContextType;
33 import org.splat.dal.bo.som.Study;
34 import org.splat.dal.bo.som.UsedByRelation;
35 import org.splat.dal.bo.som.UsesRelation;
36 import org.splat.dal.bo.som.Document.Properties;
37 import org.splat.dal.dao.som.Database;
38 import org.splat.dal.dao.som.ScenarioDAO;
39 import org.splat.kernel.InvalidPropertyException;
40 import org.splat.kernel.MismatchException;
41 import org.splat.kernel.MissedPropertyException;
42 import org.splat.kernel.MultiplyDefinedException;
43 import org.splat.kernel.NotApplicableException;
44 import org.splat.log.AppLogger;
45 import org.splat.service.DocumentTypeService;
46 import org.splat.service.KnowledgeElementTypeService;
47 import org.splat.service.PublicationService;
48 import org.splat.service.ScenarioService;
49 import org.splat.service.SimulationContextService;
50 import org.splat.service.StepService;
51 import org.splat.service.dto.DocumentDTO;
52 import org.splat.service.dto.FileDTO;
53 import org.splat.service.dto.StepDTO;
54 import org.splat.service.technical.ProjectSettingsService;
55 import org.splat.service.technical.RepositoryService;
56 import org.splat.service.technical.ProjectSettingsService.Step;
57 import org.springframework.beans.factory.annotation.Autowired;
58 import org.springframework.beans.factory.annotation.Qualifier;
59 import org.springframework.orm.hibernate3.HibernateTemplate;
60 import org.testng.Assert;
61 import org.testng.annotations.Test;
62 import org.testng.reporters.Files;
64 import test.splat.common.BaseTest;
67 * Test class for ScenarioService.
69 * @author <a href="mailto:roman.kozlov@opencascade.com">Roman Kozlov (RKV)</a>
72 public class TestScenarioService extends BaseTest {
75 * Logger for the class.
77 private static final AppLogger LOG = AppLogger
78 .getLogger(TestScenarioService.class);
81 * The tested ScenarioService. Later injected by Spring.
84 @Qualifier("scenarioService")
85 private transient ScenarioService _scenarioService;
88 * The RepositoryService. Later injected by Spring.
91 @Qualifier("repositoryService")
92 private transient RepositoryService _repositoryService;
95 * The Scenario DAO. Later injected by Spring.
98 @Qualifier("scenarioDAO")
99 private transient ScenarioDAO _scenarioDAO;
102 * The PublicationService. Later injected by Spring.
105 @Qualifier("publicationService")
106 private transient PublicationService _publicationService;
109 * The StepService. Later injected by Spring.
112 @Qualifier("stepService")
113 private transient StepService _stepService;
116 * The SimulationContextService. Later injected by Spring.
119 @Qualifier("simulationContextService")
120 private transient SimulationContextService _simulationContextService;
123 * The ProjectSettingsService. Later injected by Spring.
126 @Qualifier("projectSettings")
127 private transient ProjectSettingsService _projectSettings;
130 * The DocumentTypeService. Later injected by Spring.
133 @Qualifier("documentTypeService")
134 private transient DocumentTypeService _documentTypeService;
137 * The KnowledgeElementTypeService. Later injected by Spring.
140 @Qualifier("knowledgeElementTypeService")
141 private transient KnowledgeElementTypeService _knowledgeElementTypeService;
144 * Test of getting a scenario content for building siman-salome.conf.<BR>
145 * <B>Description :</B> <BR>
146 * <i>Create a scenario and try to get an info for it.</i><BR>
147 * <B>Action : </B><BR>
148 * <i>1. call the method for an existing scenario id.</i><BR>
149 * <i>2. call the method for a not existing scenario id.</i><BR>
150 * <B>Test data : </B><BR>
151 * <i>no input parameters</i><BR>
152 * <i>no input parameters</i><BR>
154 * <B>Outcome results:</B><BR>
157 * <li>result DTO must contain list of all documents and files<BR>
159 * <li>Exception is thrown<BR>
164 * @throws InvalidPropertyException
165 * if an invalid property is used when creating objects
166 * @throws MultiplyDefinedException
167 * when trying to create an object with already existing id
168 * @throws MissedPropertyException
169 * if a mandatory property is not defined for an object to be created
170 * @throws IOException
171 * if scenario creation is failed
172 * @throws SQLException
173 * if scenario creation is failed
175 @Test(groups = { "checkout", "sevice", "functional", "business" })
176 public void testGetScenarioInfo() throws InvalidPropertyException,
177 MissedPropertyException, MultiplyDefinedException, IOException,
179 LOG.debug(">>>>> BEGIN testGetScenarioInfo()");
180 startNestedTransaction();
182 long scenarioId = createScenario();
183 // Call DAO's create method for a good transient knowledge element.
184 List<StepDTO> steps = _scenarioService.getScenarioInfo(scenarioId);
185 Assert.assertNotNull(steps, "List of steps must not be null.");
186 Assert.assertTrue(steps.size() > 0, "No steps are read.");
188 List<Step> projSteps = _projectSettings.getStepsOf(Scenario.class);
189 Assert.assertEquals(steps.size(), projSteps.size(),
190 "Not all steps are listed.");
192 for (StepDTO step : steps) {
193 LOG.debug("check the step " + step.getNumber() + ":\n" + step);
194 Assert.assertNotNull(step, "Step DTO must not be null.");
195 Assert.assertNotNull(step.getKey(), "Step name must not be null.");
196 Assert.assertFalse(step.getKey().isEmpty(),
197 "Step name must not empty.");
198 Assert.assertTrue(step.getNumber() > 0,
199 "Step number must be positive integer.");
200 Assert.assertNotNull(step.getDocs(),
201 "Step documents list must not be null.");
203 Step aProjStep = null;
204 for (Step projStep : projSteps) {
205 if (projStep.getNumber() == step.getNumber()) {
206 aProjStep = projStep;
211 List<DocumentType> dtypes = _documentTypeService
212 .selectTypesOf(aProjStep);
213 for (DocumentType dtype : dtypes) {
214 Assert.assertTrue(step.getDocs().size() > 0,
215 "Step documents list must not be empty.");
216 String docName = "document" + docIndex;
217 for (DocumentDTO doc : step.getDocs()) {
218 if (docName.equals(doc.getTitle())) {
219 Assert.assertTrue(doc.getId() > 0,
220 "Document id must be positive integer.");
221 Assert.assertEquals(doc.getTitle(), docName);
222 Assert.assertNotNull(doc.getFiles(),
223 "Document files list must not be null.");
225 .assertTrue(doc.getFiles().size() > 1,
226 "Document must have more then 1 attached file.");
228 for (FileDTO file : doc.getFiles()) {
229 Assert.assertNotNull(file.getPath(),
230 "File path must not be null.");
231 Assert.assertFalse(file.getPath().isEmpty(),
232 "File path must not be empty.");
234 * <mappings> <document type="geometry"> <import format="brep"/> <!-- Result Shape --> </document> <document
235 * type="model"> <import format="med"/> <!-- Result mesh without input parameters --> </document> <document
236 * type="loads"> <import format="c3m"/> <!-- Input data created interactively --> </document> <document
237 * type="results"> <import format="med"/> <!-- Calculation results source file --> </document> </mappings>
239 // Check state and processing instruction
240 String fileFormat = file.getPath().substring(
241 file.getPath().lastIndexOf('.') + 1);
243 * if (_projectSettings.doImport(dtype.getName(), fileFormat)) { Assert.assertTrue(file.isResult(), "The file
244 * must be a result file."); } else { Assert.assertFalse(file.isResult(), "The file must be a source file."); }
245 */if ((docIndex % 2) == 0) { // New
246 Assert.assertEquals(file.getState(), 'Y',
247 "File state must be actual ('Y').");
248 if (_projectSettings.doImport(dtype.getName(),
250 Assert.assertEquals(file.getProcessing(),
252 "File must be imported.");
254 Assert.assertEquals(file.getProcessing(),
256 "File must be downloaded.");
259 Assert.assertEquals(file.getState(), 'O',
260 "File state must be outdated ('O').");
262 .assertEquals(file.getProcessing(),
264 "Outdated document should not be imported but downloaded.");
273 // Call DAO's get method for a not existing id.
275 steps = _scenarioService.getScenarioInfo(-1L);
276 // getHibernateTemplate().flush();
278 .fail("Getting an object with not existing id must be failed.");
279 } catch (Exception e) {
280 LOG.debug("Expected exception is thrown: "
281 + e.getClass().getSimpleName() + ": " + e.getMessage());
283 rollbackNestedTransaction();
284 LOG.debug(">>>>> END testGetScenarioInfo()");
288 * Test check-in scenario operation to be performed after SALOME session.<BR>
289 * <B>Description :</B> <BR>
290 * <i>Create a scenario and try to check-in it with some simulated SALOME results data.<BR>
291 * After check-in verify following points:
293 * <li>scenario is no more marked as checked out</li>
294 * <li>new document versions are created for checked in documents</li>
295 * <li>presentation of the previous version is removed</li>
296 * <li>uses relations are copied correctly</li>
297 * <li>files are moved correctly</li>
298 * <li>formats of files are new if they are according to the document's type on the study step</li>
299 * <li>new documents are created for new data</li>
300 * <li>new documents have correctly generated names</li>
301 * <li>uses relations are created correctly</li>
302 * <li>files are moved correctly</li>
305 * <B>Action : </B><BR>
306 * <i>1. call the method for an existing scenario id.</i><BR>
307 * <i>2. call the method for a not existing scenario id.</i><BR>
308 * <B>Test data : </B><BR>
309 * <i>no input parameters</i><BR>
310 * <i>no input parameters</i><BR>
312 * <B>Outcome results:</B><BR>
315 * <li>New version of existing documents must be created and new documents must be imported for documents with zero id. Correct
316 * relations must be created.<BR>
318 * <li>Exception is thrown<BR>
323 * @throws InvalidPropertyException
324 * if an invalid property is used when creating objects
325 * @throws MultiplyDefinedException
326 * when trying to create an object with already existing id
327 * @throws MissedPropertyException
328 * if a mandatory property is not defined for an object to be created
329 * @throws IOException
330 * if scenario creation is failed
331 * @throws SQLException
332 * if scenario creation is failed
333 * @throws NotApplicableException
335 * @throws MismatchException
338 @Test(groups = { "checkin", "sevice", "functional", "business" })
339 public void testCheckin() throws InvalidPropertyException,
340 MissedPropertyException, MultiplyDefinedException, IOException,
341 SQLException, MismatchException, NotApplicableException {
342 LOG.debug(">>>>> BEGIN testCheckin()");
343 startNestedTransaction();
345 _projectSettings.getAllSteps().clear(); // Clear config to be able to load it again
346 _projectSettings.configure(ClassLoader
347 .getSystemResource("test/som.xml").getPath());
348 getHibernateTemplate().flush();
349 long scenarioId = createScenario();
350 Scenario aScen = _scenarioDAO.get(scenarioId);
351 User user = aScen.getAuthor();
352 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.");
378 // ////////////////////////////////////////////////////////
379 // Call checkin method for good prepared transient data.
382 steps = _scenarioService.getScenarioInfo(scenarioId);
383 _scenarioService.checkout(aScen, user);
385 // Remember modification dates of all attached files
386 Map<Long, Date> dates = new HashMap<Long, Date>();
387 for (Publication p : aScen.getDocums()) {
388 for (Relation r : p.value().getRelations(ConvertsRelation.class)) {
389 org.splat.dal.bo.som.File attach = ((ConvertsRelation) r)
391 dates.put(attach.getIndex(), attach.getDate());
395 // Prepare test data for checkin
396 // Checkin only two first steps (geom and mesh)
397 for (StepDTO step : steps) {
398 // Prepare GEOM: checkin actual brep
399 StepDTO stepToCheckin = createDocDTOForModule(null, "GEOM", "brep",
400 userId, step, stepsToCheckin);
401 createDocDTOForModule(stepToCheckin, "SMESH", "med", userId, step,
405 _scenarioService.checkin(scenarioId, userId, stepsToCheckin);
407 _scenarioDAO.flush();
408 // Check that scenario is no more marked as checked out
409 aScen = _scenarioDAO.get(scenarioId);
410 Assert.assertFalse(aScen.isCheckedout(),
411 "Scenario is still marked as checked out after checkin.");
412 boolean modifDatesChecked = false;
413 // Check that new document versions are created for checked in documents
414 for (StepDTO step : stepsToCheckin) {
415 for (DocumentDTO docDTO : step.getDocs()) {
416 if ((docDTO.getId() != 0) && (docDTO.getId() != null)) {
417 boolean found = false;
418 Document prevDoc = null;
419 Document curDoc = null;
420 Publication newPub = null;
421 for (Publication pub : aScen.getDocums()) {
422 prevDoc = pub.value().getPreviousVersion();
423 if (prevDoc != null) {
424 found = (prevDoc.getIndex() == docDTO.getId());
425 if (found) { // Found next published version of the checked in document
430 if (pub.value().getIndex() == docDTO.getId()) {
431 // Document version was not changed, old document is still published
432 curDoc = pub.value();
436 Assert.assertTrue(found || (curDoc != null),
437 "New version or new attached file of the existing checked in document \""
438 + docDTO.getTitle() + "\" (id="
440 + ") is not found in the scenario.");
441 // If previous version is found then the format must be the same
442 String newFormat = docDTO.getFiles().get(0).getPath()
444 docDTO.getFiles().get(0).getPath()
445 .lastIndexOf('.') + 1);
447 Assert.assertEquals(prevDoc.getFormat(), newFormat,
448 "Formats of versions must be same");
449 Assert.assertFalse(aScen.publishes(prevDoc));
450 // Check that presentation of the previous version is removed
451 checkFiles(docDTO, newPub);
453 // Formats of files are new if they are according to the document's type on the study step
454 if ("py".equals(prevDoc.getFormat())
455 && "geometry".equals(prevDoc.getType()
457 Assert.assertEquals(newPub.value().getFormat(),
459 Assert.assertEquals(newPub.getSourceFile()
460 .getFormat(), "brep");
461 Assert.assertEquals(newPub.getSourceFile()
462 .getRelativePath().substring(
463 newPub.getSourceFile()
465 .lastIndexOf('.') + 1),
469 // Check that uses relations are copied correctly
471 // 1. Get all uses relations of the previous document version
472 for (Relation rel : prevDoc
473 .getRelations(UsesRelation.class)) {
474 Document used = ((UsesRelation) rel).getTo();
475 // 2.1. Get the latest version of the document published in this scenario
476 Publication toBeUsed = aScen.getPublication(used);
477 if (toBeUsed == null) {
478 // Find the latest published version
479 for (Publication lastPub : aScen.getDocums()) {
480 if ((lastPub.value().getPreviousVersion() != null)
482 .getPreviousVersion()
490 if ((toBeUsed != null) && (!toBeUsed.isOutdated())) {
491 // 2.2. For each used document check that its latest not outdated version
492 // is used by the new checked in document version.
493 checkUsesRelation(newPub, toBeUsed);
496 // 1. Get all usedBy relations of the previous document version
497 for (Relation rel : prevDoc
498 .getRelations(UsedByRelation.class)) {
499 Document using = ((UsedByRelation) rel).getTo();
500 // Check that not checked in dependent documents became outdated
501 Publication usingPub = aScen.getPublication(using);
502 if (usingPub != null) { // if the document using the old version is still published
503 Assert.assertTrue(usingPub.isOutdated(),
504 "Not checked in dependent document "
505 + using.getTitle() + " ("
506 + using.getType().getName()
507 + ") must become outdated.");
511 // Otherwise the new file format must differ from the previous one
512 // and the new file must be attached to the same document
513 org.splat.dal.bo.som.File attFile = curDoc
514 .getAttachedFile(newFormat);
515 Assert.assertNotNull(attFile, "File "
516 + docDTO.getFiles().get(0).getPath()
517 + " must be attached to the document "
518 + docDTO.getTitle() + "#" + docDTO.getId());
519 Assert.assertTrue(attFile.asFile().exists(), "File "
520 + docDTO.getFiles().get(0).getPath()
521 + " attached to the document "
522 + docDTO.getTitle() + "#" + docDTO.getId()
524 LOG.debug("Source format: " + curDoc.getFormat()
525 + ", new format: " + newFormat);
526 // Check that attachment with the same format is not duplicated.
528 for (Relation conv : curDoc
529 .getRelations(ConvertsRelation.class)) {
530 if (newFormat.equals(((ConvertsRelation) conv)
531 .getTo().getFormat())) {
536 .assertEquals(attachNb, 1,
537 "Attachment with the same format must be only one.");
539 // Check that the attached file date is updated
540 if (dates.containsKey(attFile.getIndex())) {
542 .assertTrue(attFile.getDate().compareTo(
543 dates.get(attFile.getIndex())) > 0,
544 "Attachment modification date is not updated.");
545 modifDatesChecked = true;
550 // Check that new documents are created for new data
551 boolean found = false;
552 Publication newPub = null;
553 for (Publication pub : aScen.getDocums()) {
554 if (pub.value().getPreviousVersion() == null) {
555 found = (pub.value().getTitle().startsWith(pub
556 .value().getType().getName()));
557 if (found) { // Found next published version of the checked in document
558 String fcontent = Files.readFile(pub
559 .getSourceFile().asFile());
560 found = fcontent.contains(docDTO.getTitle());
563 .debug("Found new document with generated title: "
564 + pub.value().getTitle());
571 Assert.assertTrue(found,
572 "New document is not created for checked in document \""
573 + docDTO.getTitle() + "\".");
575 // Check that uses relations are created correctly
576 Assert.assertTrue(newPub.value().getTitle().startsWith(
577 newPub.value().getType().getName() + "_"),
578 "Document title newPub.value().getTitle() must start with "
579 + newPub.value().getType().getName() + "_");
581 // 1. Find the document type used by this document type
582 Set<DocumentType> usedTypes = newPub.value().getType()
584 // 2. Find documents of used types in the current study step and previous study steps
585 for (Publication pub : aScen.getDocums()) {
586 if ((pub.getStep().getNumber() <= step.getNumber())
587 && (!pub.isOutdated())
588 && usedTypes.contains(pub.value().getType())) {
589 // 3. Check that there is uses relation to the found document
590 // if it is not outdated.
591 checkUsesRelation(newPub, pub);
595 // Check that files are moved correctly
596 checkFiles(docDTO, newPub);
604 "No modification date is checked because no files were attached when attachment with same extension already exists.");
606 // ///////////////////////////////////////////////////////////
607 // Call checkin method for a not existing id.
609 _scenarioService.checkin(-1, userId, stepsToCheckin);
611 .fail("Check in for scenario with not existing id must be failed.");
612 } catch (Exception e) {
613 LOG.debug("Expected exception is thrown: "
614 + e.getClass().getSimpleName() + ": " + e.getMessage());
617 // Test checkin with empty list of steps
618 stepsToCheckin.clear();
619 _scenarioService.checkin(scenarioId, userId, stepsToCheckin);
621 rollbackNestedTransaction();
622 LOG.debug(">>>>> END testCheckin()");
626 * Check if there is uses relation from the newPub to pub.
629 * the new publication
631 * the publication to be used
633 private void checkUsesRelation(final Publication newPub,
634 final Publication pub) {
635 boolean uses = false;
636 boolean usesExist = false;
637 for (Publication usesPub : newPub.getRelations(UsesRelation.class)) {
639 uses = (usesPub.equals(pub));
644 Assert.assertTrue(usesExist && uses, "The created document "
645 + newPub.value().getTitle() + "("
646 + newPub.value().getType().getName() + ")"
647 + " has no uses relation to the document "
648 + pub.value().getTitle() + "("
649 + pub.value().getType().getName() + ")");
653 * Check that files are moved correctly.
656 * checked in document DTO
658 * the created document publication
660 private void checkFiles(final DocumentDTO docDTO, final Publication newPub) {
661 // Check that original files are deleted
662 for (int j = 0; j < docDTO.getFiles().size(); j++) {
663 FileDTO fileDTO = docDTO.getFiles().get(j);
664 Assert.assertFalse(new File(fileDTO.getPath()).exists(), "File"
666 + " was not removed from downloads directory.");
667 String format = fileDTO.getPath().substring(
668 fileDTO.getPath().lastIndexOf('.') + 1);
670 // TODO: Check file by its internal content
671 Assert.assertTrue(newPub.getSourceFile().exists(), "File "
672 + newPub.getSourceFile().asFile().getAbsolutePath()
673 + " for the document " + docDTO.getTitle()
674 + " was not created.");
678 * Prepare a document with a file for check-in.
681 * step DTO with data for check-in
689 * checked out stepDTO
690 * @param stepsToCheckin
692 * @throws IOException
693 * if file creation failed
694 * @return step DTO with data prepared for check-in (stepTo or new if stepTo is null)
696 private StepDTO createDocDTOForModule(final StepDTO stepTo,
697 final String module, final String format, final long userId,
698 final StepDTO stepFrom, final List<StepDTO> stepsToCheckin)
700 StepDTO stepToCheckin = stepTo;
701 if (stepToCheckin == null) {
702 stepToCheckin = new StepDTO();
704 if (module.equals(stepFrom.getModule())) {
705 stepsToCheckin.add(stepToCheckin);
706 stepToCheckin.setNumber(stepFrom.getNumber());
707 for (DocumentDTO doc : stepFrom.getDocs()) {
708 if (doc.getFiles().get(0).getState() != 'O') {
709 DocumentDTO docToCheckin = stepToCheckin.addDoc(
710 doc.getId(), doc.getTitle());
711 for (FileDTO file : doc.getFiles()) {
712 if (file.getPath().endsWith(format)
713 || (file.getPath().endsWith("py") && (format
714 .equals("brep") || format.equals("med")))) {
715 // Create a file in the download directory
716 docToCheckin.addFile(createDownloadedFile(userId,
717 doc.getTitle() + "_result", format));
723 stepToCheckin.addDoc(0, "newdoc" + stepFrom.getNumber()).addFile(
724 createDownloadedFile(userId, "newdoc"
725 + stepFrom.getNumber(), "brep"));
727 return stepToCheckin;
731 * Create a file in the user's repository downloads directory.
739 * @return created file DTO
740 * @throws IOException
741 * if file creation failed
743 private FileDTO createDownloadedFile(final long userId, final String name,
744 final String format) throws IOException {
745 // Create a file in the download directory
746 return createDownloadedFile(userId, name + "." + format);
750 * Create a file in the user's repository downloads directory.
756 * @return created file DTO
757 * @throws IOException
758 * if file creation failed
760 private FileDTO createDownloadedFile(final long userId, final String fname)
762 // Create a file in the download directory
763 String filePath = getDownloadPath(userId) + fname;
764 FileWriter fw = new FileWriter(filePath);
765 fw.write("Simulation of " + fname + " file for checkin at "
768 return new FileDTO(filePath);
772 * Get path to the user's downloads directory. The directory is created if it is not exist yet.
776 * @return absolute path to downloads directory followed by slash
778 private String getDownloadPath(final long userId) {
779 // Prepare download directory
780 File tmpDir = _repositoryService.getDownloadDirectory(userId);
781 if (!tmpDir.exists()) {
782 Assert.assertTrue(tmpDir.mkdir(),
783 "Can't create temporary directory: "
784 + tmpDir.getAbsolutePath());
787 return tmpDir.getAbsolutePath() + "/";
791 * Create a persistent scenario for tests.
793 * @return a persistent scenario
794 * @throws InvalidPropertyException
795 * if an invalid property is used when creating objects
796 * @throws MultiplyDefinedException
797 * when trying to create an object with already existing id
798 * @throws MissedPropertyException
799 * if a mandatory property is not defined for an object to be created
800 * @throws IOException
801 * if document creation is failed
802 * @throws SQLException
803 * if project settings loading is failed
805 private long createScenario() throws InvalidPropertyException,
806 MissedPropertyException, MultiplyDefinedException, IOException,
808 // Create a scenario for tests
809 HibernateTemplate ht = getHibernateTemplate();
811 Database.getInstance().reset();
812 _projectSettings.getAllSteps().clear(); // Clear config to be able to load it again
813 // Load workflow customization
815 _projectSettings.configure(ClassLoader.getSystemResource(
816 "test/som.xml").getPath());
817 } catch (FileNotFoundException e) {
818 Assert.fail("Can't find som.xml: ", e);
820 List<Step> steps = _projectSettings.getStepsOf(Scenario.class);
821 Assert.assertTrue(steps.size() > 0, "No steps are created.");
823 // Create a test user
824 User.Properties uprop = new User.Properties();
825 uprop.setUsername("TST_Username").setName("TST_SimanUnitTestsUser")
826 .setFirstName("TST_FirstName").setDisplayName("TST_test.user")
827 .addRole("TST_user").setMailAddress(
828 "noreply@salome-platform.org");
829 uprop.disableCheck();
830 User anAuthor = new User(uprop);
831 ht.saveOrUpdate(anAuthor);
833 // Create a test study
834 Study.Properties stprops = new Study.Properties().setReference(
835 "TST_SID_01").setTitle("TST_Study").setManager(anAuthor);
836 Study aStudy = new Study(stprops);
837 ht.saveOrUpdate(aStudy);
839 // Create a test scenario
840 Scenario.Properties sprops = new Scenario.Properties().setTitle(
841 "TST_Scenario").setManager(anAuthor).setOwnerStudy(aStudy);
842 Scenario aScenario = new Scenario(sprops);
843 aStudy.getScenariiList().add(aScenario);
844 ht.saveOrUpdate(anAuthor);
845 ht.saveOrUpdate(aStudy);
846 ht.saveOrUpdate(aScenario);
848 // Create documents for each scenario step
849 Document.Properties dprop = new Document.Properties().setAuthor(
850 anAuthor).setDate(new Date());
852 Publication usedPub = null;
853 Map<Long, Long> usedMap = new HashMap<Long, Long>();
854 for (Step step : steps) {
855 LOG.debug("Create scenario step: " + i);
857 org.splat.som.Step aScStep = new org.splat.som.Step(step, aScenario);
858 List<DocumentType> dtypes = _documentTypeService
859 .selectTypesOf(step);
860 for (DocumentType dtype : dtypes) {
861 // Create a document published in the scenario
862 // document<i>: document type[0] - first type used on the step
863 // <source-file>.brep
864 // <attached-file>.med
865 dprop.setName("document" + i++).setType(dtype);
867 * if (step.getNumber() > 3) { dprop.setFormat("med"); } else {
868 */dprop.setFormat("py");
870 dprop.setLocalPath(dprop.getName() + "." + dprop.getFormat());
871 Publication pub = createDoc(aScenario, aScStep, dprop, "med",
873 if (usedPub != null) {
874 pub.addDependency(usedPub);
875 ht.saveOrUpdate(pub.value());
877 usedMap.put(pub.getIndex(), usedPub.getIndex());
881 // Create another document with outdated publication
882 dprop.setName("document" + i++).setType(dtype).setFormat("py");
883 dprop.setLocalPath(dprop.getName() + "." + dprop.getFormat());
884 createDoc(aScenario, aScStep, dprop, "med", true);
887 if (dtypes.size() <= 0) {
888 LOG.debug("No document types are found for scenario step " + i);
892 // Check that the scenario and its documents have been created correctly.
894 Assert.assertNotNull(ht.find("from Document"),
895 "No documents in the database.");
896 Assert.assertTrue(ht.find("from Document").size() > 0,
897 "No documents in the database.");
899 Assert.assertNotNull(ht.find("from Publication where owner="
900 + aScenario.getIndex()), "No publications in the database.");
902 ht.find("from Publication where owner=" + aScenario.getIndex())
903 .size() > 0, "No publications in the database.");
905 for (Publication p : (List<Publication>) ht
906 .find("from Publication where owner=" + aScenario.getIndex())) {
907 LOG.debug("Publication found: [id=" + p.getIndex() + ", owner="
908 + p.getOwner().getIndex() + ", doc=" + p.value().getIndex()
910 Assert.assertEquals(p.getOwner().getIndex(), aScenario.getIndex(),
911 "The publication was not attached to the scenario.");
914 // Remove the scenario from the current hibernate session.
916 // Check that the scenario is created in the database.
917 Scenario aScen = ht.load(Scenario.class, aScenario.getIndex());
918 Assert.assertNotNull(aScen, "Scenario was not saved in the database.");
919 Assert.assertTrue(aScen.getDocums().size() > 0,
920 "No publications in the scenario.");
922 Assert.assertTrue(i > 0,
923 "More then one document must be in the database");
925 // Check created uses relations
927 .assertTrue(usedMap.size() > 0,
928 "Uses relations must be created.");
929 boolean foundAny = false;
930 for (Long usingId : usedMap.keySet()) {
931 for (Publication pub : aScen.getDocums()) {
932 if (pub.getIndex() == usingId) {
933 boolean found = false;
934 for (Publication used : aScen.getDocums()) {
935 found = (used.getIndex() == usedMap.get(usingId));
940 Assert.assertTrue(found,
941 "Uses relation was not created in the database.");
942 foundAny = foundAny || found;
946 Assert.assertTrue(foundAny,
947 "No Uses relation was created in the database.");
949 return aScenario.getIndex();
953 * Create a document published in the scenario. <BR>
955 * document type[0] - first type used on the step <BR>
956 * <source-file>.brep <BR>
957 * <attached-file>.med
960 * the scenario to add the document to
962 * scenario step where the document to be published
964 * document properties
965 * @param attachedFileExt
966 * extension of the secon attached (exported) file
968 * outdated document flag
969 * @return the publication of the created document
970 * @throws IOException
971 * @throws MultiplyDefinedException
972 * @throws InvalidPropertyException
973 * @throws MissedPropertyException
975 private Publication createDoc(final Scenario aScenario,
976 final org.splat.som.Step aScStep, final Properties dprop,
977 final String attachedFileExt, final boolean isOutdated)
978 throws MissedPropertyException, InvalidPropertyException,
979 MultiplyDefinedException, IOException {
980 // Create a document published in the scenario
981 // document<i>: document type[0] - first type used on the step
982 // <source-file>.brep
983 // <attached-file>.med
984 createDownloadedFile(aScenario.getAuthor().getIndex(), dprop
986 Publication pub = _stepService.createDocument(aScStep, dprop);
987 Assert.assertNotNull(pub.getOwner(),
988 "The publication must be attached to the scenario.");
989 Assert.assertEquals(pub.getOwner().getIndex(), aScenario.getIndex(),
990 "The publication was not attached to the scenario.");
996 HibernateTemplate ht = getHibernateTemplate();
997 ht.saveOrUpdate(pub);
1000 createDownloadedFile(aScenario.getAuthor().getIndex(), dprop
1001 .getLocalPath().substring(0,
1002 dprop.getLocalPath().lastIndexOf(".") - 1),
1004 ht.save(pub.value());
1005 ht.saveOrUpdate(_publicationService.attach(pub, attachedFileExt));
1011 * Test check-in scenario operation to be performed after SALOME session.<BR>
1012 * <B>Description :</B> <BR>
1013 * <i>Create a scenario and try to check-in it with some simulated SALOME results data.<BR>
1014 * After check-in verify following points:
1016 * <li>scenario is no more marked as checked out</li>
1017 * <li>new document versions are created for checked in documents</li>
1018 * <li>presentation of the previous version is removed</li>
1019 * <li>uses relations are copied correctly</li>
1020 * <li>files are moved correctly</li>
1021 * <li>new documents are created for new data</li>
1022 * <li>uses relations are created correctly</li>
1023 * <li>files are moved correctly</li>
1026 * <B>Action : </B><BR>
1027 * <i>1. call the method for an existing scenario id.</i><BR>
1028 * <i>2. call the method for a not existing scenario id.</i><BR>
1029 * <B>Test data : </B><BR>
1030 * <i>no input parameters</i><BR>
1031 * <i>no input parameters</i><BR>
1033 * <B>Outcome results:</B><BR>
1036 * <li>New version of existing documents must be created and new documents must be imported for documents with zero id. Correct
1037 * relations must be created.<BR>
1039 * <li>Exception is thrown<BR>
1044 * @throws InvalidPropertyException
1045 * if an invalid property is used when creating objects
1046 * @throws MultiplyDefinedException
1047 * when trying to create an object with already existing id
1048 * @throws MissedPropertyException
1049 * if a mandatory property is not defined for an object to be created
1050 * @throws IOException
1051 * if scenario creation is failed
1052 * @throws SQLException
1053 * if scenario creation is failed
1054 * @throws NotApplicableException
1056 * @throws MismatchException
1059 @Test(groups = { "study", "sevice", "functional", "business" })
1060 public void testCreateStudy() throws InvalidPropertyException,
1061 MissedPropertyException, MultiplyDefinedException, IOException,
1062 SQLException, MismatchException, NotApplicableException {
1063 LOG.debug(">>>>> BEGIN testCreateStudy()");
1064 startNestedTransaction();
1066 Database.getInstance().reset();
1067 _projectSettings.getAllSteps().clear(); // Clear config to be able to load it again
1068 _projectSettings.configure(ClassLoader
1069 .getSystemResource("test/som.xml").getPath());
1071 // Create a test user
1072 User.Properties uprop = new User.Properties();
1073 uprop.setUsername("TST_Username").setName("TST_SimanUnitTestsUser")
1074 .setFirstName("TST_FirstName").setDisplayName("TST_test.user")
1075 .addRole("TST_user").setMailAddress(
1076 "noreply@salome-platform.org");
1077 uprop.disableCheck();
1078 User anAuthor = new User(uprop);
1080 getHibernateTemplate().saveOrUpdate(anAuthor);
1081 KnowledgeElementType ucase = _knowledgeElementTypeService
1082 .selectType("usecase");
1083 Assert.assertNotNull(ucase,
1084 "Knowledge type 'usecase' must be created in the database.");
1085 SimulationContextType prodtype = _simulationContextService
1086 .selectType("product");
1088 .assertNotNull(prodtype,
1089 "Simulation context type 'product' must be created in the database.");
1093 uprop.setUsername("TST_Admin").setName("TST_SimanUnitTestsAdmin")
1094 .setFirstName("TST_AdminFirstName").setDisplayName(
1095 "TST_test.admin").addRole("TST_user,sysadmin")
1096 .setMailAddress("noreply@salome-platform.org");
1097 uprop.disableCheck();
1099 getHibernateTemplate().saveOrUpdate(new User(uprop));
1100 getHibernateTemplate().flush();
1102 Study.Properties sprop = new Study.Properties();
1103 sprop.setTitle("Test study creation").setManager(anAuthor);
1104 Scenario.Properties oprop = new Scenario.Properties();
1105 oprop.setTitle("Test scenario for the created study");
1107 // Addition of the entered project context
1108 SimulationContext.Properties cprop = new SimulationContext.Properties();
1109 // Input of new project context
1110 cprop.setType(_simulationContextService.selectType("product"))
1111 .setValue("Test Simulation Context: Product");
1112 Study study = _scenarioService.createStudy(sprop, oprop, cprop);
1114 rollbackNestedTransaction();
1115 LOG.debug(">>>>> END testCreateStudy()");