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