Salome HOME
Fix for generating a description for version relation during checkin.
[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.Iterator;
20 import java.util.List;
21 import java.util.Map;
22 import java.util.Set;
23
24 import org.splat.dal.bo.kernel.Relation;
25 import org.splat.dal.bo.kernel.User;
26 import org.splat.dal.bo.som.ConvertsRelation;
27 import org.splat.dal.bo.som.Document;
28 import org.splat.dal.bo.som.DocumentType;
29 import org.splat.dal.bo.som.KnowledgeElementType;
30 import org.splat.dal.bo.som.Publication;
31 import org.splat.dal.bo.som.Scenario;
32 import org.splat.dal.bo.som.SimulationContext;
33 import org.splat.dal.bo.som.SimulationContextType;
34 import org.splat.dal.bo.som.Study;
35 import org.splat.dal.bo.som.UsedByRelation;
36 import org.splat.dal.bo.som.UsesRelation;
37 import org.splat.dal.bo.som.ValidationCycle;
38 import org.splat.dal.bo.som.ValidationCycleRelation;
39 import org.splat.dal.bo.som.ValidationStep;
40 import org.splat.dal.bo.som.VersionsRelation;
41 import org.splat.dal.bo.som.Document.Properties;
42 import org.splat.dal.dao.kernel.UserDAO;
43 import org.splat.dal.dao.som.Database;
44 import org.splat.dal.dao.som.ScenarioDAO;
45 import org.splat.dal.dao.som.StudyDAO;
46 import org.splat.dal.dao.som.ValidationCycleDAO;
47 import org.splat.exception.BusinessException;
48 import org.splat.exception.InvalidParameterException;
49 import org.splat.i18n.I18nUtils;
50 import org.splat.kernel.InvalidPropertyException;
51 import org.splat.kernel.MismatchException;
52 import org.splat.kernel.MissedPropertyException;
53 import org.splat.kernel.MultiplyDefinedException;
54 import org.splat.kernel.NotApplicableException;
55 import org.splat.log.AppLogger;
56 import org.splat.service.DocumentTypeService;
57 import org.splat.service.KnowledgeElementTypeService;
58 import org.splat.service.ProjectElementService;
59 import org.splat.service.PublicationService;
60 import org.splat.service.ScenarioService;
61 import org.splat.service.SimulationContextService;
62 import org.splat.service.StepService;
63 import org.splat.service.StudyService;
64 import org.splat.service.dto.DocumentDTO;
65 import org.splat.service.dto.FileDTO;
66 import org.splat.service.dto.ScenarioDTO;
67 import org.splat.service.dto.StepDTO;
68 import org.splat.service.technical.ProjectSettingsService;
69 import org.splat.service.technical.RepositoryService;
70 import org.splat.service.technical.StepsConfigService;
71 import org.splat.service.technical.ProjectSettingsService.Step;
72 import org.springframework.beans.factory.annotation.Autowired;
73 import org.springframework.beans.factory.annotation.Qualifier;
74 import org.springframework.orm.hibernate3.HibernateTemplate;
75 import org.testng.Assert;
76 import org.testng.annotations.Test;
77 import org.testng.reporters.Files;
78
79 import test.splat.common.BaseTest;
80 import test.splat.util.TestEntitiesGenerator;
81
82 /**
83  * Test class for ScenarioService.
84  * 
85  * @author <a href="mailto:roman.kozlov@opencascade.com">Roman Kozlov (RKV)</a>
86  * 
87  */
88 public class TestScenarioService extends BaseTest {
89
90         /**
91          * Logger for the class.
92          */
93         private static final AppLogger LOG = AppLogger
94                         .getLogger(TestScenarioService.class);
95
96         /**
97          * The tested ScenarioService. Later injected by Spring.
98          */
99         @Autowired
100         @Qualifier("scenarioService")
101         private transient ScenarioService _scenarioService;
102
103         /**
104          * The RepositoryService. Later injected by Spring.
105          */
106         @Autowired
107         @Qualifier("repositoryService")
108         private transient RepositoryService _repositoryService;
109
110         /**
111          * The Scenario DAO. Later injected by Spring.
112          */
113         @Autowired
114         @Qualifier("scenarioDAO")
115         private transient ScenarioDAO _scenarioDAO;
116
117         /**
118          * The PublicationService. Later injected by Spring.
119          */
120         @Autowired
121         @Qualifier("publicationService")
122         private transient PublicationService _publicationService;
123
124         /**
125          * The StepService. Later injected by Spring.
126          */
127         @Autowired
128         @Qualifier("stepService")
129         private transient StepService _stepService;
130
131         /**
132          * The SimulationContextService. Later injected by Spring.
133          */
134         @Autowired
135         @Qualifier("simulationContextService")
136         private transient SimulationContextService _simulationContextService;
137
138         /**
139          * The ProjectSettingsService. Later injected by Spring.
140          */
141         @Autowired
142         @Qualifier("projectSettings")
143         private transient ProjectSettingsService _projectSettings;
144
145         /**
146          * The StepsConfigService. Later injected by Spring.
147          */
148         @Autowired
149         @Qualifier("stepsConfigService")
150         private transient StepsConfigService _stepsConfigService;
151
152         /**
153          * The DocumentTypeService. Later injected by Spring.
154          */
155         @Autowired
156         @Qualifier("documentTypeService")
157         private transient DocumentTypeService _documentTypeService;
158
159         /**
160          * The KnowledgeElementTypeService. Later injected by Spring.
161          */
162         @Autowired
163         @Qualifier("knowledgeElementTypeService")
164         private transient KnowledgeElementTypeService _knowledgeElementTypeService;
165
166         /**
167          * The UserDAO. Later injected by Spring.
168          */
169         @Autowired
170         @Qualifier("userDAO")
171         private transient UserDAO _userDAO;
172
173         /**
174          * The StudyService. Later injected by Spring.
175          */
176         @Autowired
177         @Qualifier("studyService")
178         private transient StudyService _studyService;
179
180         /**
181          * The StudyDAO. Later injected by Spring.
182          */
183         @Autowired
184         @Qualifier("studyDAO")
185         private transient StudyDAO _studyDAO;
186
187         /**
188          * The ValidationCycleDAO. Later injected by Spring.
189          */
190         @Autowired
191         @Qualifier("validationCycleDAO")
192         private transient ValidationCycleDAO _validationCycleDAO;
193
194         /**
195          * The ProjectElementService. Later injected by Spring.
196          */
197         @Autowired
198         @Qualifier("projectElementService")
199         private transient ProjectElementService _projectElementService;
200
201         /**
202          * Test of getting a scenario content for building siman-salome.conf.<BR>
203          * <B>Description :</B> <BR>
204          * <i>Create a scenario and try to get an info for it.</i><BR>
205          * <B>Action : </B><BR>
206          * <i>1. call the method for an existing scenario id.</i><BR>
207          * <i>2. call the method for a not existing scenario id.</i><BR>
208          * <B>Test data : </B><BR>
209          * <i>no input parameters</i><BR>
210          * <i>no input parameters</i><BR>
211          * 
212          * <B>Outcome results:</B><BR>
213          * <i>
214          * <ul>
215          * <li>result DTO must contain list of all documents and files<BR>
216          * </li>
217          * <li>Exception is thrown<BR>
218          * </li>
219          * </ul>
220          * </i>
221          * 
222          * @throws InvalidPropertyException
223          *             if an invalid property is used when creating objects
224          * @throws MultiplyDefinedException
225          *             when trying to create an object with already existing id
226          * @throws MissedPropertyException
227          *             if a mandatory property is not defined for an object to be created
228          * @throws IOException
229          *             if scenario creation is failed
230          * @throws SQLException
231          *             if scenario creation is failed
232          */
233         @Test(groups = { "checkout", "sevice", "functional", "business" })
234         public void testGetScenarioInfo() throws InvalidPropertyException,
235                         MissedPropertyException, MultiplyDefinedException, IOException,
236                         SQLException {
237                 LOG.debug(">>>>> BEGIN testGetScenarioInfo()");
238                 startNestedTransaction();
239
240                 long scenarioId = createScenario();
241                 // Call DAO's create method for a good transient knowledge element.
242                 List<StepDTO> steps = _scenarioService.getScenarioInfo(scenarioId);
243                 Assert.assertNotNull(steps, "List of steps must not be null.");
244                 Assert.assertTrue(steps.size() > 0, "No steps are read.");
245
246                 List<Step> projSteps = _stepsConfigService.getStepsOf(Scenario.class);
247                 Assert.assertEquals(steps.size(), projSteps.size(),
248                                 "Not all steps are listed.");
249                 int docIndex = 0;
250                 for (StepDTO step : steps) {
251                         LOG.debug("check the step " + step.getNumber() + ":\n" + step);
252                         Assert.assertNotNull(step, "Step DTO must not be null.");
253                         Assert.assertNotNull(step.getKey(), "Step name must not be null.");
254                         Assert.assertFalse(step.getKey().isEmpty(),
255                                         "Step name must not empty.");
256                         Assert.assertTrue(step.getNumber() > 0,
257                                         "Step number must be positive integer.");
258                         Assert.assertNotNull(step.getDocs(),
259                                         "Step documents list must not be null.");
260
261                         Step aProjStep = null;
262                         for (Step projStep : projSteps) {
263                                 if (projStep.getNumber() == step.getNumber()) {
264                                         aProjStep = projStep;
265                                         break;
266                                 }
267                         }
268
269                         List<DocumentType> dtypes = _documentTypeService
270                                         .selectTypesOf(aProjStep);
271                         for (DocumentType dtype : dtypes) {
272                                 Assert.assertTrue(step.getDocs().size() > 0,
273                                                 "Step documents list must not be empty.");
274                                 String docName = "document" + docIndex;
275                                 for (DocumentDTO doc : step.getDocs()) {
276                                         if (docName.equals(doc.getTitle())) {
277                                                 Assert.assertTrue(doc.getId() > 0,
278                                                                 "Document id must be positive integer.");
279                                                 Assert.assertEquals(doc.getTitle(), docName);
280                                                 Assert.assertNotNull(doc.getFiles(),
281                                                                 "Document files list must not be null.");
282                                                 Assert
283                                                                 .assertTrue(doc.getFiles().size() > 1,
284                                                                                 "Document must have more then 1 attached file.");
285
286                                                 for (FileDTO file : doc.getFiles()) {
287                                                         Assert.assertNotNull(file.getPath(),
288                                                                         "File path must not be null.");
289                                                         Assert.assertFalse(file.getPath().isEmpty(),
290                                                                         "File path must not be empty.");
291                                                         /*
292                                                          * <mappings> <document type="geometry"> <import format="brep"/> <!-- Result Shape --> </document> <document
293                                                          * type="model"> <import format="med"/> <!-- Result mesh without input parameters --> </document> <document
294                                                          * type="loads"> <import format="c3m"/> <!-- Input data created interactively --> </document> <document
295                                                          * type="results"> <import format="med"/> <!-- Calculation results source file --> </document> </mappings>
296                                                          */
297                                                         // Check state and processing instruction
298                                                         String fileFormat = file.getPath().substring(
299                                                                         file.getPath().lastIndexOf('.') + 1);
300                                                         /*
301                                                          * if (_projectSettings.doImport(dtype.getName(), fileFormat)) { Assert.assertTrue(file.isResult(), "The file
302                                                          * must be a result file."); } else { Assert.assertFalse(file.isResult(), "The file must be a source file."); }
303                                                          */if ((docIndex % 2) == 0) { // New
304                                                                 Assert.assertEquals(file.getState(), 'Y',
305                                                                                 "File state must be actual ('Y').");
306                                                                 if (_projectSettings.doImport(dtype.getName(),
307                                                                                 fileFormat)) {
308                                                                         Assert.assertEquals(file.getProcessing(),
309                                                                                         "file-import",
310                                                                                         "File must be imported.");
311                                                                 } else {
312                                                                         Assert.assertEquals(file.getProcessing(),
313                                                                                         "file-download",
314                                                                                         "File must be downloaded.");
315                                                                 }
316                                                         } else { // Outdated
317                                                                 Assert.assertEquals(file.getState(), 'O',
318                                                                                 "File state must be outdated ('O').");
319                                                                 Assert
320                                                                                 .assertEquals(file.getProcessing(),
321                                                                                                 "file-download",
322                                                                                                 "Outdated document should not be imported but downloaded.");
323                                                         }
324                                                 }
325                                         }
326                                 }
327                                 docIndex++;
328                         }
329                 }
330
331                 // Call DAO's get method for a not existing id.
332                 try {
333                         steps = _scenarioService.getScenarioInfo(-1L);
334                         // getHibernateTemplate().flush();
335                         Assert
336                                         .fail("Getting an object with not existing id must be failed.");
337                 } catch (Exception e) {
338                         LOG.debug("Expected exception is thrown: "
339                                         + e.getClass().getSimpleName() + ": " + e.getMessage());
340                 }
341                 rollbackNestedTransaction();
342                 LOG.debug(">>>>> END testGetScenarioInfo()");
343         }
344
345         /**
346          * Test check-in scenario operation to be performed after SALOME session.<BR>
347          * <B>Description :</B> <BR>
348          * <i>Create a scenario and try to check-in it with some simulated SALOME results data.<BR>
349          * After check-in verify following points:
350          * <ul>
351          * <li>scenario is no more marked as checked out</li>
352          * <li>new document versions are created for checked in documents</li>
353          * <li>presentation of the previous version is removed</li>
354          * <li>uses relations are copied correctly</li>
355          * <li>files are moved correctly</li>
356          * <li>formats of files are new if they are according to the document's type on the study step</li>
357          * <li>new documents are created for new data</li>
358          * <li>new documents have correctly generated names</li>
359          * <li>uses relations are created correctly</li>
360          * <li>files are moved correctly</li>
361          * </ul>
362          * </i><BR>
363          * <B>Action : </B><BR>
364          * <i>1. call the method for an existing scenario id.</i><BR>
365          * <i>2. call the method for a not existing scenario id.</i><BR>
366          * <B>Test data : </B><BR>
367          * <i>no input parameters</i><BR>
368          * <i>no input parameters</i><BR>
369          * 
370          * <B>Outcome results:</B><BR>
371          * <i>
372          * <ul>
373          * <li>New version of existing documents must be created and new documents must be imported for documents with zero id. Correct
374          * relations must be created.<BR>
375          * </li>
376          * <li>Exception is thrown<BR>
377          * </li>
378          * </ul>
379          * </i>
380          * 
381          * @throws InvalidPropertyException
382          *             if an invalid property is used when creating objects
383          * @throws MultiplyDefinedException
384          *             when trying to create an object with already existing id
385          * @throws MissedPropertyException
386          *             if a mandatory property is not defined for an object to be created
387          * @throws IOException
388          *             if scenario creation is failed
389          * @throws SQLException
390          *             if scenario creation is failed
391          * @throws NotApplicableException
392          *             if checkin failed
393          * @throws MismatchException
394          *             if checkin failed
395          */
396         @Test(groups = { "checkin", "sevice", "functional", "business" })
397         public void testCheckin() throws InvalidPropertyException,
398                         MissedPropertyException, MultiplyDefinedException, IOException,
399                         SQLException, MismatchException, NotApplicableException {
400                 LOG.debug(">>>>> BEGIN testCheckin()");
401                 startNestedTransaction();
402
403                 _projectSettings.getAllSteps().clear(); // Clear config to be able to load it again
404                 _projectSettings.configure("classpath:test/som.xml");
405                 getHibernateTemplate().flush();
406                 long scenarioId = createScenario();
407                 Scenario aScen = _scenarioDAO.get(scenarioId);
408                 User user = aScen.getAuthor();
409                 long userId = user.getIndex();
410
411                 // ////////////////////////////////////////////////////////
412                 // Call checkin method for empty list of modules.
413
414                 // Simulate checkout
415                 List<StepDTO> steps = _scenarioService.getScenarioInfo(scenarioId);
416                 _scenarioService.checkout(aScen, user);
417                 _scenarioDAO.flush();
418                 // Check that scenario is no more marked as checked out
419                 aScen = _scenarioDAO.get(scenarioId);
420                 Assert.assertTrue(aScen.isCheckedout(),
421                                 "Scenario is not marked as checked out after checkout.");
422
423                 // Prepare test data for checkin
424                 // Checkin only two first steps (geom and mesh)
425                 List<StepDTO> stepsToCheckin = new ArrayList<StepDTO>();
426                 // Do test checkin
427                 _scenarioService.checkin(scenarioId, userId, stepsToCheckin);
428
429                 _scenarioDAO.flush();
430                 // Check that scenario is no more marked as checked out
431                 aScen = _scenarioDAO.get(scenarioId);
432                 Assert.assertFalse(aScen.isCheckedout(),
433                                 "Scenario is still marked as checked out after checkin.");
434
435                 // ////////////////////////////////////////////////////////
436                 // Call checkin method for good prepared transient data.
437
438                 // Simulate checkout
439                 steps = _scenarioService.getScenarioInfo(scenarioId);
440                 _scenarioService.checkout(aScen, user);
441
442                 // Remember modification dates of all attached files
443                 Map<Long, Date> dates = new HashMap<Long, Date>();
444                 for (Publication p : aScen.getDocums()) {
445                         for (Relation r : p.value().getRelations(ConvertsRelation.class)) {
446                                 org.splat.dal.bo.som.File attach = ((ConvertsRelation) r)
447                                                 .getTo();
448                                 dates.put(attach.getIndex(), attach.getDate());
449                         }
450                 }
451
452                 // Prepare test data for checkin
453                 // Checkin only two first steps (geom and mesh)
454                 for (StepDTO step : steps) {
455                         // Prepare GEOM: checkin actual brep
456                         StepDTO stepToCheckin = createDocDTOForModule(null, "GEOM", "brep",
457                                         userId, step, stepsToCheckin);
458                         createDocDTOForModule(stepToCheckin, "SMESH", "med", userId, step,
459                                         stepsToCheckin);
460                 }
461                 // /////////////////////////////////////////////////////////////////
462                 // Do test checkin
463                 _scenarioService.checkin(scenarioId, userId, stepsToCheckin);
464
465                 _scenarioDAO.flush();
466                 // Check that scenario is no more marked as checked out
467                 aScen = _scenarioDAO.get(scenarioId);
468                 Assert.assertFalse(aScen.isCheckedout(),
469                                 "Scenario is still marked as checked out after checkin.");
470                 boolean modifDatesChecked = false;
471                 // Check that new document versions are created for checked in documents
472                 for (StepDTO step : stepsToCheckin) {
473                         for (DocumentDTO docDTO : step.getDocs()) {
474                                 if ((docDTO.getId() != 0) && (docDTO.getId() != null)) {
475                                         boolean found = false;
476                                         Document prevDoc = null;
477                                         Document curDoc = null;
478                                         Publication newPub = null;
479                                         for (Publication pub : aScen.getDocums()) {
480                                                 prevDoc = pub.value().getPreviousVersion();
481                                                 if (prevDoc != null) {
482                                                         found = (prevDoc.getIndex() == docDTO.getId());
483                                                         if (found) { // Found next published version of the checked in document
484                                                                 newPub = pub;
485                                                                 break;
486                                                         }
487                                                 }
488                                                 if (pub.value().getIndex() == docDTO.getId()) {
489                                                         // Document version was not changed, old document is still published
490                                                         curDoc = pub.value();
491                                                         break;
492                                                 }
493                                         }
494                                         Assert.assertTrue(found || (curDoc != null),
495                                                         "New version or new attached file of the existing checked in document \""
496                                                                         + docDTO.getTitle() + "\" (id="
497                                                                         + docDTO.getId()
498                                                                         + ") is not found in the scenario.");
499                                         // If previous version is found then the format must be the same
500                                         String newFormat = docDTO.getFiles().get(0).getPath()
501                                                         .substring(
502                                                                         docDTO.getFiles().get(0).getPath()
503                                                                                         .lastIndexOf('.') + 1);
504                                         if (found) {
505                                                 Assert.assertEquals(prevDoc.getFormat(), newFormat,
506                                                                 "Formats of versions must be same");
507                                                 Assert.assertFalse(aScen.publishes(prevDoc));
508                                                 // Check that presentation of the previous version is removed
509                                                 checkFiles(docDTO, newPub);
510
511                                                 // Formats of files are new if they are according to the document's type on the study step
512                                                 if ("py".equals(prevDoc.getFormat())
513                                                                 && "geometry".equals(prevDoc.getType()
514                                                                                 .getName())) {
515                                                         Assert.assertEquals(newPub.value().getFormat(),
516                                                                         newFormat);
517                                                         Assert.assertEquals(newPub.getSourceFile()
518                                                                         .getFormat(), newFormat);
519                                                         Assert.assertEquals(newPub.getSourceFile()
520                                                                         .getRelativePath().substring(
521                                                                                         newPub.getSourceFile()
522                                                                                                         .getRelativePath()
523                                                                                                         .lastIndexOf('.') + 1),
524                                                                         newFormat);
525                                                 }
526
527                                                 // Check that uses relations are copied correctly
528
529                                                 // 1. Get all uses relations of the previous document version
530                                                 for (Relation rel : prevDoc
531                                                                 .getRelations(UsesRelation.class)) {
532                                                         Document used = ((UsesRelation) rel).getTo();
533                                                         // 2.1. Get the latest version of the document published in this scenario
534                                                         Publication toBeUsed = aScen.getPublication(used);
535                                                         if (toBeUsed == null) {
536                                                                 // Find the latest published version
537                                                                 for (Publication lastPub : aScen.getDocums()) {
538                                                                         if ((lastPub.value().getPreviousVersion() != null)
539                                                                                         && (lastPub.value()
540                                                                                                         .getPreviousVersion()
541                                                                                                         .getIndex() == used
542                                                                                                         .getIndex())) {
543                                                                                 toBeUsed = lastPub;
544                                                                                 break;
545                                                                         }
546                                                                 }
547                                                         }
548                                                         if ((toBeUsed != null) && (!toBeUsed.isOutdated())) {
549                                                                 // 2.2. For each used document check that its latest not outdated version
550                                                                 // is used by the new checked in document version.
551                                                                 checkUsesRelation(newPub, toBeUsed);
552                                                         }
553                                                 }
554                                                 // 1. Get all usedBy relations of the previous document version
555                                                 for (Relation rel : prevDoc
556                                                                 .getRelations(UsedByRelation.class)) {
557                                                         Document using = ((UsedByRelation) rel).getTo();
558                                                         // Check that not checked in dependent documents became outdated
559                                                         Publication usingPub = aScen.getPublication(using);
560                                                         if (usingPub != null) { // if the document using the old version is still published
561                                                                 Assert.assertTrue(usingPub.isOutdated(),
562                                                                                 "Not checked in dependent document "
563                                                                                                 + using.getTitle() + " ("
564                                                                                                 + using.getType().getName()
565                                                                                                 + ") must become outdated.");
566                                                         }
567                                                 }
568
569                                                 // Check that a correct comment is generated for VersionsRelation
570                                                 VersionsRelation versRel = (VersionsRelation) newPub
571                                                                 .value().getFirstRelation(
572                                                                                 VersionsRelation.class);
573                                                 Assert.assertNotNull(versRel,
574                                                                 "VersionsRelation must be created.");
575                                                 Assert
576                                                                 .assertNotNull(versRel.getDescription(),
577                                                                                 "VersionsRelation description was not generated.");
578                                                 int descrLen = versRel.getDescription().length();
579                                                 Assert.assertTrue(descrLen > 0,
580                                                                 "VersionsRelation description is empty.");
581                                                 LOG.debug("Version description: "
582                                                                 + versRel.getDescription());
583                                         } else {
584                                                 // Otherwise the new file format must differ from the previous one
585                                                 // and the new file must be attached to the same document
586                                                 org.splat.dal.bo.som.File attFile = curDoc
587                                                                 .getAttachedFile(newFormat);
588                                                 Assert.assertNotNull(attFile, "File "
589                                                                 + docDTO.getFiles().get(0).getPath()
590                                                                 + " must be attached to the document "
591                                                                 + docDTO.getTitle() + "#" + docDTO.getId());
592                                                 Assert.assertTrue(attFile.asFile().exists(), "File "
593                                                                 + docDTO.getFiles().get(0).getPath()
594                                                                 + " attached to the document "
595                                                                 + docDTO.getTitle() + "#" + docDTO.getId()
596                                                                 + " doesn't exist");
597                                                 LOG.debug("Source format: " + curDoc.getFormat()
598                                                                 + ", new format: " + newFormat);
599                                                 // Check that attachment with the same format is not duplicated.
600                                                 int attachNb = 0;
601                                                 for (Relation conv : curDoc
602                                                                 .getRelations(ConvertsRelation.class)) {
603                                                         if (newFormat.equals(((ConvertsRelation) conv)
604                                                                         .getTo().getFormat())) {
605                                                                 attachNb++;
606                                                         }
607                                                 }
608                                                 Assert
609                                                                 .assertEquals(attachNb, 1,
610                                                                                 "Attachment with the same format must be only one.");
611
612                                                 // Check that the attached file date is updated
613                                                 if (dates.containsKey(attFile.getIndex())) {
614                                                         Assert
615                                                                         .assertTrue(attFile.getDate().compareTo(
616                                                                                         dates.get(attFile.getIndex())) > 0,
617                                                                                         "Attachment modification date is not updated.");
618                                                         modifDatesChecked = true;
619                                                 }
620                                         }
621
622                                 } else {
623                                         // Check that new documents are created for new data
624                                         boolean found = false;
625                                         Publication newPub = null;
626                                         for (Publication pub : aScen.getDocums()) {
627                                                 if (pub.value().getPreviousVersion() == null) {
628                                                         found = (pub.value().getTitle().startsWith(pub
629                                                                         .value().getType().getName()));
630                                                         if (found) { // Found next published version of the checked in document
631                                                                 String fcontent = Files.readFile(pub
632                                                                                 .getSourceFile().asFile());
633                                                                 found = fcontent.contains(docDTO.getTitle());
634                                                                 if (found) {
635                                                                         LOG
636                                                                                         .debug("Found new document with generated title: "
637                                                                                                         + pub.value().getTitle());
638                                                                         newPub = pub;
639                                                                         break;
640                                                                 }
641                                                         }
642                                                 }
643                                         }
644                                         Assert.assertTrue(found,
645                                                         "New document is not created for checked in document \""
646                                                                         + docDTO.getTitle() + "\".");
647
648                                         // Check that uses relations are created correctly
649                                         Assert.assertTrue(newPub.value().getTitle().startsWith(
650                                                         newPub.value().getType().getName() + "_"),
651                                                         "Document title newPub.value().getTitle() must start with "
652                                                                         + newPub.value().getType().getName() + "_");
653
654                                         // 1. Find the document type used by this document type
655                                         Set<DocumentType> usedTypes = newPub.value().getType()
656                                                         .getDefaultUses();
657                                         // 2. Find documents of used types in the current study step and previous study steps
658                                         for (Publication pub : aScen.getDocums()) {
659                                                 if ((pub.getStep().getNumber() <= step.getNumber())
660                                                                 && (!pub.isOutdated())
661                                                                 && usedTypes.contains(pub.value().getType())) {
662                                                         // 3. Check that there is uses relation to the found document
663                                                         // if it is not outdated.
664                                                         checkUsesRelation(newPub, pub);
665                                                 }
666                                         }
667
668                                         // Check that files are moved correctly
669                                         checkFiles(docDTO, newPub);
670                                 }
671                         }
672                 }
673
674                 Assert
675                                 .assertTrue(
676                                                 modifDatesChecked,
677                                                 "No modification date is checked because no files were attached when attachment with same extension already exists.");
678
679                 // ///////////////////////////////////////////////////////////
680                 // Call checkin method for a not existing id.
681                 try {
682                         _scenarioService.checkin(-1, userId, stepsToCheckin);
683                         Assert
684                                         .fail("Check in for scenario with not existing id must be failed.");
685                 } catch (Exception e) {
686                         LOG.debug("Expected exception is thrown: "
687                                         + e.getClass().getSimpleName() + ": " + e.getMessage());
688                 }
689
690                 // Test checkin with empty list of steps
691                 stepsToCheckin.clear();
692                 _scenarioService.checkin(scenarioId, userId, stepsToCheckin);
693
694                 rollbackNestedTransaction();
695                 LOG.debug(">>>>> END testCheckin()");
696         }
697
698         /**
699          * Check if there is uses relation from the newPub to pub.
700          * 
701          * @param newPub
702          *            the new publication
703          * @param pub
704          *            the publication to be used
705          */
706         private void checkUsesRelation(final Publication newPub,
707                         final Publication pub) {
708                 boolean uses = false;
709                 boolean usesExist = false;
710                 for (Publication usesPub : newPub.getRelations(UsesRelation.class)) {
711                         usesExist = true;
712                         uses = (usesPub.equals(pub));
713                         if (uses) {
714                                 break;
715                         }
716                 }
717                 Assert.assertTrue(usesExist && uses, "The created document "
718                                 + newPub.value().getTitle() + "("
719                                 + newPub.value().getType().getName() + ")"
720                                 + " has no uses relation to the document "
721                                 + pub.value().getTitle() + "("
722                                 + pub.value().getType().getName() + ")");
723         }
724
725         /**
726          * Check that files are moved correctly.
727          * 
728          * @param docDTO
729          *            checked in document DTO
730          * @param newPub
731          *            the created document publication
732          */
733         private void checkFiles(final DocumentDTO docDTO, final Publication newPub) {
734                 // Check that original files are deleted
735                 for (int j = 0; j < docDTO.getFiles().size(); j++) {
736                         FileDTO fileDTO = docDTO.getFiles().get(j);
737                         Assert.assertFalse(new File(fileDTO.getPath()).exists(), "File"
738                                         + fileDTO.getPath()
739                                         + " was not removed from downloads directory.");
740                         String format = fileDTO.getPath().substring(
741                                         fileDTO.getPath().lastIndexOf('.') + 1);
742                 }
743                 // TODO: Check file by its internal content
744                 Assert.assertTrue(newPub.getSourceFile().exists(), "File "
745                                 + newPub.getSourceFile().asFile().getAbsolutePath()
746                                 + " for the document " + docDTO.getTitle()
747                                 + " was not created.");
748         }
749
750         /**
751          * Prepare a document with a file for check-in.
752          * 
753          * @param stepTo
754          *            step DTO with data for check-in
755          * @param module
756          *            SALOME module name
757          * @param format
758          *            file extension
759          * @param userId
760          *            download directory
761          * @param stepFrom
762          *            checked out stepDTO
763          * @param stepsToCheckin
764          *            DTO for check-in
765          * @throws IOException
766          *             if file creation failed
767          * @return step DTO with data prepared for check-in (stepTo or new if stepTo is null)
768          */
769         private StepDTO createDocDTOForModule(final StepDTO stepTo,
770                         final String module, final String format, final long userId,
771                         final StepDTO stepFrom, final List<StepDTO> stepsToCheckin)
772                         throws IOException {
773                 StepDTO stepToCheckin = stepTo;
774                 if (stepToCheckin == null) {
775                         stepToCheckin = new StepDTO();
776                 }
777                 if (module.equals(stepFrom.getModule())) {
778                         stepsToCheckin.add(stepToCheckin);
779                         stepToCheckin.setNumber(stepFrom.getNumber());
780                         for (DocumentDTO doc : stepFrom.getDocs()) {
781                                 if (doc.getFiles().get(0).getState() != 'O') {
782                                         DocumentDTO docToCheckin = stepToCheckin.addDoc(
783                                                         doc.getId(), doc.getTitle());
784                                         for (FileDTO file : doc.getFiles()) {
785                                                 if (file.getPath().endsWith(format)
786                                                                 || (file.getPath().endsWith("py") && (format
787                                                                                 .equals("brep") || format.equals("med")))) {
788                                                         // Create a file in the download directory
789                                                         if ("GEOM".equals(module)) {
790                                                                 // New version case
791                                                                 docToCheckin.addFile(createDownloadedFile(
792                                                                                 userId, doc.getTitle() + "_newvers",
793                                                                                 "py"));
794                                                         } else {
795                                                                 // Attached generated result case
796                                                                 docToCheckin.addFile(createDownloadedFile(
797                                                                                 userId, doc.getTitle() + "_result",
798                                                                                 format));
799                                                         }
800                                                 }
801                                         }
802                                 }
803                         }
804                         // Prepare new data
805                         stepToCheckin.addDoc(0, "newdoc" + stepFrom.getNumber()).addFile(
806                                         createDownloadedFile(userId, "newdoc"
807                                                         + stepFrom.getNumber(), "brep"));
808                 }
809                 return stepToCheckin;
810         }
811
812         /**
813          * Create a file in the user's repository downloads directory.
814          * 
815          * @param userId
816          *            user id
817          * @param name
818          *            file name
819          * @param format
820          *            file extension
821          * @return created file DTO
822          * @throws IOException
823          *             if file creation failed
824          */
825         private FileDTO createDownloadedFile(final long userId, final String name,
826                         final String format) throws IOException {
827                 // Create a file in the download directory
828                 return createDownloadedFile(userId, name + "." + format);
829         }
830
831         /**
832          * Create a file in the user's repository downloads directory.
833          * 
834          * @param userId
835          *            user id
836          * @param fname
837          *            file name
838          * @return created file DTO
839          * @throws IOException
840          *             if file creation failed
841          */
842         private FileDTO createDownloadedFile(final long userId, final String fname)
843                         throws IOException {
844                 // Create a file in the download directory
845                 String filePath = getDownloadPath(userId) + fname;
846                 FileWriter fw = new FileWriter(filePath);
847                 fw.write("Simulation of " + fname + " file for checkin at "
848                                 + new Date());
849                 fw.close();
850                 return new FileDTO(filePath);
851         }
852
853         /**
854          * Create a persistent scenario for tests.
855          * 
856          * @return a persistent scenario
857          * @throws InvalidPropertyException
858          *             if an invalid property is used when creating objects
859          * @throws MultiplyDefinedException
860          *             when trying to create an object with already existing id
861          * @throws MissedPropertyException
862          *             if a mandatory property is not defined for an object to be created
863          * @throws IOException
864          *             if document creation is failed
865          * @throws SQLException
866          *             if project settings loading is failed
867          */
868         private long createScenario() throws InvalidPropertyException,
869                         MissedPropertyException, MultiplyDefinedException, IOException,
870                         SQLException {
871                 // Create a scenario for tests
872                 HibernateTemplate ht = getHibernateTemplate();
873
874                 Database.getInstance().reset();
875                 _projectSettings.getAllSteps().clear(); // Clear config to be able to load it again
876                 // Load workflow customization
877                 try {
878                         _projectSettings.configure("classpath:test/som.xml");
879                 } catch (FileNotFoundException e) {
880                         Assert.fail("Can't find som.xml: ", e);
881                 }
882                 List<Step> steps = _stepsConfigService.getStepsOf(Scenario.class);
883                 Assert.assertTrue(steps.size() > 0, "No steps are created.");
884
885                 // Create a test user
886                 User.Properties uprop = new User.Properties();
887                 uprop.setUsername("TST_Username").setName("TST_SimanUnitTestsUser")
888                                 .setFirstName("TST_FirstName").setDisplayName("TST_test.user")
889                                 .addRole("TST_user").setMailAddress(
890                                                 "noreply@salome-platform.org");
891                 uprop.disableCheck();
892                 User anAuthor = new User(uprop);
893                 ht.saveOrUpdate(anAuthor);
894
895                 // Create a test study
896                 Study.Properties stprops = new Study.Properties().setReference(
897                                 "TST_SID_01").setTitle("TST_Study").setManager(anAuthor);
898                 Study aStudy = new Study(stprops);
899                 ht.saveOrUpdate(aStudy);
900
901                 // Create a test scenario
902                 Scenario.Properties sprops = new Scenario.Properties().setTitle(
903                                 "TST_Scenario").setManager(anAuthor).setOwnerStudy(aStudy);
904                 Scenario aScenario = new Scenario(sprops);
905                 aStudy.getScenariiList().add(aScenario);
906                 ht.saveOrUpdate(anAuthor);
907                 ht.saveOrUpdate(aStudy);
908                 ht.saveOrUpdate(aScenario);
909
910                 // Create documents for each scenario step
911                 Document.Properties dprop = new Document.Properties().setAuthor(
912                                 anAuthor).setDate(new Date());
913                 int i = 0;
914                 Publication usedPub = null;
915                 Map<Long, Long> usedMap = new HashMap<Long, Long>();
916                 for (Step step : steps) {
917                         LOG.debug("Create scenario step: " + i);
918
919                         org.splat.som.Step aScStep = new org.splat.som.Step(step, aScenario);
920                         List<DocumentType> dtypes = _documentTypeService
921                                         .selectTypesOf(step);
922                         for (DocumentType dtype : dtypes) {
923                                 // Create a document published in the scenario
924                                 // document<i>: document type[0] - first type used on the step
925                                 // <source-file>.brep
926                                 // <attached-file>.med
927                                 dprop.setName("document" + i++).setType(dtype);
928                                 /*
929                                  * if (step.getNumber() > 3) { dprop.setFormat("med"); } else {
930                                  */dprop.setFormat("py");
931                                 // }
932                                 dprop.setLocalPath(dprop.getName() + "." + dprop.getFormat());
933                                 Publication pub = createDoc(aScenario, aScStep, dprop, "med",
934                                                 false);
935                                 if (usedPub != null) {
936                                         pub.addDependency(usedPub);
937                                         ht.saveOrUpdate(pub.value());
938
939                                         usedMap.put(pub.getIndex(), usedPub.getIndex());
940                                 }
941                                 usedPub = pub;
942
943                                 // Create another document with outdated publication
944                                 dprop.setName("document" + i++).setType(dtype).setFormat("py");
945                                 dprop.setLocalPath(dprop.getName() + "." + dprop.getFormat());
946                                 createDoc(aScenario, aScStep, dprop, "med", true);
947
948                         }
949                         if (dtypes.size() <= 0) {
950                                 LOG.debug("No document types are found for scenario step " + i);
951                         }
952                 }
953
954                 // Check that the scenario and its documents have been created correctly.
955
956                 Assert.assertNotNull(ht.find("from Document"),
957                                 "No documents in the database.");
958                 Assert.assertTrue(ht.find("from Document").size() > 0,
959                                 "No documents in the database.");
960
961                 Assert.assertNotNull(ht.find("from Publication where owner="
962                                 + aScenario.getIndex()), "No publications in the database.");
963                 Assert.assertTrue(
964                                 ht.find("from Publication where owner=" + aScenario.getIndex())
965                                                 .size() > 0, "No publications in the database.");
966
967                 for (Publication p : (List<Publication>) ht
968                                 .find("from Publication where owner=" + aScenario.getIndex())) {
969                         LOG.debug("Publication found: [id=" + p.getIndex() + ", owner="
970                                         + p.getOwner().getIndex() + ", doc=" + p.value().getIndex()
971                                         + "]");
972                         Assert.assertEquals(p.getOwner().getIndex(), aScenario.getIndex(),
973                                         "The publication was not attached to the scenario.");
974                 }
975
976                 // Remove the scenario from the current hibernate session.
977                 ht.evict(aScenario);
978                 // Check that the scenario is created in the database.
979                 Scenario aScen = ht.load(Scenario.class, aScenario.getIndex());
980                 Assert.assertNotNull(aScen, "Scenario was not saved in the database.");
981                 Assert.assertTrue(aScen.getDocums().size() > 0,
982                                 "No publications in the scenario.");
983
984                 Assert.assertTrue(i > 0,
985                                 "More then one document must be in the database");
986
987                 // Check created uses relations
988                 Assert
989                                 .assertTrue(usedMap.size() > 0,
990                                                 "Uses relations must be created.");
991                 boolean foundAny = false;
992                 for (Long usingId : usedMap.keySet()) {
993                         for (Publication pub : aScen.getDocums()) {
994                                 if (pub.getIndex() == usingId) {
995                                         boolean found = false;
996                                         for (Publication used : aScen.getDocums()) {
997                                                 found = (used.getIndex() == usedMap.get(usingId));
998                                                 if (found) {
999                                                         break;
1000                                                 }
1001                                         }
1002                                         Assert.assertTrue(found,
1003                                                         "Uses relation was not created in the database.");
1004                                         foundAny = foundAny || found;
1005                                 }
1006                         }
1007                 }
1008                 Assert.assertTrue(foundAny,
1009                                 "No Uses relation was created in the database.");
1010
1011                 return aScenario.getIndex();
1012         }
1013
1014         /**
1015          * Create a document published in the scenario. <BR>
1016          * document:<BR>
1017          * document type[0] - first type used on the step <BR>
1018          * &lt;source-file&gt;.brep <BR>
1019          * &lt;attached-file&gt;.med
1020          * 
1021          * @param aScenario
1022          *            the scenario to add the document to
1023          * @param aScStep
1024          *            scenario step where the document to be published
1025          * @param dprop
1026          *            document properties
1027          * @param attachedFileExt
1028          *            extension of the secon attached (exported) file
1029          * @param isOutdated
1030          *            outdated document flag
1031          * @return the publication of the created document
1032          * @throws IOException
1033          * @throws MultiplyDefinedException
1034          * @throws InvalidPropertyException
1035          * @throws MissedPropertyException
1036          */
1037         private Publication createDoc(final Scenario aScenario,
1038                         final org.splat.som.Step aScStep, final Properties dprop,
1039                         final String attachedFileExt, final boolean isOutdated)
1040                         throws MissedPropertyException, InvalidPropertyException,
1041                         MultiplyDefinedException, IOException {
1042                 // Create a document published in the scenario
1043                 // document<i>: document type[0] - first type used on the step
1044                 // <source-file>.brep
1045                 // <attached-file>.med
1046                 createDownloadedFile(aScenario.getAuthor().getIndex(), dprop
1047                                 .getLocalPath());
1048                 Publication pub = _stepService.createDocument(aScStep, dprop);
1049                 Assert.assertNotNull(pub.getOwner(),
1050                                 "The publication must be attached to the scenario.");
1051                 Assert.assertEquals(pub.getOwner().getIndex(), aScenario.getIndex(),
1052                                 "The publication was not attached to the scenario.");
1053
1054                 if (isOutdated) {
1055                         pub.setIsnew('O');
1056                 }
1057                 aScenario.add(pub);
1058                 HibernateTemplate ht = getHibernateTemplate();
1059                 ht.saveOrUpdate(pub);
1060
1061                 // Attach a file
1062                 createDownloadedFile(aScenario.getAuthor().getIndex(), dprop
1063                                 .getLocalPath().substring(0,
1064                                                 dprop.getLocalPath().lastIndexOf(".") - 1),
1065                                 attachedFileExt);
1066                 ht.save(pub.value());
1067                 ht.saveOrUpdate(_publicationService.attach(pub, attachedFileExt));
1068
1069                 return pub;
1070         }
1071
1072         /**
1073          * Test study creation.<BR>
1074          * <B>Description :</B> <BR>
1075          * <i>Create a study.</i><BR>
1076          * <B>Action : </B><BR>
1077          * <i>1. call the method for a not existing product.</i><BR>
1078          * <i>2. call the method for an existing username and an existing product.</i><BR>
1079          * <i>3. call the method for a not existing username expecting an exception.</i><BR>
1080          * <B>Test data : </B><BR>
1081          * <i>no input parameters</i><BR>
1082          * 
1083          * <B>Outcome results:</B><BR>
1084          * <i>
1085          * <ul>
1086          * <li>1: The new study must be created. The new product simulation context must be created.</li>
1087          * <li>2: The new study must be created.</li>
1088          * <li>3: The new study must not be created. Exception must be thrown.</li>
1089          * </ul>
1090          * </i>
1091          * 
1092          * @throws IOException
1093          *             if application configuration loading is failed
1094          * @throws SQLException
1095          *             if application configuration loading is failed
1096          * @throws BusinessException
1097          *             if test data creation is failed
1098          */
1099         @Test(groups = { "study", "sevice", "functional", "business" })
1100         public void testCreateStudy() throws BusinessException, IOException,
1101                         SQLException {
1102                 LOG.debug(">>>>> BEGIN testCreateStudy()");
1103                 startNestedTransaction();
1104
1105                 Database.getInstance().reset();
1106                 _projectSettings.getAllSteps().clear(); // Clear config to be able to load it again
1107                 _projectSettings.configure("classpath:test/som.xml");
1108
1109                 // Create a test user
1110                 User.Properties uprop = new User.Properties();
1111                 uprop.setUsername("TST_Username").setName("TST_SimanUnitTestsUser")
1112                                 .setFirstName("TST_FirstName").setDisplayName("TST_test.user")
1113                                 .addRole("TST_user").setMailAddress(
1114                                                 "noreply@salome-platform.org");
1115                 uprop.disableCheck();
1116                 User anAuthor = new User(uprop);
1117
1118                 getHibernateTemplate().saveOrUpdate(anAuthor);
1119                 KnowledgeElementType ucase = _knowledgeElementTypeService
1120                                 .selectType("usecase");
1121                 Assert.assertNotNull(ucase,
1122                                 "Knowledge type 'usecase' must be created in the database.");
1123                 SimulationContextType prodtype = _simulationContextService
1124                                 .selectType("product");
1125                 Assert
1126                                 .assertNotNull(prodtype,
1127                                                 "Simulation context type 'product' must be created in the database.");
1128
1129                 // Create admin
1130                 uprop.clear();
1131                 uprop.setUsername("TST_Admin").setName("TST_SimanUnitTestsAdmin")
1132                                 .setFirstName("TST_AdminFirstName").setDisplayName(
1133                                                 "TST_test.admin").addRole("TST_user,sysadmin")
1134                                 .setMailAddress("noreply@salome-platform.org");
1135                 uprop.disableCheck();
1136
1137                 getHibernateTemplate().saveOrUpdate(new User(uprop));
1138                 getHibernateTemplate().flush();
1139
1140                 Study.Properties sprop = new Study.Properties();
1141                 sprop.setTitle("Test study creation").setManager(anAuthor);
1142                 Scenario.Properties oprop = new Scenario.Properties();
1143                 oprop.setTitle("Test scenario for the created study");
1144
1145                 // Addition of the entered project context
1146                 SimulationContext.Properties cprop = new SimulationContext.Properties();
1147                 // Input of new project context
1148                 cprop.setType(_simulationContextService.selectType("product"))
1149                                 .setValue("Test Simulation Context: Product");
1150                 Study study = _scenarioService.createStudy(sprop, oprop, cprop);
1151
1152                 Assert.assertNotNull(study);
1153                 Assert.assertTrue(study.getIndex() > 0);
1154
1155                 rollbackNestedTransaction();
1156                 LOG.debug(">>>>> END testCreateStudy()");
1157         }
1158
1159         /**
1160          * Test study creation.<BR>
1161          * <B>Description :</B> <BR>
1162          * <i>Create a study.</i><BR>
1163          * <B>Action : </B><BR>
1164          * <i>1. call the method for a not existing product.</i><BR>
1165          * <i>2. call the method for an existing username and an existing product.</i><BR>
1166          * <i>3. call the method for a not existing username expecting an exception.</i><BR>
1167          * <B>Test data : </B><BR>
1168          * <i>no input parameters</i><BR>
1169          * 
1170          * <B>Outcome results:</B><BR>
1171          * <i>
1172          * <ul>
1173          * <li>1: The new study must be created. The new product simulation context must be created.</li>
1174          * <li>2: The new study must be created.</li>
1175          * <li>3: The new study must not be created. Exception must be thrown.</li>
1176          * </ul>
1177          * </i>
1178          * 
1179          * @throws IOException
1180          *             if application configuration loading is failed
1181          * @throws SQLException
1182          *             if application configuration loading is failed
1183          * @throws BusinessException
1184          *             if test data creation is failed
1185          */
1186         @Test(groups = { "study", "sevice", "functional", "business" })
1187         public void testCreateStudyFromPython() throws IOException, SQLException,
1188                         BusinessException {
1189                 LOG.debug(">>>>> BEGIN testCreateStudyFromPython()");
1190                 startNestedTransaction();
1191
1192                 HibernateTemplate ht = getHibernateTemplate();
1193
1194                 Database.getInstance().reset();
1195                 _projectSettings.getAllSteps().clear(); // Clear config to be able to load it again
1196                 _projectSettings.configure("classpath:test/som.xml");
1197
1198                 // Create a test user
1199                 User goodUser = TestEntitiesGenerator.getTestUser("goodUser");
1200                 _userDAO.create(goodUser);
1201                 SimulationContextType prodtype = _simulationContextService
1202                                 .selectType("product");
1203                 Assert
1204                                 .assertNotNull(prodtype,
1205                                                 "Simulation context type 'product' must be created in the database.");
1206
1207                 String productName = "New Test Product " + new Date().toString();
1208
1209                 ht.flush();
1210                 ht.clear();
1211                 long studyId1 = _scenarioService.createStudy("goodUser",
1212                                 "Test Study 1", productName, "Test description");
1213                 Assert.assertTrue(studyId1 > 0);
1214
1215                 ht.flush();
1216                 ht.clear();
1217                 try {
1218                         _scenarioService.createStudy("badbadUser", "Test Study 2",
1219                                         productName, "Test description");
1220                         Assert.fail("Study must not be created for not existing user.");
1221                 } catch (InvalidPropertyException ipe) {
1222                         LOG.debug("Expected exception: " + ipe.getMessage());
1223                 }
1224
1225                 ht.flush();
1226                 ht.clear();
1227                 long studyId3 = _scenarioService.createStudy("goodUser",
1228                                 "Test Study 3", productName, "Test description");
1229                 Assert.assertTrue(studyId3 > 0);
1230
1231                 // Check that the simulation context is the same
1232                 Study study1 = _studyService.selectStudy(studyId1);
1233                 Study study3 = _studyService.selectStudy(studyId3);
1234                 Assert.assertEquals(study1.SimulationContextIterator().next(), study3
1235                                 .SimulationContextIterator().next());
1236
1237                 // Check the title of the created scenario
1238                 String scTitle = study1.getScenarii()[0].getTitle();
1239                 Assert.assertEquals(scTitle, I18nUtils
1240                                 .getMessageLocaleDefault("label.scenario")
1241                                 + " 1");
1242                 Assert.assertFalse(scTitle.equals("label.scenario 1"));
1243
1244                 rollbackNestedTransaction();
1245                 LOG.debug(">>>>> END testCreateStudyFromPython()");
1246         }
1247
1248         /**
1249          * Test study content copy.<BR>
1250          * <B>Description :</B> <BR>
1251          * <i>Create a study.</i><BR>
1252          * <B>Action : </B><BR>
1253          * <i>1. call the method for a not existing source study.</i><BR>
1254          * <i>2. call the method for a not existing source scenario with not evolving step.</i><BR>
1255          * <i>3. call the method for a not existing source scenario with evolving step.</i><BR>
1256          * <i>4. call the method for an existing source scenario with evolving step.</i><BR>
1257          * <B>Test data : </B><BR>
1258          * <i>no input parameters</i><BR>
1259          * 
1260          * <B>Outcome results:</B><BR>
1261          * <i>
1262          * <ul>
1263          * <li>1: Exception must be thrown.</li>
1264          * <li>2: The study content must be copied.</li>
1265          * <li>3: Exception must be thrown.</li>
1266          * <li>4: The study content must be copied.</li>
1267          * </ul>
1268          * </i>
1269          * 
1270          * @throws IOException
1271          *             if application configuration loading is failed
1272          * @throws SQLException
1273          *             if application configuration loading is failed
1274          * @throws BusinessException
1275          *             if test data creation is failed
1276          */
1277         @Test(groups = { "study", "sevice", "functional", "business" })
1278         public void testCopyStudyContent() throws IOException, SQLException,
1279                         BusinessException {
1280                 LOG.debug(">>>>> BEGIN testCopyStudyContent()");
1281                 startNestedTransaction();
1282
1283                 HibernateTemplate ht = getHibernateTemplate();
1284
1285                 Database.getInstance().reset();
1286                 _projectSettings.getAllSteps().clear(); // Clear config to be able to load it again
1287                 _projectSettings.configure("classpath:test/som.xml");
1288
1289                 User goodUser = TestEntitiesGenerator.getTestUser("GoodUser");
1290                 _userDAO.create(goodUser);
1291                 User otherUser = TestEntitiesGenerator.getTestUser("otherUser");
1292                 _userDAO.create(otherUser);
1293
1294                 // Create private study
1295                 Study aStudy = TestEntitiesGenerator.getTestStudy(goodUser);
1296                 aStudy.setTitle("0.This is private study");
1297                 Long studyId = _studyDAO.create(aStudy);
1298
1299                 // Add a scenario to the study
1300                 Scenario scen = TestEntitiesGenerator.getTestScenario(aStudy);
1301                 _scenarioDAO.create(scen);
1302                 ht.flush();
1303                 // Add a second scenario to the study
1304                 scen = TestEntitiesGenerator.getTestScenario(aStudy);
1305                 Long aScenId = _scenarioDAO.create(scen);
1306                 ht.flush();
1307
1308                 // Add a validation cycle with otherUser as a reviewer
1309                 ValidationCycle.Properties vprop = new ValidationCycle.Properties();
1310                 DocumentType dtype = _documentTypeService.selectType("minutes");
1311                 vprop.setDocumentType(dtype);
1312                 vprop.setActor(ValidationStep.REVIEW, otherUser);
1313                 ValidationCycle cycle = new ValidationCycle(aStudy, vprop);
1314                 _validationCycleDAO.create(cycle);
1315                 ValidationCycleRelation link = cycle.getContext();
1316                 aStudy.addRelation(link);
1317                 ht.flush();
1318
1319                 // Add documents to the first study activity
1320                 // Add a converts relations
1321                 Map<Integer, org.splat.som.Step> stSteps = _projectElementService
1322                                 .getStepsMap(aStudy);
1323                 org.splat.som.Step aStep = stSteps.get(1);
1324                 Publication pub1 = addDoc(aStudy, aStep, "document1", dtype);
1325                 Publication pub2 = addDoc(aStudy, aStep, "document2", dtype);
1326                 Publication pub3 = addDoc(aStudy, aStep, "document3", dtype);
1327                 ht.flush();
1328
1329                 LOG.debug("pub1 version doc: " + pub1.value().getTitle() + " ["
1330                                 + pub1.value().getReference() + "]" + " ["
1331                                 + pub1.value().getRid() + "]");
1332                 LOG.debug("pub2 version doc: " + pub2.value().getTitle() + " ["
1333                                 + pub2.value().getReference() + "]" + " ["
1334                                 + pub2.value().getRid() + "]");
1335                 LOG.debug("pub3 version doc: " + pub3.value().getTitle() + " ["
1336                                 + pub3.value().getReference() + "]" + " ["
1337                                 + pub3.value().getRid() + "]");
1338
1339                 ht.update(aStudy);
1340
1341                 ht.flush();
1342                 LOG.debug("Before versioning:");
1343                 for (Publication doc : _projectElementService.getFirstStep(aStudy)
1344                                 .getAllDocuments()) {
1345                         LOG.debug("Study doc: " + doc.value().getTitle() + " ["
1346                                         + doc.value().getReference() + "]" + " ["
1347                                         + doc.value().getRid() + "]");
1348                 }
1349                 // Add a version relations
1350                 Publication pub31 = version(pub3);
1351                 ht.flush();
1352                 //
1353                 // LOG.debug("pub31 version doc: " + pub31.value().getTitle() + " ["
1354                 // + pub31.value().getReference() + "]" + " ["
1355                 // + pub31.value().getRid() + "]");
1356                 // ht.saveOrUpdate(aStudy);
1357
1358                 // LOG.debug("After versioning:");
1359                 // for (Publication doc : aStudy.getDocums()) {
1360                 // LOG.debug("Study doc: " + doc.value().getTitle() + " ["
1361                 // + doc.value().getReference() + "]" + " ["
1362                 // + doc.value().getRid() + "]");
1363                 // }
1364
1365                 // Add documents to the first scenario activity
1366                 Map<Integer, org.splat.som.Step> scSteps = _projectElementService
1367                                 .getStepsMap(scen);
1368                 aStep = scSteps.get(2);
1369                 Publication spub1 = addDoc(scen, aStep, "sdocument1", dtype);
1370                 Publication spub2 = addDoc(scen, aStep, "sdocument2", dtype);
1371                 Publication spub3 = addDoc(scen, aStep, "sdocument3", dtype);
1372                 LOG.debug("spub1 version doc: " + spub1.value().getTitle() + " ["
1373                                 + spub1.value().getReference() + "]" + " ["
1374                                 + spub1.value().getRid() + "]");
1375                 LOG.debug("spub2 version doc: " + spub2.value().getTitle() + " ["
1376                                 + spub2.value().getReference() + "]" + " ["
1377                                 + spub2.value().getRid() + "]");
1378                 LOG.debug("spub3 version doc: " + spub3.value().getTitle() + " ["
1379                                 + spub3.value().getReference() + "]" + " ["
1380                                 + spub3.value().getRid() + "]");
1381                 ht.flush();
1382
1383                 // Create a scenario document version
1384                 Publication spub31 = version(spub3);
1385                 // LOG.debug("spub31 version doc: " + spub31.value().getTitle() + " ["
1386                 // + spub31.value().getReference() + "]" + " ["
1387                 // + spub31.value().getRid() + "]");
1388                 ht.flush();
1389
1390                 // Add uses relations
1391                 pub2.addDependency(pub1);
1392                 ht.saveOrUpdate(pub2.value());
1393                 pub3.addDependency(pub2);
1394                 ht.saveOrUpdate(pub3.value());
1395
1396                 spub2.addDependency(pub1);
1397                 spub2.addDependency(spub1);
1398                 spub2.addDependency(pub2);
1399                 spub2.addDependency(pub3);
1400                 ht.saveOrUpdate(spub2.value());
1401                 spub3.addDependency(spub2);
1402                 ht.saveOrUpdate(spub3.value());
1403                 spub31.addDependency(pub31);
1404                 ht.saveOrUpdate(spub31.value());
1405                 ht.flush();
1406
1407                 // Create target study1
1408                 Study aStudy1 = TestEntitiesGenerator.getTestStudy(goodUser);
1409                 aStudy1.setTitle("1.This is a target study1");
1410                 aStudy1.setReference("tst1");
1411                 Long studyId1 = _studyDAO.create(aStudy1);
1412
1413                 // Add a scenario to the study
1414                 Scenario scen1 = TestEntitiesGenerator.getTestScenario(aStudy1);
1415                 _scenarioDAO.create(scen1);
1416                 ht.flush();
1417
1418                 // Create target study2
1419                 Study aStudy2 = TestEntitiesGenerator.getTestStudy(goodUser);
1420                 aStudy2.setTitle("2.This is a target study2");
1421                 aStudy2.setReference("tst2");
1422                 Long studyId2 = _studyDAO.create(aStudy2);
1423
1424                 // Add a scenario to the study
1425                 Scenario scen2 = TestEntitiesGenerator.getTestScenario(aStudy2);
1426                 _scenarioDAO.create(scen2);
1427                 ht.flush();
1428                 ht.clear();
1429
1430                 // //////////////////// TEST CALL /////////////////////////////////////
1431                 // 1. call the method for a not existing source study.
1432                 try {
1433                         _scenarioService.copyStudyContent(-1, -1, -1, -1);
1434                         Assert.fail("Exception must be thrown for not existing study id.");
1435                 } catch (InvalidParameterException e) {
1436                         LOG.debug("Expected exception: " + e.getClass().getSimpleName()
1437                                         + ": " + e.getMessage());
1438                 }
1439
1440                 ht.flush();
1441                 ht.clear();
1442
1443                 // 2. call the method for a not existing source scenario with not evolving step.
1444                 _scenarioService.copyStudyContent(studyId, -1, 1, studyId1);
1445
1446                 ht.flush();
1447                 ht.clear();
1448
1449                 aStudy = _studyService.selectStudy(studyId);
1450                 aStudy1 = _studyService.selectStudy(studyId1);
1451                 for (Publication pub : aStudy.getDocums()) {
1452                         // Find the same document in the created copy of the study
1453                         Publication found = null;
1454                         for (Publication newPub : aStudy1.getDocums()) {
1455                                 if (pub.value().getTitle().equals(newPub.value().getTitle())
1456                                                 && pub.value().getType().equals(
1457                                                                 newPub.value().getType())) {
1458                                         found = newPub;
1459                                         break;
1460                                 }
1461                         }
1462                         Assert.assertNotNull(found, "The document "
1463                                         + pub.value().getTitle() + "is not copied");
1464                         // Check that all files are copied (source and attached)
1465                 }
1466
1467                 // 3. call the method for a not existing source scenario with evolving step.
1468                 try {
1469                         _scenarioService.copyStudyContent(studyId, -1, 2, studyId2);
1470                         Assert
1471                                         .fail("Exception must be thrown for not existing scenario id and evolving step.");
1472                 } catch (InvalidParameterException e) {
1473                         LOG.debug("Expected exception: " + e.getClass().getSimpleName()
1474                                         + ": " + e.getMessage());
1475                 }
1476
1477                 ht.flush();
1478                 ht.clear();
1479
1480                 // 4. call the method for an existing source scenario with evolving step.
1481                 _scenarioService.copyStudyContent(studyId, aScenId, 9, studyId2);
1482                 ht.flush();
1483
1484                 rollbackNestedTransaction();
1485                 LOG.debug(">>>>> END testCopyStudyContent()");
1486         }
1487
1488         /**
1489          * Test assigning a simulation context to a study.<BR>
1490          * <B>Description :</B> <BR>
1491          * <i>Create a study and assign a simulation context to it.</i><BR>
1492          * <B>Action : </B><BR>
1493          * <i>1. call the method for not existing study id.</i><BR>
1494          * <i>2. call the method for not existing context type and context value.</i><BR>
1495          * <i>3. call the method for existing context type and context value.</i><BR>
1496          * <i>4. call the method for existing context type and not existing context value.</i><BR>
1497          * <i>5. call the method for empty context type.</i><BR>
1498          * <i>6. call the method for empty context value.</i><BR>
1499          * <B>Test data : </B><BR>
1500          * <i>no input parameters</i><BR>
1501          * 
1502          * <B>Outcome results:</B><BR>
1503          * <i>
1504          * <ul>
1505          * <li>1: Exception must be thrown.</li>
1506          * <li>2: The new context type and value must be created. The new context must be assigned to the study first step.</li>
1507          * <li>3: The existing context must be assigned to the study first step.</li>
1508          * <li>4: The new context value must be created. The new context must be assigned to the study first step.</li>
1509          * <li>5: Exception must be thrown.</li>
1510          * <li>6: Exception must be thrown.</li>
1511          * </ul>
1512          * </i>
1513          * 
1514          * @throws IOException
1515          *             if application configuration loading is failed
1516          * @throws SQLException
1517          *             if application configuration loading is failed
1518          * @throws BusinessException
1519          *             if test data creation is failed
1520          */
1521         @Test(groups = { "study", "sevice", "functional", "business" })
1522         public void testAssignStudyContextFromPython() throws IOException,
1523                         SQLException, BusinessException {
1524                 LOG.debug(">>>>> BEGIN testAssignStudyContextFromPython()");
1525                 startNestedTransaction();
1526
1527                 HibernateTemplate ht = getHibernateTemplate();
1528
1529                 Database.getInstance().reset();
1530                 _projectSettings.getAllSteps().clear(); // Clear config to be able to load it again
1531                 _projectSettings.configure("classpath:test/som.xml");
1532
1533                 // Create a test user
1534                 User goodUser = TestEntitiesGenerator.getTestUser("goodUser");
1535                 _userDAO.create(goodUser);
1536                 SimulationContextType prodtype = _simulationContextService
1537                                 .selectType("product");
1538                 Assert
1539                                 .assertNotNull(prodtype,
1540                                                 "Simulation context type 'product' must be created in the database.");
1541
1542                 String productName = "New Test Product " + new Date().toString();
1543
1544                 ht.flush();
1545                 ht.clear();
1546                 long studyId1 = _scenarioService.createStudy("goodUser",
1547                                 "Test Study 1", productName, "Test description");
1548                 Assert.assertTrue(studyId1 > 0);
1549
1550                 ht.flush();
1551                 ht.clear();
1552
1553                 // //////// START OF TESTS
1554                 // 1. call the method for not existing study id.</i><BR>
1555                 try {
1556                         _scenarioService.assignStudyContext(-1L, "new context type",
1557                                         "new context value");
1558                         Assert.fail("Not existing study must not be found.");
1559                 } catch (InvalidPropertyException ipe) {
1560                         LOG.debug("Expected exception: " + ipe.getMessage());
1561                 }
1562
1563                 // 2. call the method for not existing context type and context value.</i><BR>
1564                 _scenarioService.assignStudyContext(studyId1, "new context type",
1565                                 "new context value");
1566
1567                 ht.flush();
1568                 ht.clear();
1569
1570                 // Check the assigned simulation context
1571                 checkCtx(studyId1, "new context type", "new context value");
1572
1573                 // 3. call the method for existing context type and context value.</i><BR>
1574                 _scenarioService.assignStudyContext(studyId1, "new context type",
1575                                 "new context value");
1576
1577                 ht.flush();
1578                 ht.clear();
1579
1580                 // Check the assigned simulation context
1581                 checkCtx(studyId1, "new context type", "new context value");
1582
1583                 // 4. call the method for existing context type and not existing context value.</i><BR>
1584                 _scenarioService.assignStudyContext(studyId1, "new context type",
1585                                 "new context value1");
1586
1587                 ht.flush();
1588                 ht.clear();
1589
1590                 // Check the assigned simulation context
1591                 checkCtx(studyId1, "new context type", "new context value1");
1592
1593                 // 5. call the method for empty context type.</i><BR>
1594                 try {
1595                         _scenarioService.assignStudyContext(studyId1, "",
1596                                         "new context value");
1597                         Assert.fail("Empty context type name must be forbidden.");
1598                 } catch (InvalidPropertyException ipe) {
1599                         LOG.debug("Expected exception: " + ipe.getMessage());
1600                 }
1601                 // 6. call the method for empty context value.</i><BR>
1602                 try {
1603                         _scenarioService.assignStudyContext(studyId1, "new context type",
1604                                         "");
1605                         Assert.fail("Empty context value must be forbidden.");
1606                 } catch (InvalidPropertyException ipe) {
1607                         LOG.debug("Expected exception: " + ipe.getMessage());
1608                 }
1609
1610                 rollbackNestedTransaction();
1611                 LOG.debug(">>>>> END testAssignStudyContextFromPython()");
1612         }
1613
1614         /**
1615          * Test getting a study scenarios DTO list.<BR>
1616          * <B>Description :</B> <BR>
1617          * <i>Create a study and get its scenarios DTO list.</i><BR>
1618          * <B>Action : </B><BR>
1619          * <i>1. call the method for not existing study id.</i><BR>
1620          * <i>2. call the method for a study with one scenario.</i><BR>
1621          * <i>3. call the method for a study with several scenarios.</i><BR>
1622          * <B>Test data : </B><BR>
1623          * <i>no input parameters</i><BR>
1624          * 
1625          * <B>Outcome results:</B><BR>
1626          * <i>
1627          * <ul>
1628          * <li>1: The returned list of DTO must be empty.</li>
1629          * <li>2: The returned list of DTO must contain one scenario DTO.</li>
1630          * <li>3: The returned list of DTO must contain several scenario DTOs.</li>
1631          * </ul>
1632          * </i>
1633          * 
1634          * @throws IOException
1635          *             if application configuration loading is failed
1636          * @throws SQLException
1637          *             if application configuration loading is failed
1638          * @throws BusinessException
1639          *             if test data creation is failed
1640          */
1641         @Test(groups = { "study", "sevice", "functional", "business" })
1642         public void testGetStudyScenarios() throws IOException, SQLException,
1643                         BusinessException {
1644                 LOG.debug(">>>>> BEGIN testGetStudyScenarios()");
1645                 startNestedTransaction();
1646
1647                 HibernateTemplate ht = getHibernateTemplate();
1648
1649                 Database.getInstance().reset();
1650                 _projectSettings.getAllSteps().clear(); // Clear config to be able to load it again
1651                 _projectSettings.configure("classpath:test/som.xml");
1652
1653                 // Create a test user
1654                 User goodUser = TestEntitiesGenerator.getTestUser("goodUser");
1655                 _userDAO.create(goodUser);
1656                 Study study = TestEntitiesGenerator.getTestStudy(goodUser);
1657                 long studyId1 = _studyDAO.create(study);
1658                 ht.flush();
1659                 Scenario scen = TestEntitiesGenerator.getTestScenario(study,
1660                                 "test scen11");
1661                 long id11 = _scenarioDAO.create(scen);
1662                 ht.flush();
1663                 study = TestEntitiesGenerator.getTestStudy(goodUser);
1664                 long studyId2 = _studyDAO.create(study);
1665                 ht.flush();
1666                 scen = TestEntitiesGenerator.getTestScenario(study, "test scen21");
1667                 long id21 = _scenarioDAO.create(scen);
1668                 ht.flush();
1669                 scen = TestEntitiesGenerator.getTestScenario(study, "test scen22");
1670                 long id22 = _scenarioDAO.create(scen);
1671                 ht.flush();
1672                 scen = TestEntitiesGenerator.getTestScenario(study, "test scen23");
1673                 long id23 = _scenarioDAO.create(scen);
1674                 ht.flush();
1675                 ht.clear();
1676
1677                 // //////// START OF TESTS
1678                 // 1. call the method for not existing study id.
1679                 List<ScenarioDTO> scens = _scenarioService.getStudyScenarios(-1L);
1680
1681                 Assert.assertNotNull(scens);
1682                 Assert.assertTrue(scens.isEmpty());
1683
1684                 // 2. call the method for a study with one scenario.
1685                 scens = _scenarioService.getStudyScenarios(studyId1);
1686
1687                 ht.flush();
1688                 ht.clear();
1689                 Assert.assertNotNull(scens);
1690                 Assert.assertEquals(scens.size(), 1);
1691                 Assert.assertEquals(scens.get(0).getIndex().longValue(), id11);
1692                 Assert.assertEquals(scens.get(0).getTitle(), "test scen11");
1693
1694                 // 3. call the method for a study with several scenarios.
1695                 scens = _scenarioService.getStudyScenarios(studyId2);
1696                 Assert.assertEquals(scens.size(), 3);
1697                 Assert.assertEquals(scens.get(0).getIndex().longValue(), id21);
1698                 Assert.assertEquals(scens.get(0).getTitle(), "test scen21");
1699                 Assert.assertEquals(scens.get(1).getIndex().longValue(), id22);
1700                 Assert.assertEquals(scens.get(1).getTitle(), "test scen22");
1701                 Assert.assertEquals(scens.get(2).getIndex().longValue(), id23);
1702                 Assert.assertEquals(scens.get(2).getTitle(), "test scen23");
1703
1704                 ht.flush();
1705                 ht.clear();
1706
1707                 rollbackNestedTransaction();
1708                 LOG.debug(">>>>> END testGetStudyScenarios()");
1709         }
1710
1711         /**
1712          * Check if the context is assigned to the study.
1713          * 
1714          * @param studyId1
1715          *            the study id
1716          * @param ctxType
1717          *            the context type name
1718          * @param ctxValue
1719          *            the context value
1720          */
1721         private void checkCtx(final long studyId1, final String ctxType,
1722                         final String ctxValue) {
1723                 // Check the assigned simulation context
1724                 Study study1 = _studyService.selectStudy(studyId1);
1725                 Iterator<SimulationContext> it = study1.SimulationContextIterator();
1726                 SimulationContext ctx;
1727                 boolean isFound = false;
1728                 while ((!isFound) && it.hasNext()) {
1729                         ctx = it.next();
1730                         isFound = ctx.getType().getName().equals(ctxType)
1731                                         && ctx.getValue().equals(ctxValue);
1732                 }
1733                 Assert.assertTrue(isFound, "Context must be assigned to the study.");
1734         }
1735 }