Salome HOME
0710f118397850642d4b5d67357577c276e421ae
[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.KnowledgeElementType;
28 import org.splat.dal.bo.som.Publication;
29 import org.splat.dal.bo.som.Scenario;
30 import org.splat.dal.bo.som.SimulationContext;
31 import org.splat.dal.bo.som.SimulationContextType;
32 import org.splat.dal.bo.som.Study;
33 import org.splat.dal.bo.som.UsedByRelation;
34 import org.splat.dal.bo.som.UsesRelation;
35 import org.splat.dal.bo.som.Document.Properties;
36 import org.splat.dal.dao.som.Database;
37 import org.splat.dal.dao.som.ScenarioDAO;
38 import org.splat.kernel.InvalidPropertyException;
39 import org.splat.kernel.MismatchException;
40 import org.splat.kernel.MissedPropertyException;
41 import org.splat.kernel.MultiplyDefinedException;
42 import org.splat.kernel.NotApplicableException;
43 import org.splat.log.AppLogger;
44 import org.splat.service.DocumentTypeService;
45 import org.splat.service.KnowledgeElementTypeService;
46 import org.splat.service.PublicationService;
47 import org.splat.service.ScenarioService;
48 import org.splat.service.SimulationContextService;
49 import org.splat.service.StepService;
50 import org.splat.service.dto.DocumentDTO;
51 import org.splat.service.dto.FileDTO;
52 import org.splat.service.dto.StepDTO;
53 import org.splat.service.technical.ProjectSettingsService;
54 import org.splat.service.technical.RepositoryService;
55 import org.splat.service.technical.ProjectSettingsService.Step;
56 import org.springframework.beans.factory.annotation.Autowired;
57 import org.springframework.beans.factory.annotation.Qualifier;
58 import org.springframework.orm.hibernate3.HibernateTemplate;
59 import org.testng.Assert;
60 import org.testng.annotations.Test;
61 import org.testng.reporters.Files;
62
63 import test.splat.common.BaseTest;
64
65 /**
66  * Test class for ScenarioService.
67  * 
68  * @author <a href="mailto:roman.kozlov@opencascade.com">Roman Kozlov (RKV)</a>
69  * 
70  */
71 public class TestScenarioService extends BaseTest {
72
73         /**
74          * Logger for the class.
75          */
76         private static final AppLogger LOG = AppLogger
77                         .getLogger(TestScenarioService.class);
78
79         /**
80          * The tested ScenarioService. Later injected by Spring.
81          */
82         @Autowired
83         @Qualifier("scenarioService")
84         private transient ScenarioService _scenarioService;
85
86         /**
87          * The RepositoryService. Later injected by Spring.
88          */
89         @Autowired
90         @Qualifier("repositoryService")
91         private transient RepositoryService _repositoryService;
92
93         /**
94          * The Scenario DAO. Later injected by Spring.
95          */
96         @Autowired
97         @Qualifier("scenarioDAO")
98         private transient ScenarioDAO _scenarioDAO;
99
100         /**
101          * The PublicationService. Later injected by Spring.
102          */
103         @Autowired
104         @Qualifier("publicationService")
105         private transient PublicationService _publicationService;
106
107         /**
108          * The StepService. Later injected by Spring.
109          */
110         @Autowired
111         @Qualifier("stepService")
112         private transient StepService _stepService;
113
114         /**
115          * The SimulationContextService. Later injected by Spring.
116          */
117         @Autowired
118         @Qualifier("simulationContextService")
119         private transient SimulationContextService _simulationContextService;
120
121         /**
122          * The ProjectSettingsService. Later injected by Spring.
123          */
124         @Autowired
125         @Qualifier("projectSettings")
126         private transient ProjectSettingsService _projectSettings;
127
128         /**
129          * The DocumentTypeService. Later injected by Spring.
130          */
131         @Autowired
132         @Qualifier("documentTypeService")
133         private transient DocumentTypeService _documentTypeService;
134
135         /**
136          * The KnowledgeElementTypeService. Later injected by Spring.
137          */
138         @Autowired
139         @Qualifier("knowledgeElementTypeService")
140         private transient KnowledgeElementTypeService _knowledgeElementTypeService;
141
142         /**
143          * Test of getting a scenario content for building siman-salome.conf.<BR>
144          * <B>Description :</B> <BR>
145          * <i>Create a scenario and try to get an info for it.</i><BR>
146          * <B>Action : </B><BR>
147          * <i>1. call the method for an existing scenario id.</i><BR>
148          * <i>2. call the method for a not existing scenario id.</i><BR>
149          * <B>Test data : </B><BR>
150          * <i>no input parameters</i><BR>
151          * <i>no input parameters</i><BR>
152          * 
153          * <B>Outcome results:</B><BR>
154          * <i>
155          * <ul>
156          * <li>result DTO must contain list of all documents and files<BR>
157          * </li>
158          * <li>Exception is thrown<BR>
159          * </li>
160          * </ul>
161          * </i>
162          * 
163          * @throws InvalidPropertyException
164          *             if an invalid property is used when creating objects
165          * @throws MultiplyDefinedException
166          *             when trying to create an object with already existing id
167          * @throws MissedPropertyException
168          *             if a mandatory property is not defined for an object to be created
169          * @throws IOException
170          *             if scenario creation is failed
171          * @throws SQLException
172          *             if scenario creation is failed
173          */
174         @Test(groups = { "checkout", "sevice", "functional", "business" })
175         public void testGetScenarioInfo() throws InvalidPropertyException,
176                         MissedPropertyException, MultiplyDefinedException, IOException,
177                         SQLException {
178                 LOG.debug(">>>>> BEGIN testGetScenarioInfo()");
179                 startNestedTransaction();
180
181                 long scenarioId = createScenario();
182                 // Call DAO's create method for a good transient knowledge element.
183                 List<StepDTO> steps = _scenarioService.getScenarioInfo(scenarioId);
184                 Assert.assertNotNull(steps, "List of steps must not be null.");
185                 Assert.assertTrue(steps.size() > 0, "No steps are read.");
186
187                 List<Step> projSteps = _projectSettings.getStepsOf(Scenario.class);
188                 Assert.assertEquals(steps.size(), projSteps.size(),
189                                 "Not all steps are listed.");
190                 int docIndex = 0;
191                 for (StepDTO step : steps) {
192                         LOG.debug("check the step " + step.getNumber() + ":\n" + step);
193                         Assert.assertNotNull(step, "Step DTO must not be null.");
194                         Assert.assertNotNull(step.getKey(), "Step name must not be null.");
195                         Assert.assertFalse(step.getKey().isEmpty(),
196                                         "Step name must not empty.");
197                         Assert.assertTrue(step.getNumber() > 0,
198                                         "Step number must be positive integer.");
199                         Assert.assertNotNull(step.getDocs(),
200                                         "Step documents list must not be null.");
201
202                         Step aProjStep = null;
203                         for (Step projStep : projSteps) {
204                                 if (projStep.getNumber() == step.getNumber()) {
205                                         aProjStep = projStep;
206                                         break;
207                                 }
208                         }
209
210                         List<DocumentType> dtypes = _documentTypeService
211                                         .selectTypesOf(aProjStep);
212                         for (DocumentType dtype : dtypes) {
213                                 Assert.assertTrue(step.getDocs().size() > 0,
214                                                 "Step documents list must not be empty.");
215                                 String docName = "document" + docIndex;
216                                 for (DocumentDTO doc : step.getDocs()) {
217                                         if (docName.equals(doc.getTitle())) {
218                                                 Assert.assertTrue(doc.getId() > 0,
219                                                                 "Document id must be positive integer.");
220                                                 Assert.assertEquals(doc.getTitle(), docName);
221                                                 Assert.assertNotNull(doc.getFiles(),
222                                                                 "Document files list must not be null.");
223                                                 Assert
224                                                                 .assertTrue(doc.getFiles().size() > 1,
225                                                                                 "Document must have more then 1 attached file.");
226
227                                                 for (FileDTO file : doc.getFiles()) {
228                                                         Assert.assertNotNull(file.getPath(),
229                                                                         "File path must not be null.");
230                                                         Assert.assertFalse(file.getPath().isEmpty(),
231                                                                         "File path must not be empty.");
232                                                         /*
233                                                          * <mappings> <document type="geometry"> <import format="brep"/> <!-- Result Shape --> </document> <document
234                                                          * type="model"> <import format="med"/> <!-- Result mesh without input parameters --> </document> <document
235                                                          * type="loads"> <import format="c3m"/> <!-- Input data created interactively --> </document> <document
236                                                          * type="results"> <import format="med"/> <!-- Calculation results source file --> </document> </mappings>
237                                                          */
238                                                         // Check state and processing instruction
239                                                         String fileFormat = file.getPath().substring(
240                                                                         file.getPath().lastIndexOf('.') + 1);
241                                                         /*
242                                                          * if (_projectSettings.doImport(dtype.getName(), fileFormat)) { Assert.assertTrue(file.isResult(), "The file
243                                                          * must be a result file."); } else { Assert.assertFalse(file.isResult(), "The file must be a source file."); }
244                                                          */if ((docIndex % 2) == 0) { // New
245                                                                 Assert.assertEquals(file.getState(), 'Y',
246                                                                                 "File state must be actual ('Y').");
247                                                                 if (_projectSettings.doImport(dtype.getName(),
248                                                                                 fileFormat)) {
249                                                                         Assert.assertEquals(file.getProcessing(),
250                                                                                         "file-import",
251                                                                                         "File must be imported.");
252                                                                 } else {
253                                                                         Assert.assertEquals(file.getProcessing(),
254                                                                                         "file-download",
255                                                                                         "File must be downloaded.");
256                                                                 }
257                                                         } else { // Outdated
258                                                                 Assert.assertEquals(file.getState(), 'O',
259                                                                                 "File state must be outdated ('O').");
260                                                                 Assert
261                                                                                 .assertEquals(file.getProcessing(),
262                                                                                                 "file-download",
263                                                                                                 "Outdated document should not be imported but downloaded.");
264                                                         }
265                                                 }
266                                         }
267                                 }
268                                 docIndex++;
269                         }
270                 }
271
272                 // Call DAO's get method for a not existing id.
273                 try {
274                         steps = _scenarioService.getScenarioInfo(-1L);
275                         // getHibernateTemplate().flush();
276                         Assert
277                                         .fail("Getting an object with not existing id must be failed.");
278                 } catch (Exception e) {
279                         LOG.debug("Expected exception is thrown: "
280                                         + e.getClass().getSimpleName() + ": " + e.getMessage());
281                 }
282                 rollbackNestedTransaction();
283                 LOG.debug(">>>>> END testGetScenarioInfo()");
284         }
285
286         /**
287          * Test check-in scenario operation to be performed after SALOME session.<BR>
288          * <B>Description :</B> <BR>
289          * <i>Create a scenario and try to check-in it with some simulated SALOME results data.<BR>
290          * After check-in verify following points:
291          * <ul>
292          * <li>scenario is no more marked as checked out</li>
293          * <li>new document versions are created for checked in documents</li>
294          * <li>presentation of the previous version is removed</li>
295          * <li>uses relations are copied correctly</li>
296          * <li>files are moved correctly</li>
297          * <li>formats of files are new if they are according to the document's type on the study step</li>
298          * <li>new documents are created for new data</li>
299          * <li>new documents have correctly generated names</li>
300          * <li>uses relations are created correctly</li>
301          * <li>files are moved correctly</li>
302          * </ul>
303          * </i><BR>
304          * <B>Action : </B><BR>
305          * <i>1. call the method for an existing scenario id.</i><BR>
306          * <i>2. call the method for a not existing scenario id.</i><BR>
307          * <B>Test data : </B><BR>
308          * <i>no input parameters</i><BR>
309          * <i>no input parameters</i><BR>
310          * 
311          * <B>Outcome results:</B><BR>
312          * <i>
313          * <ul>
314          * <li>New version of existing documents must be created and new documents must be imported for documents with zero id. Correct
315          * relations must be created.<BR>
316          * </li>
317          * <li>Exception is thrown<BR>
318          * </li>
319          * </ul>
320          * </i>
321          * 
322          * @throws InvalidPropertyException
323          *             if an invalid property is used when creating objects
324          * @throws MultiplyDefinedException
325          *             when trying to create an object with already existing id
326          * @throws MissedPropertyException
327          *             if a mandatory property is not defined for an object to be created
328          * @throws IOException
329          *             if scenario creation is failed
330          * @throws SQLException
331          *             if scenario creation is failed
332          * @throws NotApplicableException
333          *             if checkin failed
334          * @throws MismatchException
335          *             if checkin failed
336          */
337         @Test(groups = { "checkin", "sevice", "functional", "business" })
338         public void testCheckin() throws InvalidPropertyException,
339                         MissedPropertyException, MultiplyDefinedException, IOException,
340                         SQLException, MismatchException, NotApplicableException {
341                 LOG.debug(">>>>> BEGIN testCheckin()");
342                 startNestedTransaction();
343
344                 _projectSettings.getAllSteps().clear(); // Clear config to be able to load it again
345                 _projectSettings.configure(ClassLoader
346                                 .getSystemResource("test/som.xml").getPath());
347                 getHibernateTemplate().flush();
348                 long scenarioId = createScenario();
349                 Scenario aScen = _scenarioDAO.get(scenarioId);
350                 User user = aScen.getAuthor();
351                 long userId = user.getIndex();
352
353                 
354                 // ////////////////////////////////////////////////////////
355                 // Call checkin method for empty list of modules.
356
357                 // Simulate checkout
358                 List<StepDTO> steps = _scenarioService.getScenarioInfo(scenarioId);
359                 _scenarioService.checkout(aScen, user);
360                 _scenarioDAO.flush();
361                 // Check that scenario is no more marked as checked out
362                 aScen = _scenarioDAO.get(scenarioId);
363                 Assert.assertTrue(aScen.isCheckedout(),
364                                 "Scenario is not marked as checked out after checkout.");
365
366                 // Prepare test data for checkin
367                 // Checkin only two first steps (geom and mesh)
368                 List<StepDTO> stepsToCheckin = new ArrayList<StepDTO>();
369                 // Do test checkin
370                 _scenarioService.checkin(scenarioId, userId, stepsToCheckin);
371
372                 _scenarioDAO.flush();
373                 // Check that scenario is no more marked as checked out
374                 aScen = _scenarioDAO.get(scenarioId);
375                 Assert.assertFalse(aScen.isCheckedout(),
376                                 "Scenario is still marked as checked out after checkin.");
377                 
378                 
379                 
380                 // ////////////////////////////////////////////////////////
381                 // Call checkin method for good prepared transient data.
382
383                 // Simulate checkout
384                 steps = _scenarioService.getScenarioInfo(scenarioId);
385                 _scenarioService.checkout(aScen, user);
386
387                 // Prepare test data for checkin
388                 // Checkin only two first steps (geom and mesh)
389                 for (StepDTO step : steps) {
390                         // Prepare GEOM: checkin actual brep
391                         StepDTO stepToCheckin = createDocDTOForModule(null, "GEOM", "brep",
392                                         userId, step, stepsToCheckin);
393                         createDocDTOForModule(stepToCheckin, "SMESH", "med", userId, step,
394                                         stepsToCheckin);
395                 }
396                 // Do test checkin
397                 _scenarioService.checkin(scenarioId, userId, stepsToCheckin);
398
399                 _scenarioDAO.flush();
400                 // Check that scenario is no more marked as checked out
401                 aScen = _scenarioDAO.get(scenarioId);
402                 Assert.assertFalse(aScen.isCheckedout(),
403                                 "Scenario is still marked as checked out after checkin.");
404                 // Check that new document versions are created for checked in documents
405                 boolean caseFound = false;
406                 for (StepDTO step : stepsToCheckin) {
407                         for (DocumentDTO docDTO : step.getDocs()) {
408                                 if ((docDTO.getId() != 0) && (docDTO.getId() != null)) {
409                                         boolean found = false;
410                                         Document prevDoc = null;
411                                         Document curDoc = null;
412                                         Publication newPub = null;
413                                         for (Publication pub : aScen.getDocums()) {
414                                                 prevDoc = pub.value().getPreviousVersion();
415                                                 if (prevDoc != null) {
416                                                         found = (prevDoc.getIndex() == docDTO.getId());
417                                                         if (found) { // Found next published version of the checked in document
418                                                                 newPub = pub;
419                                                                 break;
420                                                         }
421                                                 }
422                                                 if (pub.value().getIndex() == docDTO.getId()) {
423                                                         // Document version was not changed, old document is still published
424                                                         curDoc = pub.value();
425                                                         break;
426                                                 }
427                                         }
428                                         Assert.assertTrue(found || (curDoc != null),
429                                                         "New version or new attached file of the existing checked in document \""
430                                                                         + docDTO.getTitle() + "\" (id="
431                                                                         + docDTO.getId()
432                                                                         + ") is not found in the scenario.");
433                                         // If previous version is found then the format must be the same
434                                         String newFormat = docDTO.getFiles().get(0).getPath()
435                                                         .substring(
436                                                                         docDTO.getFiles().get(0).getPath()
437                                                                                         .lastIndexOf('.') + 1);
438                                         if (found) {
439                                                 Assert.assertEquals(prevDoc.getFormat(), newFormat,
440                                                                 "Formats of versions must be same");
441                                                 Assert.assertFalse(aScen.publishes(prevDoc));
442                                                 // Check that presentation of the previous version is removed
443                                                 checkFiles(docDTO, newPub);
444                                                 
445                                                 // Formats of files are new if they are according to the document's type on the study step
446                                                 if ("py".equals(prevDoc.getFormat())
447                                                                 && "geometry".equals(prevDoc.getType().getName())) {
448                                                         Assert.assertEquals(newPub.value().getFormat(), "brep");
449                                                         Assert.assertEquals(newPub.getSourceFile().getFormat(),
450                                                                         "brep");
451                                                         Assert.assertEquals(newPub.getSourceFile()
452                                                                         .getRelativePath().substring(
453                                                                                         newPub.getSourceFile()
454                                                                                                         .getRelativePath().lastIndexOf(
455                                                                                                                         '.') + 1), "brep");
456                                                 }
457
458                                                 // Check that uses relations are copied correctly
459
460                                                 // 1. Get all uses relations of the previous document version
461                                                 for (Relation rel : prevDoc
462                                                                 .getRelations(UsesRelation.class)) {
463                                                         Document used = ((UsesRelation) rel).getTo();
464                                                         // 2.1. Get the latest version of the document published in this scenario
465                                                         Publication toBeUsed = aScen.getPublication(used);
466                                                         if (toBeUsed == null) {
467                                                                 // Find the latest published version
468                                                                 for (Publication lastPub : aScen.getDocums()) {
469                                                                         if ((lastPub.value().getPreviousVersion() != null)
470                                                                                         && (lastPub.value()
471                                                                                                         .getPreviousVersion()
472                                                                                                         .getIndex() == used.getIndex())) {
473                                                                                 toBeUsed = lastPub;
474                                                                                 break;
475                                                                         }
476                                                                 }
477                                                         }
478                                                         if ((toBeUsed != null) && (!toBeUsed.isOutdated())) {
479                                                                 // 2.2. For each used document check that its latest not outdated version
480                                                                 // is used by the new checked in document version.
481                                                                 checkUsesRelation(newPub, toBeUsed);
482                                                         }
483                                                 }
484                                                 // 1. Get all usedBy relations of the previous document version
485                                                 for (Relation rel : prevDoc
486                                                                 .getRelations(UsedByRelation.class)) {
487                                                         Document using = ((UsedByRelation) rel).getTo();
488                                                         // Check that not checked in dependent documents became outdated
489                                                         Publication usingPub = aScen.getPublication(using);
490                                                         if (usingPub != null) { // if the document using the old version is still published
491                                                                 Assert.assertTrue(usingPub.isOutdated(),
492                                                                                 "Not checked in dependent document "
493                                                                                                 + using.getTitle() + " ("
494                                                                                                 + using.getType().getName()
495                                                                                                 + ") must become outdated.");
496                                                                 caseFound = true;
497                                                         }
498                                                 }
499                                         } else {
500                                                 // Otherwise the new file format must differ from the previous one
501                                                 // and the new file must be attached to the same document
502                                                 org.splat.dal.bo.som.File attFile = curDoc
503                                                                 .getAttachedFile(newFormat);
504                                                 Assert.assertNotNull(attFile, "File "
505                                                                 + docDTO.getFiles().get(0).getPath()
506                                                                 + " must be attached to the document "
507                                                                 + docDTO.getTitle() + "#" + docDTO.getId());
508                                                 Assert.assertTrue(attFile.asFile().exists(), "File "
509                                                                 + docDTO.getFiles().get(0).getPath()
510                                                                 + " attached to the document "
511                                                                 + docDTO.getTitle() + "#" + docDTO.getId() + " doesn't exist");
512                                         }
513
514
515                                 } else {
516                                         // Check that new documents are created for new data
517                                         boolean found = false;
518                                         Publication newPub = null;
519                                         for (Publication pub : aScen.getDocums()) {
520                                                 if (pub.value().getPreviousVersion() == null) {
521                                                         found = (pub.value().getTitle().startsWith(pub
522                                                                         .value().getType().getName()));
523                                                         if (found) { // Found next published version of the checked in document
524                                                                 String fcontent = Files.readFile(pub
525                                                                                 .getSourceFile().asFile());
526                                                                 found = fcontent.contains(docDTO.getTitle());
527                                                                 if (found) {
528                                                                         LOG
529                                                                                         .debug("Found new document with generated title: "
530                                                                                                         + pub.value().getTitle());
531                                                                         newPub = pub;
532                                                                         break;
533                                                                 }
534                                                         }
535                                                 }
536                                         }
537                                         Assert.assertTrue(found,
538                                                         "New document is not created for checked in document \""
539                                                                         + docDTO.getTitle() + "\".");
540
541                                         // Check that uses relations are created correctly
542                                         Assert.assertTrue(newPub.value().getTitle().startsWith(
543                                                         newPub.value().getType().getName() + "_"),
544                                                         "Document title newPub.value().getTitle() must start with "
545                                                                         + newPub.value().getType().getName() + "_");
546
547                                         // 1. Find the document type used by this document type
548                                         Set<DocumentType> usedTypes = newPub.value().getType()
549                                                         .getDefaultUses();
550                                         // 2. Find documents of used types in the current study step and previous study steps
551                                         for (Publication pub : aScen.getDocums()) {
552                                                 if ((pub.getStep().getNumber() <= step.getNumber())
553                                                                 && (!pub.isOutdated())
554                                                                 && usedTypes.contains(pub.value().getType())) {
555                                                         // 3. Check that there is uses relation to the found document
556                                                         // if it is not outdated.
557                                                         checkUsesRelation(newPub, pub);
558                                                 }
559                                         }
560
561                                         // Check that files are moved correctly
562                                         checkFiles(docDTO, newPub);
563                                 }
564                         }
565                 }
566                 Assert.assertTrue(caseFound,
567                                 "Not checked in dependent documents must become outdated.");
568
569                 // ///////////////////////////////////////////////////////////
570                 // Call checkin method for a not existing id.
571                 try {
572                         _scenarioService.checkin(-1, userId, stepsToCheckin);
573                         Assert
574                                         .fail("Check in for scenario with not existing id must be failed.");
575                 } catch (Exception e) {
576                         LOG.debug("Expected exception is thrown: "
577                                         + e.getClass().getSimpleName() + ": " + e.getMessage());
578                 }
579
580                 // Test checkin with empty list of steps
581                 stepsToCheckin.clear();
582                 _scenarioService.checkin(scenarioId, userId, stepsToCheckin);
583
584                 rollbackNestedTransaction();
585                 LOG.debug(">>>>> END testCheckin()");
586         }
587
588         /**
589          * Check if there is uses relation from the newPub to pub.
590          * 
591          * @param newPub
592          *            the new publication
593          * @param pub
594          *            the publication to be used
595          */
596         private void checkUsesRelation(final Publication newPub,
597                         final Publication pub) {
598                 boolean uses = false;
599                 boolean usesExist = false;
600                 for (Publication usesPub : newPub.getRelations(UsesRelation.class)) {
601                         usesExist = true;
602                         uses = (usesPub.equals(pub));
603                         if (uses) {
604                                 break;
605                         }
606                 }
607                 Assert.assertTrue(usesExist && uses, "The created document "
608                                 + newPub.value().getTitle() + "("
609                                 + newPub.value().getType().getName() + ")"
610                                 + " has no uses relation to the document "
611                                 + pub.value().getTitle() + "("
612                                 + pub.value().getType().getName() + ")");
613         }
614
615         /**
616          * Check that files are moved correctly.
617          * 
618          * @param docDTO
619          *            checked in document DTO
620          * @param newPub
621          *            the created document publication
622          */
623         private void checkFiles(final DocumentDTO docDTO, final Publication newPub) {
624                 // Check that original files are deleted
625                 for (int j = 0; j < docDTO.getFiles().size(); j++) {
626                         FileDTO fileDTO = docDTO.getFiles().get(j);
627                         Assert.assertFalse(new File(fileDTO.getPath()).exists(), "File"
628                                         + fileDTO.getPath()
629                                         + " was not removed from downloads directory.");
630                         String format = fileDTO.getPath().substring(
631                                         fileDTO.getPath().lastIndexOf('.') + 1);
632                 }
633                 // TODO: Check file by its internal content
634                 Assert.assertTrue(newPub.getSourceFile().exists(), "File "
635                                 + newPub.getSourceFile().asFile().getAbsolutePath()
636                                 + " for the document " + docDTO.getTitle()
637                                 + " was not created.");
638         }
639
640         /**
641          * Prepare a document with a file for check-in.
642          * 
643          * @param stepTo
644          *            step DTO with data for check-in
645          * @param module
646          *            SALOME module name
647          * @param format
648          *            file extension
649          * @param userId
650          *            download directory
651          * @param stepFrom
652          *            checked out stepDTO
653          * @param stepsToCheckin
654          *            DTO for check-in
655          * @throws IOException
656          *             if file creation failed
657          * @return step DTO with data prepared for check-in (stepTo or new if stepTo is null)
658          */
659         private StepDTO createDocDTOForModule(final StepDTO stepTo,
660                         final String module, final String format, final long userId,
661                         final StepDTO stepFrom, final List<StepDTO> stepsToCheckin)
662                         throws IOException {
663                 StepDTO stepToCheckin = stepTo;
664                 if (stepToCheckin == null) {
665                         stepToCheckin = new StepDTO();
666                 }
667                 if (module.equals(stepFrom.getModule())) {
668                         stepsToCheckin.add(stepToCheckin);
669                         stepToCheckin.setNumber(stepFrom.getNumber());
670                         for (DocumentDTO doc : stepFrom.getDocs()) {
671                                 if (doc.getFiles().get(0).getState() != 'O') {
672                                         DocumentDTO docToCheckin = stepToCheckin.addDoc(
673                                                         doc.getId(), doc.getTitle());
674                                         for (FileDTO file : doc.getFiles()) {
675                                                 if (file.getPath().endsWith(format)
676                                                                 || (file.getPath().endsWith("py") && format
677                                                                                 .equals("brep"))) {
678                                                         // Create a file in the download directory
679                                                         docToCheckin.addFile(createDownloadedFile(userId,
680                                                                         doc.getTitle() + "_result", format));
681                                                 }
682                                         }
683                                 }
684                         }
685                         // Prepare new data
686                         stepToCheckin.addDoc(0, "newdoc" + stepFrom.getNumber()).addFile(
687                                         createDownloadedFile(userId, "newdoc"
688                                                         + stepFrom.getNumber(), "brep"));
689                 }
690                 return stepToCheckin;
691         }
692
693         /**
694          * Create a file in the user's repository downloads directory.
695          * 
696          * @param userId
697          *            user id
698          * @param name
699          *            file name
700          * @param format
701          *            file extension
702          * @return created file DTO
703          * @throws IOException
704          *             if file creation failed
705          */
706         private FileDTO createDownloadedFile(final long userId, final String name,
707                         final String format) throws IOException {
708                 // Create a file in the download directory
709                 return createDownloadedFile(userId, name + "." + format);
710         }
711
712         /**
713          * Create a file in the user's repository downloads directory.
714          * 
715          * @param userId
716          *            user id
717          * @param fname
718          *            file name
719          * @return created file DTO
720          * @throws IOException
721          *             if file creation failed
722          */
723         private FileDTO createDownloadedFile(final long userId, final String fname)
724                         throws IOException {
725                 // Create a file in the download directory
726                 String filePath = getDownloadPath(userId) + fname;
727                 FileWriter fw = new FileWriter(filePath);
728                 fw.write("Simulation of " + fname + " file for checkin at "
729                                 + new Date());
730                 fw.close();
731                 return new FileDTO(filePath);
732         }
733
734         /**
735          * Get path to the user's downloads directory. The directory is created if it is not exist yet.
736          * 
737          * @param userId
738          *            user id
739          * @return absolute path to downloads directory followed by slash
740          */
741         private String getDownloadPath(final long userId) {
742                 // Prepare download directory
743                 File tmpDir = _repositoryService.getDownloadDirectory(userId);
744                 if (!tmpDir.exists()) {
745                         Assert.assertTrue(tmpDir.mkdir(),
746                                         "Can't create temporary directory: "
747                                                         + tmpDir.getAbsolutePath());
748                 }
749
750                 return tmpDir.getAbsolutePath() + "/";
751         }
752
753         /**
754          * Create a persistent scenario for tests.
755          * 
756          * @return a persistent scenario
757          * @throws InvalidPropertyException
758          *             if an invalid property is used when creating objects
759          * @throws MultiplyDefinedException
760          *             when trying to create an object with already existing id
761          * @throws MissedPropertyException
762          *             if a mandatory property is not defined for an object to be created
763          * @throws IOException
764          *             if document creation is failed
765          * @throws SQLException
766          *             if project settings loading is failed
767          */
768         private long createScenario() throws InvalidPropertyException,
769                         MissedPropertyException, MultiplyDefinedException, IOException,
770                         SQLException {
771                 // Create a scenario for tests
772                 HibernateTemplate ht = getHibernateTemplate();
773
774                 Database.getInstance().reset();
775                 _projectSettings.getAllSteps().clear(); // Clear config to be able to load it again
776                 // Load workflow customization
777                 try {
778                         _projectSettings.configure(ClassLoader.getSystemResource(
779                                         "test/som.xml").getPath());
780                 } catch (FileNotFoundException e) {
781                         Assert.fail("Can't find som.xml: ", e);
782                 }
783                 List<Step> steps = _projectSettings.getStepsOf(Scenario.class);
784                 Assert.assertTrue(steps.size() > 0, "No steps are created.");
785
786                 // Create a test user
787                 User.Properties uprop = new User.Properties();
788                 uprop.setUsername("TST_Username").setName("TST_SimanUnitTestsUser")
789                                 .setFirstName("TST_FirstName").setDisplayName("TST_test.user")
790                                 .addRole("TST_user").setMailAddress(
791                                                 "noreply@salome-platform.org");
792                 uprop.disableCheck();
793                 User anAuthor = new User(uprop);
794                 ht.saveOrUpdate(anAuthor);
795
796                 // Create a test study
797                 Study.Properties stprops = new Study.Properties().setReference(
798                                 "TST_SID_01").setTitle("TST_Study").setManager(anAuthor);
799                 Study aStudy = new Study(stprops);
800                 ht.saveOrUpdate(aStudy);
801
802                 // Create a test scenario
803                 Scenario.Properties sprops = new Scenario.Properties().setTitle(
804                                 "TST_Scenario").setManager(anAuthor).setOwnerStudy(aStudy);
805                 Scenario aScenario = new Scenario(sprops);
806                 aStudy.getScenariiList().add(aScenario);
807                 ht.saveOrUpdate(anAuthor);
808                 ht.saveOrUpdate(aStudy);
809                 ht.saveOrUpdate(aScenario);
810
811                 // Create documents for each scenario step
812                 Document.Properties dprop = new Document.Properties().setAuthor(
813                                 anAuthor).setDate(new Date());
814                 int i = 0;
815                 Publication usedPub = null;
816                 Map<Long, Long> usedMap = new HashMap<Long, Long>();
817                 for (Step step : steps) {
818                         LOG.debug("Create scenario step: " + i);
819
820                         org.splat.som.Step aScStep = new org.splat.som.Step(step, aScenario);
821                         List<DocumentType> dtypes = _documentTypeService
822                                         .selectTypesOf(step);
823                         for (DocumentType dtype : dtypes) {
824                                 // Create a document published in the scenario
825                                 // document<i>: document type[0] - first type used on the step
826                                 // <source-file>.brep
827                                 // <attached-file>.med
828                                 dprop.setName("document" + i++).setType(dtype);
829                                 if (step.getNumber() > 3) {
830                                         dprop.setFormat("med");
831                                 } else {
832                                         dprop.setFormat("py");
833                                 }
834                                 dprop.setLocalPath(dprop.getName() + "." + dprop.getFormat());
835                                 Publication pub = createDoc(aScenario, aScStep, dprop, "med",
836                                                 false);
837                                 if (usedPub != null) {
838                                         pub.addDependency(usedPub);
839                                         ht.saveOrUpdate(pub.value());
840
841                                         usedMap.put(pub.getIndex(), usedPub.getIndex());
842                                 }
843                                 usedPub = pub;
844
845                                 // Create another document with outdated publication
846                                 dprop.setName("document" + i++).setType(dtype).setFormat("py");
847                                 dprop.setLocalPath(dprop.getName() + "." + dprop.getFormat());
848                                 createDoc(aScenario, aScStep, dprop, "med", true);
849
850                         }
851                         if (dtypes.size() <= 0) {
852                                 LOG.debug("No document types are found for scenario step " + i);
853                         }
854                 }
855
856                 // Check that the scenario and its documents have been created correctly.
857
858                 Assert.assertNotNull(ht.find("from Document"),
859                                 "No documents in the database.");
860                 Assert.assertTrue(ht.find("from Document").size() > 0,
861                                 "No documents in the database.");
862
863                 Assert.assertNotNull(ht.find("from Publication where owner="
864                                 + aScenario.getIndex()), "No publications in the database.");
865                 Assert.assertTrue(
866                                 ht.find("from Publication where owner=" + aScenario.getIndex())
867                                                 .size() > 0, "No publications in the database.");
868
869                 for (Publication p : (List<Publication>) ht
870                                 .find("from Publication where owner=" + aScenario.getIndex())) {
871                         LOG.debug("Publication found: [id=" + p.getIndex() + ", owner="
872                                         + p.getOwner().getIndex() + ", doc=" + p.value().getIndex()
873                                         + "]");
874                         Assert.assertEquals(p.getOwner().getIndex(), aScenario.getIndex(),
875                                         "The publication was not attached to the scenario.");
876                 }
877
878                 // Remove the scenario from the current hibernate session.
879                 ht.evict(aScenario);
880                 // Check that the scenario is created in the database.
881                 Scenario aScen = ht.load(Scenario.class, aScenario.getIndex());
882                 Assert.assertNotNull(aScen, "Scenario was not saved in the database.");
883                 Assert.assertTrue(aScen.getDocums().size() > 0,
884                                 "No publications in the scenario.");
885
886                 Assert.assertTrue(i > 0,
887                                 "More then one document must be in the database");
888
889                 // Check created uses relations
890                 Assert
891                                 .assertTrue(usedMap.size() > 0,
892                                                 "Uses relations must be created.");
893                 boolean foundAny = false;
894                 for (Long usingId : usedMap.keySet()) {
895                         for (Publication pub : aScen.getDocums()) {
896                                 if (pub.getIndex() == usingId) {
897                                         boolean found = false;
898                                         for (Publication used : aScen.getDocums()) {
899                                                 found = (used.getIndex() == usedMap.get(usingId));
900                                                 if (found) {
901                                                         break;
902                                                 }
903                                         }
904                                         Assert.assertTrue(found,
905                                                         "Uses relation was not created in the database.");
906                                         foundAny = foundAny || found;
907                                 }
908                         }
909                 }
910                 Assert.assertTrue(foundAny,
911                                 "No Uses relation was created in the database.");
912
913                 return aScenario.getIndex();
914         }
915
916         /**
917          * Create a document published in the scenario. <BR>
918          * document:<BR>
919          * document type[0] - first type used on the step <BR>
920          * &lt;source-file&gt;.brep <BR>
921          * &lt;attached-file&gt;.med
922          * 
923          * @param aScenario
924          *            the scenario to add the document to
925          * @param aScStep
926          *            scenario step where the document to be published
927          * @param dprop
928          *            document properties
929          * @param attachedFileExt
930          *            extension of the secon attached (exported) file
931          * @param isOutdated
932          *            outdated document flag
933          * @return the publication of the created document
934          * @throws IOException
935          * @throws MultiplyDefinedException
936          * @throws InvalidPropertyException
937          * @throws MissedPropertyException
938          */
939         private Publication createDoc(final Scenario aScenario,
940                         final org.splat.som.Step aScStep, final Properties dprop,
941                         final String attachedFileExt, final boolean isOutdated)
942                         throws MissedPropertyException, InvalidPropertyException,
943                         MultiplyDefinedException, IOException {
944                 // Create a document published in the scenario
945                 // document<i>: document type[0] - first type used on the step
946                 // <source-file>.brep
947                 // <attached-file>.med
948                 createDownloadedFile(aScenario.getAuthor().getIndex(), dprop
949                                 .getLocalPath());
950                 Publication pub = _stepService.createDocument(aScStep, dprop);
951                 Assert.assertNotNull(pub.getOwner(),
952                                 "The publication must be attached to the scenario.");
953                 Assert.assertEquals(pub.getOwner().getIndex(), aScenario.getIndex(),
954                                 "The publication was not attached to the scenario.");
955
956                 if (isOutdated) {
957                         pub.setIsnew('O');
958                 }
959                 aScenario.add(pub);
960                 HibernateTemplate ht = getHibernateTemplate();
961                 ht.saveOrUpdate(pub);
962
963                 // Attach a file
964                 createDownloadedFile(aScenario.getAuthor().getIndex(), dprop
965                                 .getLocalPath().substring(0,
966                                                 dprop.getLocalPath().lastIndexOf(".") - 1),
967                                 attachedFileExt);
968                 ht.save(pub.value());
969                 ht.saveOrUpdate(_publicationService.attach(pub, attachedFileExt));
970
971                 return pub;
972         }
973
974         /**
975          * Test check-in scenario operation to be performed after SALOME session.<BR>
976          * <B>Description :</B> <BR>
977          * <i>Create a scenario and try to check-in it with some simulated SALOME results data.<BR>
978          * After check-in verify following points:
979          * <ul>
980          * <li>scenario is no more marked as checked out</li>
981          * <li>new document versions are created for checked in documents</li>
982          * <li>presentation of the previous version is removed</li>
983          * <li>uses relations are copied correctly</li>
984          * <li>files are moved correctly</li>
985          * <li>new documents are created for new data</li>
986          * <li>uses relations are created correctly</li>
987          * <li>files are moved correctly</li>
988          * </ul>
989          * </i><BR>
990          * <B>Action : </B><BR>
991          * <i>1. call the method for an existing scenario id.</i><BR>
992          * <i>2. call the method for a not existing scenario id.</i><BR>
993          * <B>Test data : </B><BR>
994          * <i>no input parameters</i><BR>
995          * <i>no input parameters</i><BR>
996          * 
997          * <B>Outcome results:</B><BR>
998          * <i>
999          * <ul>
1000          * <li>New version of existing documents must be created and new documents must be imported for documents with zero id. Correct
1001          * relations must be created.<BR>
1002          * </li>
1003          * <li>Exception is thrown<BR>
1004          * </li>
1005          * </ul>
1006          * </i>
1007          * 
1008          * @throws InvalidPropertyException
1009          *             if an invalid property is used when creating objects
1010          * @throws MultiplyDefinedException
1011          *             when trying to create an object with already existing id
1012          * @throws MissedPropertyException
1013          *             if a mandatory property is not defined for an object to be created
1014          * @throws IOException
1015          *             if scenario creation is failed
1016          * @throws SQLException
1017          *             if scenario creation is failed
1018          * @throws NotApplicableException
1019          *             if checkin failed
1020          * @throws MismatchException
1021          *             if checkin failed
1022          */
1023         @Test(groups = { "study", "sevice", "functional", "business" })
1024         public void testCreateStudy() throws InvalidPropertyException,
1025                         MissedPropertyException, MultiplyDefinedException, IOException,
1026                         SQLException, MismatchException, NotApplicableException {
1027                 LOG.debug(">>>>> BEGIN testCreateStudy()");
1028                 startNestedTransaction();
1029
1030                 Database.getInstance().reset();
1031                 _projectSettings.getAllSteps().clear(); // Clear config to be able to load it again
1032                 _projectSettings.configure(ClassLoader
1033                                 .getSystemResource("test/som.xml").getPath());
1034
1035                 // Create a test user
1036                 User.Properties uprop = new User.Properties();
1037                 uprop.setUsername("TST_Username").setName("TST_SimanUnitTestsUser")
1038                                 .setFirstName("TST_FirstName").setDisplayName("TST_test.user")
1039                                 .addRole("TST_user").setMailAddress(
1040                                                 "noreply@salome-platform.org");
1041                 uprop.disableCheck();
1042                 User anAuthor = new User(uprop);
1043
1044                 getHibernateTemplate().saveOrUpdate(anAuthor);
1045                 KnowledgeElementType ucase = _knowledgeElementTypeService
1046                                 .selectType("usecase");
1047                 Assert.assertNotNull(ucase,
1048                                 "Knowledge type 'usecase' must be created in the database.");
1049                 SimulationContextType prodtype = _simulationContextService
1050                                 .selectType("product");
1051                 Assert
1052                                 .assertNotNull(prodtype,
1053                                                 "Simulation context type 'product' must be created in the database.");
1054
1055                 // Create admin
1056                 uprop.clear();
1057                 uprop.setUsername("TST_Admin").setName("TST_SimanUnitTestsAdmin")
1058                                 .setFirstName("TST_AdminFirstName").setDisplayName(
1059                                                 "TST_test.admin").addRole("TST_user,sysadmin")
1060                                 .setMailAddress("noreply@salome-platform.org");
1061                 uprop.disableCheck();
1062
1063                 getHibernateTemplate().saveOrUpdate(new User(uprop));
1064                 getHibernateTemplate().flush();
1065
1066                 Study.Properties sprop = new Study.Properties();
1067                 sprop.setTitle("Test study creation").setManager(anAuthor);
1068                 Scenario.Properties oprop = new Scenario.Properties();
1069                 oprop.setTitle("Test scenario for the created study");
1070
1071                 // Addition of the entered project context
1072                 SimulationContext.Properties cprop = new SimulationContext.Properties();
1073                 // Input of new project context
1074                 cprop.setType(_simulationContextService.selectType("product"))
1075                                 .setValue("Test Simulation Context: Product");
1076                 Study study = _scenarioService.createStudy(sprop, oprop, cprop);
1077
1078                 rollbackNestedTransaction();
1079                 LOG.debug(">>>>> END testCreateStudy()");
1080         }
1081 }