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