]> SALOME platform Git repositories - tools/siman.git/blob - Workspace/Siman-Common/src/test/splat/service/TestScenarioService.java
Salome HOME
Don't attach format to the file name when adding a document.
[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                 // Call checkin method for good prepared transient data.
355
356                 // Simulate checkout
357                 List<StepDTO> steps = _scenarioService.getScenarioInfo(scenarioId);
358                 _scenarioService.checkout(aScen, user);
359
360                 // Prepare test data for checkin
361                 // Checkin only two first steps (geom and mesh)
362                 List<StepDTO> stepsToCheckin = new ArrayList<StepDTO>();
363                 for (StepDTO step : steps) {
364                         // Prepare GEOM: checkin actual brep
365                         StepDTO stepToCheckin = createDocDTOForModule(null, "GEOM", "brep",
366                                         userId, step, stepsToCheckin);
367                         createDocDTOForModule(stepToCheckin, "SMESH", "med", userId, step,
368                                         stepsToCheckin);
369                 }
370                 // Do test checkin
371                 _scenarioService.checkin(scenarioId, userId, stepsToCheckin);
372
373                 _scenarioDAO.flush();
374                 // Check that scenario is no more marked as checked out
375                 aScen = _scenarioDAO.get(scenarioId);
376                 Assert.assertFalse(aScen.isCheckedout(),
377                                 "Scenario is still marked as checked out after checkin.");
378                 // Check that new document versions are created for checked in documents
379                 boolean caseFound = false;
380                 for (StepDTO step : stepsToCheckin) {
381                         for (DocumentDTO docDTO : step.getDocs()) {
382                                 if ((docDTO.getId() != 0) && (docDTO.getId() != null)) {
383                                         boolean found = false;
384                                         Document prevDoc = null;
385                                         Publication newPub = null;
386                                         for (Publication pub : aScen.getDocums()) {
387                                                 prevDoc = pub.value().getPreviousVersion();
388                                                 if (prevDoc != null) {
389                                                         found = (prevDoc.getIndex() == docDTO.getId());
390                                                         if (found) { // Found next published version of the checked in document
391                                                                 newPub = pub;
392                                                                 break;
393                                                         }
394                                                 }
395                                         }
396                                         Assert.assertTrue(found,
397                                                         "New version of the existing checked in document \""
398                                                                         + docDTO.getTitle() + "\" (id="
399                                                                         + docDTO.getId()
400                                                                         + ") is not found in the scenario.");
401                                         // Check that presentation of the previous version is removed
402                                         Assert.assertFalse(aScen.publishes(prevDoc));
403                                         checkFiles(docDTO, newPub);
404
405                                         // Formats of files are new if they are according to the document's type on the study step
406                                         if ("py".equals(prevDoc.getFormat())
407                                                         && "geometry".equals(prevDoc.getType().getName())) {
408                                                 Assert.assertEquals(newPub.value().getFormat(), "brep");
409                                                 Assert.assertEquals(newPub.getSourceFile().getFormat(),
410                                                                 "brep");
411                                                 Assert.assertEquals(newPub.getSourceFile()
412                                                                 .getRelativePath().substring(
413                                                                                 newPub.getSourceFile()
414                                                                                                 .getRelativePath().lastIndexOf(
415                                                                                                                 '.') + 1), "brep");
416                                         }
417
418                                         // Check that uses relations are copied correctly
419
420                                         // 1. Get all uses relations of the previous document version
421                                         for (Relation rel : prevDoc
422                                                         .getRelations(UsesRelation.class)) {
423                                                 Document used = ((UsesRelation) rel).getTo();
424                                                 // 2.1. Get the latest version of the document published in this scenario
425                                                 Publication toBeUsed = aScen.getPublication(used);
426                                                 if (toBeUsed == null) {
427                                                         // Find the latest published version
428                                                         for (Publication lastPub : aScen.getDocums()) {
429                                                                 if ((lastPub.value().getPreviousVersion() != null)
430                                                                                 && (lastPub.value()
431                                                                                                 .getPreviousVersion()
432                                                                                                 .getIndex() == used.getIndex())) {
433                                                                         toBeUsed = lastPub;
434                                                                         break;
435                                                                 }
436                                                         }
437                                                 }
438                                                 if ((toBeUsed != null) && (!toBeUsed.isOutdated())) {
439                                                         // 2.2. For each used document check that its latest not outdated version
440                                                         // is used by the new checked in document version.
441                                                         checkUsesRelation(newPub, toBeUsed);
442                                                 }
443                                         }
444                                         // 1. Get all usedBy relations of the previous document version
445                                         for (Relation rel : prevDoc
446                                                         .getRelations(UsedByRelation.class)) {
447                                                 Document using = ((UsedByRelation) rel).getTo();
448                                                 // Check that not checked in dependent documents became outdated
449                                                 Publication usingPub = aScen.getPublication(using);
450                                                 if (usingPub != null) { // if the document using the old version is still published
451                                                         Assert.assertTrue(usingPub.isOutdated(),
452                                                                         "Not checked in dependent document "
453                                                                                         + using.getTitle() + " ("
454                                                                                         + using.getType().getName()
455                                                                                         + ") must become outdated.");
456                                                         caseFound = true;
457                                                 }
458                                         }
459
460                                 } else {
461                                         // Check that new documents are created for new data
462                                         boolean found = false;
463                                         Publication newPub = null;
464                                         for (Publication pub : aScen.getDocums()) {
465                                                 if (pub.value().getPreviousVersion() == null) {
466                                                         found = (pub.value().getTitle().startsWith(pub
467                                                                         .value().getType().getName()));
468                                                         if (found) { // Found next published version of the checked in document
469                                                                 String fcontent = Files.readFile(pub
470                                                                                 .getSourceFile().asFile());
471                                                                 found = fcontent.contains(docDTO.getTitle());
472                                                                 if (found) {
473                                                                         LOG
474                                                                                         .debug("Found new document with generated title: "
475                                                                                                         + pub.value().getTitle());
476                                                                         newPub = pub;
477                                                                         break;
478                                                                 }
479                                                         }
480                                                 }
481                                         }
482                                         Assert.assertTrue(found,
483                                                         "New document is not created for checked in document \""
484                                                                         + docDTO.getTitle() + "\".");
485
486                                         // Check that uses relations are created correctly
487                                         Assert.assertTrue(newPub.value().getTitle().startsWith(
488                                                         newPub.value().getType().getName() + "_"),
489                                                         "Document title newPub.value().getTitle() must start with "
490                                                                         + newPub.value().getType().getName() + "_");
491
492                                         // 1. Find the document type used by this document type
493                                         Set<DocumentType> usedTypes = newPub.value().getType()
494                                                         .getDefaultUses();
495                                         // 2. Find documents of used types in the current study step and previous study steps
496                                         for (Publication pub : aScen.getDocums()) {
497                                                 if ((pub.getStep().getNumber() <= step.getNumber())
498                                                                 && (!pub.isOutdated())
499                                                                 && usedTypes.contains(pub.value().getType())) {
500                                                         // 3. Check that there is uses relation to the found document
501                                                         // if it is not outdated.
502                                                         checkUsesRelation(newPub, pub);
503                                                 }
504                                         }
505
506                                         // Check that files are moved correctly
507                                         checkFiles(docDTO, newPub);
508                                 }
509                         }
510                 }
511                 Assert.assertTrue(caseFound,
512                                 "Not checked in dependent documents must become outdated.");
513
514                 // ///////////////////////////////////////////////////////////
515                 // Call checkin method for a not existing id.
516                 try {
517                         _scenarioService.checkin(-1, userId, stepsToCheckin);
518                         Assert
519                                         .fail("Check in for scenario with not existing id must be failed.");
520                 } catch (Exception e) {
521                         LOG.debug("Expected exception is thrown: "
522                                         + e.getClass().getSimpleName() + ": " + e.getMessage());
523                 }
524
525                 // Test checkin with empty list of steps
526                 stepsToCheckin.clear();
527                 _scenarioService.checkin(scenarioId, userId, stepsToCheckin);
528
529                 rollbackNestedTransaction();
530                 LOG.debug(">>>>> END testCheckin()");
531         }
532
533         /**
534          * Check if there is uses relation from the newPub to pub.
535          * 
536          * @param newPub
537          *            the new publication
538          * @param pub
539          *            the publication to be used
540          */
541         private void checkUsesRelation(final Publication newPub,
542                         final Publication pub) {
543                 boolean uses = false;
544                 boolean usesExist = false;
545                 for (Publication usesPub : newPub.getRelations(UsesRelation.class)) {
546                         usesExist = true;
547                         uses = (usesPub.equals(pub));
548                         if (uses) {
549                                 break;
550                         }
551                 }
552                 Assert.assertTrue(usesExist && uses, "The created document "
553                                 + newPub.value().getTitle() + "("
554                                 + newPub.value().getType().getName() + ")"
555                                 + " has no uses relation to the document "
556                                 + pub.value().getTitle() + "("
557                                 + pub.value().getType().getName() + ")");
558         }
559
560         /**
561          * Check that files are moved correctly.
562          * 
563          * @param docDTO
564          *            checked in document DTO
565          * @param newPub
566          *            the created document publication
567          */
568         private void checkFiles(final DocumentDTO docDTO, final Publication newPub) {
569                 // Check that original files are deleted
570                 for (int j = 0; j < docDTO.getFiles().size(); j++) {
571                         FileDTO fileDTO = docDTO.getFiles().get(j);
572                         Assert.assertFalse(new File(fileDTO.getPath()).exists(), "File"
573                                         + fileDTO.getPath()
574                                         + " was not removed from downloads directory.");
575                         String format = fileDTO.getPath().substring(
576                                         fileDTO.getPath().lastIndexOf('.') + 1);
577                 }
578                 // TODO: Check file by its internal content
579                 Assert.assertTrue(newPub.getSourceFile().exists(), "File "
580                                 + newPub.getSourceFile().asFile().getAbsolutePath()
581                                 + " for the document " + docDTO.getTitle()
582                                 + " was not created.");
583         }
584
585         /**
586          * Prepare a document with a file for check-in.
587          * 
588          * @param stepTo
589          *            step DTO with data for check-in
590          * @param module
591          *            SALOME module name
592          * @param format
593          *            file extension
594          * @param userId
595          *            download directory
596          * @param stepFrom
597          *            checked out stepDTO
598          * @param stepsToCheckin
599          *            DTO for check-in
600          * @throws IOException
601          *             if file creation failed
602          * @return step DTO with data prepared for check-in (stepTo or new if stepTo is null)
603          */
604         private StepDTO createDocDTOForModule(final StepDTO stepTo,
605                         final String module, final String format, final long userId,
606                         final StepDTO stepFrom, final List<StepDTO> stepsToCheckin)
607                         throws IOException {
608                 StepDTO stepToCheckin = stepTo;
609                 if (stepToCheckin == null) {
610                         stepToCheckin = new StepDTO();
611                 }
612                 if (module.equals(stepFrom.getModule())) {
613                         stepsToCheckin.add(stepToCheckin);
614                         stepToCheckin.setNumber(stepFrom.getNumber());
615                         for (DocumentDTO doc : stepFrom.getDocs()) {
616                                 if (doc.getFiles().get(0).getState() != 'O') {
617                                         DocumentDTO docToCheckin = stepToCheckin.addDoc(
618                                                         doc.getId(), doc.getTitle());
619                                         for (FileDTO file : doc.getFiles()) {
620                                                 if (file.getPath().endsWith(format)
621                                                                 || (file.getPath().endsWith("py") && format
622                                                                                 .equals("brep"))) {
623                                                         // Create a file in the download directory
624                                                         docToCheckin.addFile(createDownloadedFile(userId,
625                                                                         doc.getTitle() + "_result", format));
626                                                 }
627                                         }
628                                 }
629                         }
630                         // Prepare new data
631                         stepToCheckin.addDoc(0, "newdoc" + stepFrom.getNumber()).addFile(
632                                         createDownloadedFile(userId, "newdoc"
633                                                         + stepFrom.getNumber(), "brep"));
634                 }
635                 return stepToCheckin;
636         }
637
638         /**
639          * Create a file in the user's repository downloads directory.
640          * 
641          * @param userId
642          *            user id
643          * @param name
644          *            file name
645          * @param format
646          *            file extension
647          * @return created file DTO
648          * @throws IOException
649          *             if file creation failed
650          */
651         private FileDTO createDownloadedFile(final long userId, final String name,
652                         final String format) throws IOException {
653                 // Create a file in the download directory
654                 return createDownloadedFile(userId, name + "." + format);
655         }
656
657         /**
658          * Create a file in the user's repository downloads directory.
659          * 
660          * @param userId
661          *            user id
662          * @param fname
663          *            file name
664          * @return created file DTO
665          * @throws IOException
666          *             if file creation failed
667          */
668         private FileDTO createDownloadedFile(final long userId, final String fname)
669                         throws IOException {
670                 // Create a file in the download directory
671                 String filePath = getDownloadPath(userId) + fname;
672                 FileWriter fw = new FileWriter(filePath);
673                 fw.write("Simulation of " + fname + " file for checkin at "
674                                 + new Date());
675                 fw.close();
676                 return new FileDTO(filePath);
677         }
678
679         /**
680          * Get path to the user's downloads directory. The directory is created if it is not exist yet.
681          * 
682          * @param userId
683          *            user id
684          * @return absolute path to downloads directory followed by slash
685          */
686         private String getDownloadPath(final long userId) {
687                 // Prepare download directory
688                 File tmpDir = _repositoryService.getDownloadDirectory(userId);
689                 if (!tmpDir.exists()) {
690                         Assert.assertTrue(tmpDir.mkdir(),
691                                         "Can't create temporary directory: "
692                                                         + tmpDir.getAbsolutePath());
693                 }
694
695                 return tmpDir.getAbsolutePath() + "/";
696         }
697
698         /**
699          * Create a persistent scenario for tests.
700          * 
701          * @return a persistent scenario
702          * @throws InvalidPropertyException
703          *             if an invalid property is used when creating objects
704          * @throws MultiplyDefinedException
705          *             when trying to create an object with already existing id
706          * @throws MissedPropertyException
707          *             if a mandatory property is not defined for an object to be created
708          * @throws IOException
709          *             if document creation is failed
710          * @throws SQLException
711          *             if project settings loading is failed
712          */
713         private long createScenario() throws InvalidPropertyException,
714                         MissedPropertyException, MultiplyDefinedException, IOException,
715                         SQLException {
716                 // Create a scenario for tests
717                 HibernateTemplate ht = getHibernateTemplate();
718
719                 Database.getInstance().reset();
720                 _projectSettings.getAllSteps().clear(); // Clear config to be able to load it again
721                 // Load workflow customization
722                 try {
723                         _projectSettings.configure(ClassLoader.getSystemResource(
724                                         "test/som.xml").getPath());
725                 } catch (FileNotFoundException e) {
726                         Assert.fail("Can't find som.xml: ", e);
727                 }
728                 List<Step> steps = _projectSettings.getStepsOf(Scenario.class);
729                 Assert.assertTrue(steps.size() > 0, "No steps are created.");
730
731                 // Create a test user
732                 User.Properties uprop = new User.Properties();
733                 uprop.setUsername("TST_Username").setName("TST_SimanUnitTestsUser")
734                                 .setFirstName("TST_FirstName").setDisplayName("TST_test.user")
735                                 .addRole("TST_user").setMailAddress(
736                                                 "noreply@salome-platform.org");
737                 uprop.disableCheck();
738                 User anAuthor = new User(uprop);
739                 ht.saveOrUpdate(anAuthor);
740
741                 // Create a test study
742                 Study.Properties stprops = new Study.Properties().setReference(
743                                 "TST_SID_01").setTitle("TST_Study").setManager(anAuthor);
744                 Study aStudy = new Study(stprops);
745                 ht.saveOrUpdate(aStudy);
746
747                 // Create a test scenario
748                 Scenario.Properties sprops = new Scenario.Properties().setTitle(
749                                 "TST_Scenario").setManager(anAuthor).setOwnerStudy(aStudy);
750                 Scenario aScenario = new Scenario(sprops);
751                 aStudy.getScenariiList().add(aScenario);
752                 ht.saveOrUpdate(anAuthor);
753                 ht.saveOrUpdate(aStudy);
754                 ht.saveOrUpdate(aScenario);
755
756                 // Create documents for each scenario step
757                 Document.Properties dprop = new Document.Properties().setAuthor(
758                                 anAuthor).setDate(new Date());
759                 int i = 0;
760                 Publication usedPub = null;
761                 Map<Long, Long> usedMap = new HashMap<Long, Long>();
762                 for (Step step : steps) {
763                         LOG.debug("Create scenario step: " + i);
764
765                         org.splat.som.Step aScStep = new org.splat.som.Step(step, aScenario);
766                         List<DocumentType> dtypes = _documentTypeService
767                                         .selectTypesOf(step);
768                         for (DocumentType dtype : dtypes) {
769                                 // Create a document published in the scenario
770                                 // document<i>: document type[0] - first type used on the step
771                                 // <source-file>.brep
772                                 // <attached-file>.med
773                                 dprop.setName("document" + i++).setType(dtype);
774                                 if (step.getNumber() > 3) {
775                                         dprop.setFormat("med");
776                                 } else {
777                                         dprop.setFormat("py");
778                                 }
779                                 dprop.setLocalPath(dprop.getName() + "." + dprop.getFormat());
780                                 Publication pub = createDoc(aScenario, aScStep, dprop, "med",
781                                                 false);
782                                 if (usedPub != null) {
783                                         pub.addDependency(usedPub);
784                                         ht.saveOrUpdate(pub.value());
785
786                                         usedMap.put(pub.getIndex(), usedPub.getIndex());
787                                 }
788                                 usedPub = pub;
789
790                                 // Create another document with outdated publication
791                                 dprop.setName("document" + i++).setType(dtype).setFormat("py");
792                                 dprop.setLocalPath(dprop.getName() + "." + dprop.getFormat());
793                                 createDoc(aScenario, aScStep, dprop, "med", true);
794
795                         }
796                         if (dtypes.size() <= 0) {
797                                 LOG.debug("No document types are found for scenario step " + i);
798                         }
799                 }
800
801                 // Check that the scenario and its documents have been created correctly.
802
803                 Assert.assertNotNull(ht.find("from Document"),
804                                 "No documents in the database.");
805                 Assert.assertTrue(ht.find("from Document").size() > 0,
806                                 "No documents in the database.");
807
808                 Assert.assertNotNull(ht.find("from Publication where owner="
809                                 + aScenario.getIndex()), "No publications in the database.");
810                 Assert.assertTrue(
811                                 ht.find("from Publication where owner=" + aScenario.getIndex())
812                                                 .size() > 0, "No publications in the database.");
813
814                 for (Publication p : (List<Publication>) ht
815                                 .find("from Publication where owner=" + aScenario.getIndex())) {
816                         LOG.debug("Publication found: [id=" + p.getIndex() + ", owner="
817                                         + p.getOwner().getIndex() + ", doc=" + p.value().getIndex()
818                                         + "]");
819                         Assert.assertEquals(p.getOwner().getIndex(), aScenario.getIndex(),
820                                         "The publication was not attached to the scenario.");
821                 }
822
823                 // Remove the scenario from the current hibernate session.
824                 ht.evict(aScenario);
825                 // Check that the scenario is created in the database.
826                 Scenario aScen = ht.load(Scenario.class, aScenario.getIndex());
827                 Assert.assertNotNull(aScen, "Scenario was not saved in the database.");
828                 Assert.assertTrue(aScen.getDocums().size() > 0,
829                                 "No publications in the scenario.");
830
831                 Assert.assertTrue(i > 0,
832                                 "More then one document must be in the database");
833
834                 // Check created uses relations
835                 Assert
836                                 .assertTrue(usedMap.size() > 0,
837                                                 "Uses relations must be created.");
838                 boolean foundAny = false;
839                 for (Long usingId : usedMap.keySet()) {
840                         for (Publication pub : aScen.getDocums()) {
841                                 if (pub.getIndex() == usingId) {
842                                         boolean found = false;
843                                         for (Publication used : aScen.getDocums()) {
844                                                 found = (used.getIndex() == usedMap.get(usingId));
845                                                 if (found) {
846                                                         break;
847                                                 }
848                                         }
849                                         Assert.assertTrue(found,
850                                                         "Uses relation was not created in the database.");
851                                         foundAny = foundAny || found;
852                                 }
853                         }
854                 }
855                 Assert.assertTrue(foundAny,
856                                 "No Uses relation was created in the database.");
857
858                 return aScenario.getIndex();
859         }
860
861         /**
862          * Create a document published in the scenario. <BR>
863          * document:<BR>
864          * document type[0] - first type used on the step <BR>
865          * &lt;source-file&gt;.brep <BR>
866          * &lt;attached-file&gt;.med
867          * 
868          * @param aScenario
869          *            the scenario to add the document to
870          * @param aScStep
871          *            scenario step where the document to be published
872          * @param dprop
873          *            document properties
874          * @param attachedFileExt
875          *            extension of the secon attached (exported) file
876          * @param isOutdated
877          *            outdated document flag
878          * @return the publication of the created document
879          * @throws IOException
880          * @throws MultiplyDefinedException
881          * @throws InvalidPropertyException
882          * @throws MissedPropertyException
883          */
884         private Publication createDoc(final Scenario aScenario,
885                         final org.splat.som.Step aScStep, final Properties dprop,
886                         final String attachedFileExt, final boolean isOutdated)
887                         throws MissedPropertyException, InvalidPropertyException,
888                         MultiplyDefinedException, IOException {
889                 // Create a document published in the scenario
890                 // document<i>: document type[0] - first type used on the step
891                 // <source-file>.brep
892                 // <attached-file>.med
893                 createDownloadedFile(aScenario.getAuthor().getIndex(), dprop
894                                 .getLocalPath());
895                 Publication pub = _stepService.createDocument(aScStep, dprop);
896                 Assert.assertNotNull(pub.getOwner(),
897                                 "The publication must be attached to the scenario.");
898                 Assert.assertEquals(pub.getOwner().getIndex(), aScenario.getIndex(),
899                                 "The publication was not attached to the scenario.");
900
901                 if (isOutdated) {
902                         pub.setIsnew('O');
903                 }
904                 aScenario.add(pub);
905                 HibernateTemplate ht = getHibernateTemplate();
906                 ht.saveOrUpdate(pub);
907
908                 // Attach a file
909                 createDownloadedFile(aScenario.getAuthor().getIndex(), dprop
910                                 .getLocalPath().substring(0,
911                                                 dprop.getLocalPath().lastIndexOf(".") - 1),
912                                 attachedFileExt);
913                 ht.save(pub.value());
914                 ht.saveOrUpdate(_publicationService.attach(pub, attachedFileExt));
915
916                 return pub;
917         }
918
919         /**
920          * Test check-in scenario operation to be performed after SALOME session.<BR>
921          * <B>Description :</B> <BR>
922          * <i>Create a scenario and try to check-in it with some simulated SALOME results data.<BR>
923          * After check-in verify following points:
924          * <ul>
925          * <li>scenario is no more marked as checked out</li>
926          * <li>new document versions are created for checked in documents</li>
927          * <li>presentation of the previous version is removed</li>
928          * <li>uses relations are copied correctly</li>
929          * <li>files are moved correctly</li>
930          * <li>new documents are created for new data</li>
931          * <li>uses relations are created correctly</li>
932          * <li>files are moved correctly</li>
933          * </ul>
934          * </i><BR>
935          * <B>Action : </B><BR>
936          * <i>1. call the method for an existing scenario id.</i><BR>
937          * <i>2. call the method for a not existing scenario id.</i><BR>
938          * <B>Test data : </B><BR>
939          * <i>no input parameters</i><BR>
940          * <i>no input parameters</i><BR>
941          * 
942          * <B>Outcome results:</B><BR>
943          * <i>
944          * <ul>
945          * <li>New version of existing documents must be created and new documents must be imported for documents with zero id. Correct
946          * relations must be created.<BR>
947          * </li>
948          * <li>Exception is thrown<BR>
949          * </li>
950          * </ul>
951          * </i>
952          * 
953          * @throws InvalidPropertyException
954          *             if an invalid property is used when creating objects
955          * @throws MultiplyDefinedException
956          *             when trying to create an object with already existing id
957          * @throws MissedPropertyException
958          *             if a mandatory property is not defined for an object to be created
959          * @throws IOException
960          *             if scenario creation is failed
961          * @throws SQLException
962          *             if scenario creation is failed
963          * @throws NotApplicableException
964          *             if checkin failed
965          * @throws MismatchException
966          *             if checkin failed
967          */
968         @Test(groups = { "study", "sevice", "functional", "business" })
969         public void testCreateStudy() throws InvalidPropertyException,
970                         MissedPropertyException, MultiplyDefinedException, IOException,
971                         SQLException, MismatchException, NotApplicableException {
972                 LOG.debug(">>>>> BEGIN testCreateStudy()");
973                 startNestedTransaction();
974
975                 Database.getInstance().reset();
976                 _projectSettings.getAllSteps().clear(); // Clear config to be able to load it again
977                 _projectSettings.configure(ClassLoader
978                                 .getSystemResource("test/som.xml").getPath());
979
980                 // Create a test user
981                 User.Properties uprop = new User.Properties();
982                 uprop.setUsername("TST_Username").setName("TST_SimanUnitTestsUser")
983                                 .setFirstName("TST_FirstName").setDisplayName("TST_test.user")
984                                 .addRole("TST_user").setMailAddress(
985                                                 "noreply@salome-platform.org");
986                 uprop.disableCheck();
987                 User anAuthor = new User(uprop);
988
989                 getHibernateTemplate().saveOrUpdate(anAuthor);
990                 KnowledgeElementType ucase = _knowledgeElementTypeService
991                                 .selectType("usecase");
992                 Assert.assertNotNull(ucase,
993                                 "Knowledge type 'usecase' must be created in the database.");
994                 SimulationContextType prodtype = _simulationContextService
995                                 .selectType("product");
996                 Assert
997                                 .assertNotNull(prodtype,
998                                                 "Simulation context type 'product' must be created in the database.");
999
1000                 // Create admin
1001                 uprop.clear();
1002                 uprop.setUsername("TST_Admin").setName("TST_SimanUnitTestsAdmin")
1003                                 .setFirstName("TST_AdminFirstName").setDisplayName(
1004                                                 "TST_test.admin").addRole("TST_user,sysadmin")
1005                                 .setMailAddress("noreply@salome-platform.org");
1006                 uprop.disableCheck();
1007
1008                 getHibernateTemplate().saveOrUpdate(new User(uprop));
1009                 getHibernateTemplate().flush();
1010
1011                 Study.Properties sprop = new Study.Properties();
1012                 sprop.setTitle("Test study creation").setManager(anAuthor);
1013                 Scenario.Properties oprop = new Scenario.Properties();
1014                 oprop.setTitle("Test scenario for the created study");
1015
1016                 // Addition of the entered project context
1017                 SimulationContext.Properties cprop = new SimulationContext.Properties();
1018                 // Input of new project context
1019                 cprop.setType(_simulationContextService.selectType("product"))
1020                                 .setValue("Test Simulation Context: Product");
1021                 Study study = _scenarioService.createStudy(sprop, oprop, cprop);
1022
1023                 rollbackNestedTransaction();
1024                 LOG.debug(">>>>> END testCreateStudy()");
1025         }
1026 }