]> SALOME platform Git repositories - tools/siman.git/blob - Workspace/Siman-Common/src/test/splat/service/TestScenarioService.java
Salome HOME
Dependent not checked in documents are marked as outdated during checkin. Unit test...
[tools/siman.git] / Workspace / Siman-Common / src / test / splat / service / TestScenarioService.java
1 /*****************************************************************************
2  * Company         OPEN CASCADE
3  * Application     SIMAN
4  * File            $Id$ 
5  * Creation date   12 Oct 2012
6  * @author         $Author$
7  * @version        $Revision$
8  *****************************************************************************/
9 package test.splat.service;
10
11 import java.io.File;
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;
20 import java.util.Map;
21 import java.util.Set;
22
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.Publication;
28 import org.splat.dal.bo.som.Scenario;
29 import org.splat.dal.bo.som.Study;
30 import org.splat.dal.bo.som.UsedByRelation;
31 import org.splat.dal.bo.som.UsesRelation;
32 import org.splat.dal.bo.som.Document.Properties;
33 import org.splat.dal.dao.som.Database;
34 import org.splat.dal.dao.som.ScenarioDAO;
35 import org.splat.kernel.InvalidPropertyException;
36 import org.splat.kernel.MismatchException;
37 import org.splat.kernel.MissedPropertyException;
38 import org.splat.kernel.MultiplyDefinedException;
39 import org.splat.kernel.NotApplicableException;
40 import org.splat.log.AppLogger;
41 import org.splat.service.DocumentTypeService;
42 import org.splat.service.PublicationService;
43 import org.splat.service.ScenarioService;
44 import org.splat.service.StepService;
45 import org.splat.service.dto.DocumentDTO;
46 import org.splat.service.dto.FileDTO;
47 import org.splat.service.dto.StepDTO;
48 import org.splat.service.technical.ProjectSettingsService;
49 import org.splat.service.technical.RepositoryService;
50 import org.splat.service.technical.ProjectSettingsService.Step;
51 import org.springframework.beans.factory.annotation.Autowired;
52 import org.springframework.beans.factory.annotation.Qualifier;
53 import org.springframework.orm.hibernate3.HibernateTemplate;
54 import org.testng.Assert;
55 import org.testng.annotations.Test;
56
57 import test.splat.common.BaseTest;
58
59 /**
60  * Test class for KnowledgeElementDAO.
61  * 
62  * @author <a href="mailto:roman.kozlov@opencascade.com">Roman Kozlov (RKV)</a>
63  * 
64  */
65 public class TestScenarioService extends BaseTest {
66
67         /**
68          * Logger for the class.
69          */
70         private static final AppLogger LOG = AppLogger
71                         .getLogger(TestScenarioService.class);
72
73         /**
74          * The tested ScenarioService. Later injected by Spring.
75          */
76         @Autowired
77         @Qualifier("scenarioService")
78         private transient ScenarioService _scenarioService;
79
80         /**
81          * The RepositoryService. Later injected by Spring.
82          */
83         @Autowired
84         @Qualifier("repositoryService")
85         private transient RepositoryService _repositoryService;
86
87         /**
88          * The Scenario DAO. Later injected by Spring.
89          */
90         @Autowired
91         @Qualifier("scenarioDAO")
92         private transient ScenarioDAO _scenarioDAO;
93
94         /**
95          * The PublicationService. Later injected by Spring.
96          */
97         @Autowired
98         @Qualifier("publicationService")
99         private transient PublicationService _publicationService;
100
101         /**
102          * The StepService. Later injected by Spring.
103          */
104         @Autowired
105         @Qualifier("stepService")
106         private transient StepService _stepService;
107
108         /**
109          * The ProjectSettingsService. Later injected by Spring.
110          */
111         @Autowired
112         @Qualifier("projectSettings")
113         private transient ProjectSettingsService _projectSettings;
114
115         /**
116          * The DocumentTypeService. Later injected by Spring.
117          */
118         @Autowired
119         @Qualifier("documentTypeService")
120         private transient DocumentTypeService _documentTypeService;
121
122         /**
123          * Test of getting a scenario content for building siman-salome.conf.<BR>
124          * <B>Description :</B> <BR>
125          * <i>Create a scenario and try to get an info for it.</i><BR>
126          * <B>Action : </B><BR>
127          * <i>1. call the method for an existing scenario id.</i><BR>
128          * <i>2. call the method for a not existing scenario id.</i><BR>
129          * <B>Test data : </B><BR>
130          * <i>no input parameters</i><BR>
131          * <i>no input parameters</i><BR>
132          * 
133          * <B>Outcome results:</B><BR>
134          * <i>
135          * <ul>
136          * <li>result DTO must contain list of all documents and files<BR>
137          * </li>
138          * <li>Exception is thrown<BR>
139          * </li>
140          * </ul>
141          * </i>
142          * 
143          * @throws InvalidPropertyException
144          *             if an invalid property is used when creating objects
145          * @throws MultiplyDefinedException
146          *             when trying to create an object with already existing id
147          * @throws MissedPropertyException
148          *             if a mandatory property is not defined for an object to be created
149          * @throws IOException
150          *             if scenario creation is failed
151          * @throws SQLException
152          *             if scenario creation is failed
153          */
154         @Test
155         public void testGetScenarioInfo() throws InvalidPropertyException,
156                         MissedPropertyException, MultiplyDefinedException, IOException,
157                         SQLException {
158                 LOG.debug(">>>>> BEGIN testGetScenarioInfo()");
159                 long scenarioId = createScenario();
160                 // Call DAO's create method for a good transient knowledge element.
161                 List<StepDTO> steps = _scenarioService.getScenarioInfo(scenarioId);
162                 Assert.assertNotNull(steps, "List of steps must not be null.");
163                 Assert.assertTrue(steps.size() > 0, "No steps are read.");
164
165                 List<Step> projSteps = _projectSettings.getStepsOf(Scenario.class);
166                 Assert.assertEquals(steps.size(), projSteps.size(),
167                                 "Not all steps are listed.");
168                 int docIndex = 0;
169                 for (StepDTO step : steps) {
170                         LOG.debug("check the step " + step.getNumber() + ":\n" + step);
171                         Assert.assertNotNull(step, "Step DTO must not be null.");
172                         Assert.assertNotNull(step.getKey(), "Step name must not be null.");
173                         Assert.assertFalse(step.getKey().isEmpty(),
174                                         "Step name must not empty.");
175                         Assert.assertTrue(step.getNumber() > 0,
176                                         "Step number must be positive integer.");
177                         Assert.assertNotNull(step.getDocs(),
178                                         "Step documents list must not be null.");
179
180                         Step aProjStep = null;
181                         for (Step projStep : projSteps) {
182                                 if (projStep.getNumber() == step.getNumber()) {
183                                         aProjStep = projStep;
184                                         break;
185                                 }
186                         }
187
188                         List<DocumentType> dtypes = _documentTypeService
189                                         .selectTypesOf(aProjStep);
190                         for (DocumentType dtype : dtypes) {
191                                 Assert.assertTrue(step.getDocs().size() > 0,
192                                                 "Step documents list must not be empty.");
193                                 String docName = "document" + docIndex;
194                                 for (DocumentDTO doc : step.getDocs()) {
195                                         if (docName.equals(doc.getTitle())) {
196                                                 Assert.assertTrue(doc.getId() > 0,
197                                                                 "Document id must be positive integer.");
198                                                 Assert.assertEquals(doc.getTitle(), docName);
199                                                 Assert.assertNotNull(doc.getFiles(),
200                                                                 "Document files list must not be null.");
201                                                 Assert
202                                                                 .assertTrue(doc.getFiles().size() > 1,
203                                                                                 "Document must have more then 1 attached file.");
204
205                                                 for (FileDTO file : doc.getFiles()) {
206                                                         Assert.assertNotNull(file.getPath(),
207                                                                         "File path must not be null.");
208                                                         Assert.assertFalse(file.getPath().isEmpty(),
209                                                                         "File path must not be empty.");
210                                                         /*
211                                                          * <mappings> <document type="geometry"> <import format="brep"/> <!-- Result Shape --> </document> <document
212                                                          * type="model"> <import format="med"/> <!-- Result mesh without input parameters --> </document> <document
213                                                          * type="loads"> <import format="c3m"/> <!-- Input data created interactively --> </document> <document
214                                                          * type="results"> <import format="med"/> <!-- Calculation results source file --> </document> </mappings>
215                                                          */
216                                                         // Check state and processing instruction
217                                                         String fileFormat = file.getPath().substring(
218                                                                         file.getPath().lastIndexOf('.') + 1);
219                                                         /*
220                                                          * if (_projectSettings.doImport(dtype.getName(), fileFormat)) { Assert.assertTrue(file.isResult(), "The file
221                                                          * must be a result file."); } else { Assert.assertFalse(file.isResult(), "The file must be a source file."); }
222                                                          */if ((docIndex % 2) == 0) { // New
223                                                                 Assert.assertEquals(file.getState(), 'Y',
224                                                                                 "File state must be actual ('Y').");
225                                                                 if (_projectSettings.doImport(dtype.getName(),
226                                                                                 fileFormat)) {
227                                                                         Assert.assertEquals(file.getProcessing(),
228                                                                                         "file-import",
229                                                                                         "File must be imported.");
230                                                                 } else {
231                                                                         Assert.assertEquals(file.getProcessing(),
232                                                                                         "file-download",
233                                                                                         "File must be downloaded.");
234                                                                 }
235                                                         } else { // Outdated
236                                                                 Assert.assertEquals(file.getState(), 'O',
237                                                                                 "File state must be actual ('O').");
238                                                                 Assert
239                                                                                 .assertEquals(file.getProcessing(),
240                                                                                                 "file-download",
241                                                                                                 "Outdated document should not be imported but downloaded.");
242                                                         }
243                                                 }
244                                         }
245                                 }
246                                 docIndex++;
247                         }
248                 }
249
250                 // Call DAO's get method for a not existing id.
251                 try {
252                         steps = _scenarioService.getScenarioInfo(-1L);
253                         // getHibernateTemplate().flush();
254                         Assert
255                                         .fail("Getting an object with not existing id must be failed.");
256                 } catch (Exception e) {
257                         LOG.debug("Expected exception is thrown: "
258                                         + e.getClass().getSimpleName() + ": " + e.getMessage());
259                 }
260                 LOG.debug(">>>>> END testGetScenarioInfo()");
261         }
262
263         /**
264          * Test check-in scenario operation to be performed after SALOME session.<BR>
265          * <B>Description :</B> <BR>
266          * <i>Create a scenario and try to check-in it with some simulated SALOME results data.<BR>
267          * After check-in verify following points:
268          * <ul>
269          * <li>scenario is no more marked as checked out</li>
270          * <li>new document versions are created for checked in documents</li>
271          * <li>presentation of the previous version is removed</li>
272          * <li>uses relations are copied correctly</li>
273          * <li>files are moved correctly</li>
274          * <li>new documents are created for new data</li>
275          * <li>uses relations are created correctly</li>
276          * <li>files are moved correctly</li>
277          * </ul>
278          * </i><BR>
279          * <B>Action : </B><BR>
280          * <i>1. call the method for an existing scenario id.</i><BR>
281          * <i>2. call the method for a not existing scenario id.</i><BR>
282          * <B>Test data : </B><BR>
283          * <i>no input parameters</i><BR>
284          * <i>no input parameters</i><BR>
285          * 
286          * <B>Outcome results:</B><BR>
287          * <i>
288          * <ul>
289          * <li>New version of existing documents must be created and new documents must be imported for documents with zero id. Correct
290          * relations must be created.<BR>
291          * </li>
292          * <li>Exception is thrown<BR>
293          * </li>
294          * </ul>
295          * </i>
296          * 
297          * @throws InvalidPropertyException
298          *             if an invalid property is used when creating objects
299          * @throws MultiplyDefinedException
300          *             when trying to create an object with already existing id
301          * @throws MissedPropertyException
302          *             if a mandatory property is not defined for an object to be created
303          * @throws IOException
304          *             if scenario creation is failed
305          * @throws SQLException
306          *             if scenario creation is failed
307          * @throws NotApplicableException
308          *             if checkin failed
309          * @throws MismatchException
310          *             if checkin failed
311          */
312         @Test(groups = { "checkin", "sevice", "functional", "business" })
313         public void testCheckin() throws InvalidPropertyException,
314                         MissedPropertyException, MultiplyDefinedException, IOException,
315                         SQLException, MismatchException, NotApplicableException {
316                 LOG.debug(">>>>> BEGIN testCheckin()");
317                 _projectSettings.getAllSteps().clear(); // Clear config to be able to load it again
318                 _projectSettings.configure(ClassLoader
319                                 .getSystemResource("test/som.xml").getPath());
320                 long scenarioId = createScenario();
321                 Scenario aScen = _scenarioDAO.get(scenarioId);
322                 User user = aScen.getAuthor();
323                 long userId = user.getIndex();
324
325                 // ////////////////////////////////////////////////////////
326                 // Call checkin method for good prepared transient data.
327
328                 // Simulate checkout
329                 List<StepDTO> steps = _scenarioService.getScenarioInfo(scenarioId);
330                 _scenarioService.checkout(aScen, user);
331
332                 // Prepare test data for checkin
333                 // Checkin only two first steps (geom and mesh)
334                 List<StepDTO> stepsToCheckin = new ArrayList<StepDTO>();
335                 for (StepDTO step : steps) {
336                         // Prepare GEOM: checkin actual brep
337                         StepDTO stepToCheckin = createDocDTOForModule(null, "GEOM", "brep",
338                                         userId, step, stepsToCheckin);
339                         createDocDTOForModule(stepToCheckin, "SMESH", "med", userId, step,
340                                         stepsToCheckin);
341                 }
342                 // Do test checkin
343                 _scenarioService.checkin(scenarioId, userId, stepsToCheckin);
344
345                 // Check that scenario is no more marked as checked out
346                 aScen = _scenarioDAO.get(scenarioId);
347                 Assert.assertFalse(aScen.isCheckedout(),
348                                 "Scenario is still marked as checked out after checkin.");
349                 // Check that new document versions are created for checked in documents
350                 boolean caseFound = false;
351                 for (StepDTO step : stepsToCheckin) {
352                         for (DocumentDTO docDTO : step.getDocs()) {
353                                 if ((docDTO.getId() != 0) && (docDTO.getId() != null)) {
354                                         boolean found = false;
355                                         Document prevDoc = null;
356                                         Publication newPub = null;
357                                         for (Publication pub : aScen.getDocums()) {
358                                                 prevDoc = pub.value().getPreviousVersion();
359                                                 if (prevDoc != null) {
360                                                         found = (prevDoc.getIndex() == docDTO.getId());
361                                                         if (found) { // Found next published version of the checked in document
362                                                                 newPub = pub;
363                                                                 break;
364                                                         }
365                                                 }
366                                         }
367                                         Assert.assertTrue(found,
368                                                         "New version of the existing checked in document \""
369                                                                         + docDTO.getTitle() + "\" (id="
370                                                                         + docDTO.getId()
371                                                                         + ") is not found in the scenario.");
372                                         // Check that presentation of the previous version is removed
373                                         Assert.assertFalse(aScen.publishes(prevDoc));
374                                         checkFiles(docDTO, newPub);
375                                         // Check that uses relations are copied correctly
376
377                                         // 1. Get all uses relations of the previous document version
378                                         for (Relation rel : prevDoc
379                                                         .getRelations(UsesRelation.class)) {
380                                                 Document used = ((UsesRelation) rel).getTo();
381                                                 // 2.1. Get the latest version of the document published in this scenario
382                                                 Publication toBeUsed = aScen.getPublication(used);
383                                                 if (toBeUsed == null) {
384                                                         // Find the latest published version
385                                                         for (Publication lastPub : aScen.getDocums()) {
386                                                                 if ((lastPub.value().getPreviousVersion() != null)
387                                                                                 && (lastPub.value()
388                                                                                                 .getPreviousVersion()
389                                                                                                 .getIndex() == used.getIndex())) {
390                                                                         toBeUsed = lastPub;
391                                                                         break;
392                                                                 }
393                                                         }
394                                                 }
395                                                 if ((toBeUsed != null) && (!toBeUsed.isOutdated())) {
396                                                         // 2.2. For each used document check that its latest not outdated version
397                                                         // is used by the new checked in document version.
398                                                         checkUsesRelation(newPub, toBeUsed);
399                                                 }
400                                         }
401                                         // 1. Get all usedBy relations of the previous document version
402                                         for (Relation rel : prevDoc
403                                                         .getRelations(UsedByRelation.class)) {
404                                                 Document using = ((UsedByRelation) rel).getTo();
405                                                 // Check that not checked in dependent documents became outdated
406                                                 Publication usingPub = aScen.getPublication(using);
407                                                 if (usingPub != null) { // if the document using the old version is still published
408                                                         Assert.assertTrue(usingPub.isOutdated(),
409                                                                         "Not checked in dependent document "
410                                                                                         + using.getTitle() + " ("
411                                                                                         + using.getType().getName()
412                                                                                         + ") must become outdated.");
413                                                         caseFound = true;
414                                                 }
415                                         }
416
417                                 } else {
418                                         // Check that new documents are created for new data
419                                         boolean found = false;
420                                         Publication newPub = null;
421                                         for (Publication pub : aScen.getDocums()) {
422                                                 if (pub.value().getPreviousVersion() == null) {
423                                                         found = (docDTO.getTitle().equals(pub.value()
424                                                                         .getTitle()));
425                                                         if (found) { // Found next published version of the checked in document
426                                                                 newPub = pub;
427                                                                 break;
428                                                         }
429                                                 }
430                                         }
431                                         Assert.assertTrue(found,
432                                                         "New document is not created for checked in document \""
433                                                                         + docDTO.getTitle() + "\".");
434                                         // Check that uses relations are created correctly
435
436                                         // 1. Find the document type used by this document type
437                                         Set<DocumentType> usedTypes = newPub.value().getType()
438                                                         .getDefaultUses();
439                                         // 2. Find documents of used types in the current study step and previous study steps
440                                         for (Publication pub : aScen.getDocums()) {
441                                                 if ((pub.getStep().getNumber() <= step.getNumber())
442                                                                 && (!pub.isOutdated())
443                                                                 && usedTypes.contains(pub.value().getType())) {
444                                                         // 3. Check that there is uses relation to the found document
445                                                         // if it is not outdated.
446                                                         checkUsesRelation(newPub, pub);
447                                                 }
448                                         }
449
450                                         // Check that files are moved correctly
451                                         checkFiles(docDTO, newPub);
452                                 }
453                         }
454                 }
455                 Assert.assertTrue(caseFound,
456                                 "Not checked in dependent documents must become outdated.");
457
458                 // ///////////////////////////////////////////////////////////
459                 // Call checkin method for a not existing id.
460                 try {
461                         _scenarioService.checkin(-1, userId, stepsToCheckin);
462                         Assert
463                                         .fail("Check in for scenario with not existing id must be failed.");
464                 } catch (Exception e) {
465                         LOG.debug("Expected exception is thrown: "
466                                         + e.getClass().getSimpleName() + ": " + e.getMessage());
467                 }
468
469                 LOG.debug(">>>>> END testCheckin()");
470         }
471
472         /**
473          * Check if there is uses relation from the newPub to pub.
474          * 
475          * @param newPub
476          *            the new publication
477          * @param pub
478          *            the publication to be used
479          */
480         private void checkUsesRelation(final Publication newPub,
481                         final Publication pub) {
482                 boolean uses = false;
483                 boolean usesExist = false;
484                 for (Publication usesPub : newPub.getRelations(UsesRelation.class)) {
485                         usesExist = true;
486                         uses = (usesPub.equals(pub));
487                         if (uses) {
488                                 break;
489                         }
490                 }
491                 Assert.assertTrue(usesExist && uses, "The created document "
492                                 + newPub.value().getTitle() + "("
493                                 + newPub.value().getType().getName() + ")"
494                                 + " has no uses relation to the document "
495                                 + pub.value().getTitle() + "("
496                                 + pub.value().getType().getName() + ")");
497         }
498
499         /**
500          * Check that files are moved correctly.
501          * 
502          * @param docDTO
503          *            checked in document DTO
504          * @param newPub
505          *            the created document publication
506          */
507         private void checkFiles(final DocumentDTO docDTO, final Publication newPub) {
508                 // Check that original files are deleted
509                 for (int j = 0; j < docDTO.getFiles().size(); j++) {
510                         FileDTO fileDTO = docDTO.getFiles().get(j);
511                         Assert.assertFalse(new File(fileDTO.getPath()).exists(), "File"
512                                         + fileDTO.getPath()
513                                         + " was not removed from downloads directory.");
514                         String format = fileDTO.getPath().substring(
515                                         fileDTO.getPath().lastIndexOf('.') + 1);
516                 }
517                 // TODO:Check file by its internal content
518                 Assert.assertTrue(newPub.getSourceFile().exists(), "File "
519                                 + newPub.getSourceFile().asFile().getAbsolutePath()
520                                 + " for the document " + docDTO.getTitle()
521                                 + " was not created.");
522         }
523
524         /**
525          * Prepare a document with a file for check-in.
526          * 
527          * @param stepTo
528          *            step DTO with data for check-in
529          * @param module
530          *            SALOME module name
531          * @param format
532          *            file extension
533          * @param userId
534          *            download directory
535          * @param stepFrom
536          *            checked out stepDTO
537          * @param stepsToCheckin
538          *            DTO for check-in
539          * @throws IOException
540          *             if file creation failed
541          * @return step DTO with data prepared for check-in (stepTo or new if stepTo is null)
542          */
543         private StepDTO createDocDTOForModule(final StepDTO stepTo,
544                         final String module, final String format, final long userId,
545                         final StepDTO stepFrom, final List<StepDTO> stepsToCheckin)
546                         throws IOException {
547                 StepDTO stepToCheckin = stepTo;
548                 if (stepToCheckin == null) {
549                         stepToCheckin = new StepDTO();
550                 }
551                 if (module.equals(stepFrom.getModule())) {
552                         stepsToCheckin.add(stepToCheckin);
553                         stepToCheckin.setNumber(stepFrom.getNumber());
554                         for (DocumentDTO doc : stepFrom.getDocs()) {
555                                 if (doc.getFiles().get(0).getState() != 'O') {
556                                         DocumentDTO docToCheckin = stepToCheckin.addDoc(
557                                                         doc.getId(), doc.getTitle());
558                                         for (FileDTO file : doc.getFiles()) {
559                                                 if (file.getPath().endsWith(format)) {
560                                                         // Create a file in the download directory
561                                                         docToCheckin.addFile(createDownloadedFile(userId,
562                                                                         doc.getTitle() + "_result", format));
563                                                 }
564                                         }
565                                 }
566                         }
567                         // Prepare new data
568                         stepToCheckin.addDoc(0, "newdoc" + stepFrom.getNumber()).addFile(
569                                         createDownloadedFile(userId, "newdoc"
570                                                         + stepFrom.getNumber(), "brep"));
571                 }
572                 return stepToCheckin;
573         }
574
575         /**
576          * Create a file in the user's repository downloads directory.
577          * 
578          * @param userId
579          *            user id
580          * @param name
581          *            file name
582          * @param format
583          *            file extension
584          * @return created file DTO
585          * @throws IOException
586          *             if file creation failed
587          */
588         private FileDTO createDownloadedFile(final long userId, final String name,
589                         final String format) throws IOException {
590                 // Create a file in the download directory
591                 String filePath = getDownloadPath(userId) + name + "." + format;
592                 FileWriter fw = new FileWriter(filePath);
593                 fw.write("Simulation of " + name + "." + format
594                                 + " file for checkin at " + new Date());
595                 fw.close();
596                 return new FileDTO(filePath);
597         }
598
599         /**
600          * Get path to the user's downloads directory. The directory is created if it is not exist yet.
601          * 
602          * @param userId
603          *            user id
604          * @return absolute path to downloads directory followed by slash
605          */
606         private String getDownloadPath(final long userId) {
607                 // Prepare download directory
608                 File tmpDir = _repositoryService.getDownloadDirectory(userId);
609                 if (!tmpDir.exists()) {
610                         Assert.assertTrue(tmpDir.mkdir(),
611                                         "Can't create temporary directory: "
612                                                         + tmpDir.getAbsolutePath());
613                 }
614
615                 return tmpDir.getAbsolutePath() + "/";
616         }
617
618         /**
619          * Create a persistent scenario for tests.
620          * 
621          * @return a persistent scenario
622          * @throws InvalidPropertyException
623          *             if an invalid property is used when creating objects
624          * @throws MultiplyDefinedException
625          *             when trying to create an object with already existing id
626          * @throws MissedPropertyException
627          *             if a mandatory property is not defined for an object to be created
628          * @throws IOException
629          *             if document creation is failed
630          * @throws SQLException
631          *             if project settings loading is failed
632          */
633         private long createScenario() throws InvalidPropertyException,
634                         MissedPropertyException, MultiplyDefinedException, IOException,
635                         SQLException {
636                 // Create a scenario for tests
637                 HibernateTemplate ht = getHibernateTemplate();
638
639                 Database.getInstance().reset();
640                 _projectSettings.getAllSteps().clear(); // Clear config to be able to load it again
641                 // Load workflow customization
642                 try {
643                         _projectSettings.configure(ClassLoader.getSystemResource(
644                                         "test/som.xml").getPath());
645                 } catch (FileNotFoundException e) {
646                         Assert.fail("Can't find som.xml: ", e);
647                 }
648                 List<Step> steps = _projectSettings.getStepsOf(Scenario.class);
649                 Assert.assertTrue(steps.size() > 0, "No steps are created.");
650
651                 // Create a test user
652                 User.Properties uprop = new User.Properties();
653                 uprop.setUsername("TST_Username").setName("TST_SimanUnitTestsUser")
654                                 .setFirstName("TST_FirstName").setDisplayName("TST_test.user")
655                                 .addRole("TST_user").setMailAddress(
656                                                 "noreply@salome-platform.org");
657                 uprop.disableCheck();
658                 User anAuthor = new User(uprop);
659                 ht.saveOrUpdate(anAuthor);
660
661                 // Create a test study
662                 Study.Properties stprops = new Study.Properties().setReference(
663                                 "TST_SID_01").setTitle("TST_Study").setManager(anAuthor);
664                 Study aStudy = new Study(stprops);
665                 ht.saveOrUpdate(aStudy);
666
667                 // Create a test scenario
668                 Scenario.Properties sprops = new Scenario.Properties().setTitle(
669                                 "TST_Scenario").setManager(anAuthor).setOwnerStudy(aStudy);
670                 Scenario aScenario = new Scenario(sprops);
671                 aStudy.getScenariiList().add(aScenario);
672                 ht.saveOrUpdate(anAuthor);
673                 ht.saveOrUpdate(aStudy);
674                 ht.saveOrUpdate(aScenario);
675
676                 // Create documents for each scenario step
677                 Document.Properties dprop = new Document.Properties().setAuthor(
678                                 anAuthor).setDate(new Date());
679                 int i = 0;
680                 Publication usedPub = null;
681                 Map<Long, Long> usedMap = new HashMap<Long, Long>();
682                 for (Step step : steps) {
683                         LOG.debug("Create scenario step: " + i);
684
685                         org.splat.som.Step aScStep = new org.splat.som.Step(step, aScenario);
686                         List<DocumentType> dtypes = _documentTypeService
687                                         .selectTypesOf(step);
688                         for (DocumentType dtype : dtypes) {
689                                 // Create a document published in the scenario
690                                 // document<i>: document type[0] - first type used on the step
691                                 // <source-file>.brep
692                                 // <attached-file>.med
693                                 dprop.setName("document" + i++).setType(dtype);
694                                 if (step.getNumber() > 3) {
695                                         dprop.setFormat("med");
696                                 } else {
697                                         dprop.setFormat("brep");
698                                 }
699                                 Publication pub = createDoc(aScenario, aScStep, dprop, "med",
700                                                 false);
701                                 if (usedPub != null) {
702                                         pub.addDependency(usedPub);
703                                         ht.saveOrUpdate(pub.value());
704
705                                         usedMap.put(pub.getIndex(), usedPub.getIndex());
706                                 }
707                                 usedPub = pub;
708
709                                 // Create another document with outdated publication
710                                 dprop.setName("document" + i++).setType(dtype)
711                                                 .setFormat("brep");
712                                 createDoc(aScenario, aScStep, dprop, "med", true);
713
714                         }
715                         if (dtypes.size() <= 0) {
716                                 LOG.debug("No document types are found for scenario step " + i);
717                         }
718                 }
719
720                 // Check that the scenario and its documents have been created correctly.
721
722                 Assert.assertNotNull(ht.find("from Document"),
723                                 "No documents in the database.");
724                 Assert.assertTrue(ht.find("from Document").size() > 0,
725                                 "No documents in the database.");
726
727                 Assert.assertNotNull(ht.find("from Publication where owner="
728                                 + aScenario.getIndex()), "No publications in the database.");
729                 Assert.assertTrue(
730                                 ht.find("from Publication where owner=" + aScenario.getIndex())
731                                                 .size() > 0, "No publications in the database.");
732
733                 for (Publication p : (List<Publication>) ht
734                                 .find("from Publication where owner=" + aScenario.getIndex())) {
735                         LOG.debug("Publication found: [id=" + p.getIndex() + ", owner="
736                                         + p.getOwner().getIndex() + ", doc=" + p.value().getIndex()
737                                         + "]");
738                         Assert.assertEquals(p.getOwner().getIndex(), aScenario.getIndex(),
739                                         "The publication was not attached to the scenario.");
740                 }
741
742                 // Remove the scenario from the current hibernate session.
743                 ht.evict(aScenario);
744                 // Check that the scenario is created in the database.
745                 Scenario aScen = ht.load(Scenario.class, aScenario.getIndex());
746                 Assert.assertNotNull(aScen, "Scenario was not saved in the database.");
747                 Assert.assertTrue(aScen.getDocums().size() > 0,
748                                 "No publications in the scenario.");
749
750                 Assert.assertTrue(i > 0,
751                                 "More then one document must be in the database");
752
753                 // Check created uses relations
754                 Assert
755                                 .assertTrue(usedMap.size() > 0,
756                                                 "Uses relations must be created.");
757                 boolean foundAny = false;
758                 for (Long usingId : usedMap.keySet()) {
759                         for (Publication pub : aScen.getDocums()) {
760                                 if (pub.getIndex() == usingId) {
761                                         boolean found = false;
762                                         for (Publication used : aScen.getDocums()) {
763                                                 found = (used.getIndex() == usedMap.get(usingId));
764                                                 if (found) {
765                                                         break;
766                                                 }
767                                         }
768                                         Assert.assertTrue(found,
769                                                         "Uses relation was not created in the database.");
770                                         foundAny = foundAny || found;
771                                 }
772                         }
773                 }
774                 Assert.assertTrue(foundAny,
775                                 "No Uses relation was created in the database.");
776
777                 return aScenario.getIndex();
778         }
779
780         /**
781          * Create a document published in the scenario. <BR>
782          * document:<BR>
783          * document type[0] - first type used on the step <BR>
784          * &lt;source-file&gt;.brep <BR>
785          * &lt;attached-file&gt;.med
786          * 
787          * @param aScenario
788          *            the scenario to add the document to
789          * @param aScStep
790          *            scenario step where the document to be published
791          * @param dprop
792          *            document properties
793          * @param attachedFileExt
794          *            extension of the secon attached (exported) file
795          * @param isOutdated
796          *            outdated document flag
797          * @return the publication of the created document
798          * @throws IOException
799          * @throws MultiplyDefinedException
800          * @throws InvalidPropertyException
801          * @throws MissedPropertyException
802          */
803         private Publication createDoc(final Scenario aScenario,
804                         final org.splat.som.Step aScStep, final Properties dprop,
805                         final String attachedFileExt, final boolean isOutdated)
806                         throws MissedPropertyException, InvalidPropertyException,
807                         MultiplyDefinedException, IOException {
808                 // Create a document published in the scenario
809                 // document<i>: document type[0] - first type used on the step
810                 // <source-file>.brep
811                 // <attached-file>.med
812                 Publication pub = _stepService.createDocument(aScStep, dprop);
813                 Assert.assertNotNull(pub.getOwner(),
814                                 "The publication must be attached to the scenario.");
815                 Assert.assertEquals(pub.getOwner().getIndex(), aScenario.getIndex(),
816                                 "The publication was not attached to the scenario.");
817
818                 if (isOutdated) {
819                         pub.setIsnew('O');
820                 }
821                 aScenario.add(pub);
822                 HibernateTemplate ht = getHibernateTemplate();
823                 ht.saveOrUpdate(pub);
824
825                 // Attach a file
826                 ht.save(pub.value());
827                 ht.saveOrUpdate(_publicationService.attach(pub, attachedFileExt));
828
829                 return pub;
830         }
831 }