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