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