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