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