Salome HOME
Creation of a new study from an existing one is implemented.
[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.ProjectElement;
31 import org.splat.dal.bo.som.Publication;
32 import org.splat.dal.bo.som.Scenario;
33 import org.splat.dal.bo.som.SimulationContext;
34 import org.splat.dal.bo.som.SimulationContextType;
35 import org.splat.dal.bo.som.Study;
36 import org.splat.dal.bo.som.UsedByRelation;
37 import org.splat.dal.bo.som.UsesRelation;
38 import org.splat.dal.bo.som.ValidationCycle;
39 import org.splat.dal.bo.som.ValidationCycleRelation;
40 import org.splat.dal.bo.som.ValidationStep;
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                 // Do test checkin
462                 _scenarioService.checkin(scenarioId, userId, stepsToCheckin);
463
464                 _scenarioDAO.flush();
465                 // Check that scenario is no more marked as checked out
466                 aScen = _scenarioDAO.get(scenarioId);
467                 Assert.assertFalse(aScen.isCheckedout(),
468                                 "Scenario is still marked as checked out after checkin.");
469                 boolean modifDatesChecked = false;
470                 // Check that new document versions are created for checked in documents
471                 for (StepDTO step : stepsToCheckin) {
472                         for (DocumentDTO docDTO : step.getDocs()) {
473                                 if ((docDTO.getId() != 0) && (docDTO.getId() != null)) {
474                                         boolean found = false;
475                                         Document prevDoc = null;
476                                         Document curDoc = null;
477                                         Publication newPub = null;
478                                         for (Publication pub : aScen.getDocums()) {
479                                                 prevDoc = pub.value().getPreviousVersion();
480                                                 if (prevDoc != null) {
481                                                         found = (prevDoc.getIndex() == docDTO.getId());
482                                                         if (found) { // Found next published version of the checked in document
483                                                                 newPub = pub;
484                                                                 break;
485                                                         }
486                                                 }
487                                                 if (pub.value().getIndex() == docDTO.getId()) {
488                                                         // Document version was not changed, old document is still published
489                                                         curDoc = pub.value();
490                                                         break;
491                                                 }
492                                         }
493                                         Assert.assertTrue(found || (curDoc != null),
494                                                         "New version or new attached file of the existing checked in document \""
495                                                                         + docDTO.getTitle() + "\" (id="
496                                                                         + docDTO.getId()
497                                                                         + ") is not found in the scenario.");
498                                         // If previous version is found then the format must be the same
499                                         String newFormat = docDTO.getFiles().get(0).getPath()
500                                                         .substring(
501                                                                         docDTO.getFiles().get(0).getPath()
502                                                                                         .lastIndexOf('.') + 1);
503                                         if (found) {
504                                                 Assert.assertEquals(prevDoc.getFormat(), newFormat,
505                                                                 "Formats of versions must be same");
506                                                 Assert.assertFalse(aScen.publishes(prevDoc));
507                                                 // Check that presentation of the previous version is removed
508                                                 checkFiles(docDTO, newPub);
509
510                                                 // Formats of files are new if they are according to the document's type on the study step
511                                                 if ("py".equals(prevDoc.getFormat())
512                                                                 && "geometry".equals(prevDoc.getType()
513                                                                                 .getName())) {
514                                                         Assert.assertEquals(newPub.value().getFormat(),
515                                                                         "brep");
516                                                         Assert.assertEquals(newPub.getSourceFile()
517                                                                         .getFormat(), "brep");
518                                                         Assert.assertEquals(newPub.getSourceFile()
519                                                                         .getRelativePath().substring(
520                                                                                         newPub.getSourceFile()
521                                                                                                         .getRelativePath()
522                                                                                                         .lastIndexOf('.') + 1),
523                                                                         "brep");
524                                                 }
525
526                                                 // Check that uses relations are copied correctly
527
528                                                 // 1. Get all uses relations of the previous document version
529                                                 for (Relation rel : prevDoc
530                                                                 .getRelations(UsesRelation.class)) {
531                                                         Document used = ((UsesRelation) rel).getTo();
532                                                         // 2.1. Get the latest version of the document published in this scenario
533                                                         Publication toBeUsed = aScen.getPublication(used);
534                                                         if (toBeUsed == null) {
535                                                                 // Find the latest published version
536                                                                 for (Publication lastPub : aScen.getDocums()) {
537                                                                         if ((lastPub.value().getPreviousVersion() != null)
538                                                                                         && (lastPub.value()
539                                                                                                         .getPreviousVersion()
540                                                                                                         .getIndex() == used
541                                                                                                         .getIndex())) {
542                                                                                 toBeUsed = lastPub;
543                                                                                 break;
544                                                                         }
545                                                                 }
546                                                         }
547                                                         if ((toBeUsed != null) && (!toBeUsed.isOutdated())) {
548                                                                 // 2.2. For each used document check that its latest not outdated version
549                                                                 // is used by the new checked in document version.
550                                                                 checkUsesRelation(newPub, toBeUsed);
551                                                         }
552                                                 }
553                                                 // 1. Get all usedBy relations of the previous document version
554                                                 for (Relation rel : prevDoc
555                                                                 .getRelations(UsedByRelation.class)) {
556                                                         Document using = ((UsedByRelation) rel).getTo();
557                                                         // Check that not checked in dependent documents became outdated
558                                                         Publication usingPub = aScen.getPublication(using);
559                                                         if (usingPub != null) { // if the document using the old version is still published
560                                                                 Assert.assertTrue(usingPub.isOutdated(),
561                                                                                 "Not checked in dependent document "
562                                                                                                 + using.getTitle() + " ("
563                                                                                                 + using.getType().getName()
564                                                                                                 + ") must become outdated.");
565                                                         }
566                                                 }
567                                         } else {
568                                                 // Otherwise the new file format must differ from the previous one
569                                                 // and the new file must be attached to the same document
570                                                 org.splat.dal.bo.som.File attFile = curDoc
571                                                                 .getAttachedFile(newFormat);
572                                                 Assert.assertNotNull(attFile, "File "
573                                                                 + docDTO.getFiles().get(0).getPath()
574                                                                 + " must be attached to the document "
575                                                                 + docDTO.getTitle() + "#" + docDTO.getId());
576                                                 Assert.assertTrue(attFile.asFile().exists(), "File "
577                                                                 + docDTO.getFiles().get(0).getPath()
578                                                                 + " attached to the document "
579                                                                 + docDTO.getTitle() + "#" + docDTO.getId()
580                                                                 + " doesn't exist");
581                                                 LOG.debug("Source format: " + curDoc.getFormat()
582                                                                 + ", new format: " + newFormat);
583                                                 // Check that attachment with the same format is not duplicated.
584                                                 int attachNb = 0;
585                                                 for (Relation conv : curDoc
586                                                                 .getRelations(ConvertsRelation.class)) {
587                                                         if (newFormat.equals(((ConvertsRelation) conv)
588                                                                         .getTo().getFormat())) {
589                                                                 attachNb++;
590                                                         }
591                                                 }
592                                                 Assert
593                                                                 .assertEquals(attachNb, 1,
594                                                                                 "Attachment with the same format must be only one.");
595
596                                                 // Check that the attached file date is updated
597                                                 if (dates.containsKey(attFile.getIndex())) {
598                                                         Assert
599                                                                         .assertTrue(attFile.getDate().compareTo(
600                                                                                         dates.get(attFile.getIndex())) > 0,
601                                                                                         "Attachment modification date is not updated.");
602                                                         modifDatesChecked = true;
603                                                 }
604                                         }
605
606                                 } else {
607                                         // Check that new documents are created for new data
608                                         boolean found = false;
609                                         Publication newPub = null;
610                                         for (Publication pub : aScen.getDocums()) {
611                                                 if (pub.value().getPreviousVersion() == null) {
612                                                         found = (pub.value().getTitle().startsWith(pub
613                                                                         .value().getType().getName()));
614                                                         if (found) { // Found next published version of the checked in document
615                                                                 String fcontent = Files.readFile(pub
616                                                                                 .getSourceFile().asFile());
617                                                                 found = fcontent.contains(docDTO.getTitle());
618                                                                 if (found) {
619                                                                         LOG
620                                                                                         .debug("Found new document with generated title: "
621                                                                                                         + pub.value().getTitle());
622                                                                         newPub = pub;
623                                                                         break;
624                                                                 }
625                                                         }
626                                                 }
627                                         }
628                                         Assert.assertTrue(found,
629                                                         "New document is not created for checked in document \""
630                                                                         + docDTO.getTitle() + "\".");
631
632                                         // Check that uses relations are created correctly
633                                         Assert.assertTrue(newPub.value().getTitle().startsWith(
634                                                         newPub.value().getType().getName() + "_"),
635                                                         "Document title newPub.value().getTitle() must start with "
636                                                                         + newPub.value().getType().getName() + "_");
637
638                                         // 1. Find the document type used by this document type
639                                         Set<DocumentType> usedTypes = newPub.value().getType()
640                                                         .getDefaultUses();
641                                         // 2. Find documents of used types in the current study step and previous study steps
642                                         for (Publication pub : aScen.getDocums()) {
643                                                 if ((pub.getStep().getNumber() <= step.getNumber())
644                                                                 && (!pub.isOutdated())
645                                                                 && usedTypes.contains(pub.value().getType())) {
646                                                         // 3. Check that there is uses relation to the found document
647                                                         // if it is not outdated.
648                                                         checkUsesRelation(newPub, pub);
649                                                 }
650                                         }
651
652                                         // Check that files are moved correctly
653                                         checkFiles(docDTO, newPub);
654                                 }
655                         }
656                 }
657
658                 Assert
659                                 .assertTrue(
660                                                 modifDatesChecked,
661                                                 "No modification date is checked because no files were attached when attachment with same extension already exists.");
662
663                 // ///////////////////////////////////////////////////////////
664                 // Call checkin method for a not existing id.
665                 try {
666                         _scenarioService.checkin(-1, userId, stepsToCheckin);
667                         Assert
668                                         .fail("Check in for scenario with not existing id must be failed.");
669                 } catch (Exception e) {
670                         LOG.debug("Expected exception is thrown: "
671                                         + e.getClass().getSimpleName() + ": " + e.getMessage());
672                 }
673
674                 // Test checkin with empty list of steps
675                 stepsToCheckin.clear();
676                 _scenarioService.checkin(scenarioId, userId, stepsToCheckin);
677
678                 rollbackNestedTransaction();
679                 LOG.debug(">>>>> END testCheckin()");
680         }
681
682         /**
683          * Check if there is uses relation from the newPub to pub.
684          * 
685          * @param newPub
686          *            the new publication
687          * @param pub
688          *            the publication to be used
689          */
690         private void checkUsesRelation(final Publication newPub,
691                         final Publication pub) {
692                 boolean uses = false;
693                 boolean usesExist = false;
694                 for (Publication usesPub : newPub.getRelations(UsesRelation.class)) {
695                         usesExist = true;
696                         uses = (usesPub.equals(pub));
697                         if (uses) {
698                                 break;
699                         }
700                 }
701                 Assert.assertTrue(usesExist && uses, "The created document "
702                                 + newPub.value().getTitle() + "("
703                                 + newPub.value().getType().getName() + ")"
704                                 + " has no uses relation to the document "
705                                 + pub.value().getTitle() + "("
706                                 + pub.value().getType().getName() + ")");
707         }
708
709         /**
710          * Check that files are moved correctly.
711          * 
712          * @param docDTO
713          *            checked in document DTO
714          * @param newPub
715          *            the created document publication
716          */
717         private void checkFiles(final DocumentDTO docDTO, final Publication newPub) {
718                 // Check that original files are deleted
719                 for (int j = 0; j < docDTO.getFiles().size(); j++) {
720                         FileDTO fileDTO = docDTO.getFiles().get(j);
721                         Assert.assertFalse(new File(fileDTO.getPath()).exists(), "File"
722                                         + fileDTO.getPath()
723                                         + " was not removed from downloads directory.");
724                         String format = fileDTO.getPath().substring(
725                                         fileDTO.getPath().lastIndexOf('.') + 1);
726                 }
727                 // TODO: Check file by its internal content
728                 Assert.assertTrue(newPub.getSourceFile().exists(), "File "
729                                 + newPub.getSourceFile().asFile().getAbsolutePath()
730                                 + " for the document " + docDTO.getTitle()
731                                 + " was not created.");
732         }
733
734         /**
735          * Prepare a document with a file for check-in.
736          * 
737          * @param stepTo
738          *            step DTO with data for check-in
739          * @param module
740          *            SALOME module name
741          * @param format
742          *            file extension
743          * @param userId
744          *            download directory
745          * @param stepFrom
746          *            checked out stepDTO
747          * @param stepsToCheckin
748          *            DTO for check-in
749          * @throws IOException
750          *             if file creation failed
751          * @return step DTO with data prepared for check-in (stepTo or new if stepTo is null)
752          */
753         private StepDTO createDocDTOForModule(final StepDTO stepTo,
754                         final String module, final String format, final long userId,
755                         final StepDTO stepFrom, final List<StepDTO> stepsToCheckin)
756                         throws IOException {
757                 StepDTO stepToCheckin = stepTo;
758                 if (stepToCheckin == null) {
759                         stepToCheckin = new StepDTO();
760                 }
761                 if (module.equals(stepFrom.getModule())) {
762                         stepsToCheckin.add(stepToCheckin);
763                         stepToCheckin.setNumber(stepFrom.getNumber());
764                         for (DocumentDTO doc : stepFrom.getDocs()) {
765                                 if (doc.getFiles().get(0).getState() != 'O') {
766                                         DocumentDTO docToCheckin = stepToCheckin.addDoc(
767                                                         doc.getId(), doc.getTitle());
768                                         for (FileDTO file : doc.getFiles()) {
769                                                 if (file.getPath().endsWith(format)
770                                                                 || (file.getPath().endsWith("py") && (format
771                                                                                 .equals("brep") || format.equals("med")))) {
772                                                         // Create a file in the download directory
773                                                         docToCheckin.addFile(createDownloadedFile(userId,
774                                                                         doc.getTitle() + "_result", format));
775                                                 }
776                                         }
777                                 }
778                         }
779                         // Prepare new data
780                         stepToCheckin.addDoc(0, "newdoc" + stepFrom.getNumber()).addFile(
781                                         createDownloadedFile(userId, "newdoc"
782                                                         + stepFrom.getNumber(), "brep"));
783                 }
784                 return stepToCheckin;
785         }
786
787         /**
788          * Create a file in the user's repository downloads directory.
789          * 
790          * @param userId
791          *            user id
792          * @param name
793          *            file name
794          * @param format
795          *            file extension
796          * @return created file DTO
797          * @throws IOException
798          *             if file creation failed
799          */
800         private FileDTO createDownloadedFile(final long userId, final String name,
801                         final String format) throws IOException {
802                 // Create a file in the download directory
803                 return createDownloadedFile(userId, name + "." + format);
804         }
805
806         /**
807          * Create a file in the user's repository downloads directory.
808          * 
809          * @param userId
810          *            user id
811          * @param fname
812          *            file name
813          * @return created file DTO
814          * @throws IOException
815          *             if file creation failed
816          */
817         private FileDTO createDownloadedFile(final long userId, final String fname)
818                         throws IOException {
819                 // Create a file in the download directory
820                 String filePath = getDownloadPath(userId) + fname;
821                 FileWriter fw = new FileWriter(filePath);
822                 fw.write("Simulation of " + fname + " file for checkin at "
823                                 + new Date());
824                 fw.close();
825                 return new FileDTO(filePath);
826         }
827
828         /**
829          * Create a file.
830          * 
831          * @param fname
832          *            file name
833          * @throws IOException
834          *             if file creation failed
835          */
836         private void createFile(final String fname) throws IOException {
837                 // Create a file in the download directory
838                 LOG.debug("Create file: " + fname);
839                 String filePath = fname;
840                 FileWriter fw = new FileWriter(filePath);
841                 fw.write("Simulation of " + fname + " data file at " + new Date());
842                 fw.close();
843         }
844
845         /**
846          * Get path to the user's downloads directory. The directory is created if it is not exist yet.
847          * 
848          * @param userId
849          *            user id
850          * @return absolute path to downloads directory followed by slash
851          */
852         private String getDownloadPath(final long userId) {
853                 // Prepare download directory
854                 File tmpDir = _repositoryService.getDownloadDirectory(userId);
855                 if (!tmpDir.exists()) {
856                         Assert.assertTrue(tmpDir.mkdir(),
857                                         "Can't create temporary directory: "
858                                                         + tmpDir.getAbsolutePath());
859                 }
860
861                 return tmpDir.getAbsolutePath() + "/";
862         }
863
864         /**
865          * Create a persistent scenario for tests.
866          * 
867          * @return a persistent scenario
868          * @throws InvalidPropertyException
869          *             if an invalid property is used when creating objects
870          * @throws MultiplyDefinedException
871          *             when trying to create an object with already existing id
872          * @throws MissedPropertyException
873          *             if a mandatory property is not defined for an object to be created
874          * @throws IOException
875          *             if document creation is failed
876          * @throws SQLException
877          *             if project settings loading is failed
878          */
879         private long createScenario() throws InvalidPropertyException,
880                         MissedPropertyException, MultiplyDefinedException, IOException,
881                         SQLException {
882                 // Create a scenario for tests
883                 HibernateTemplate ht = getHibernateTemplate();
884
885                 Database.getInstance().reset();
886                 _projectSettings.getAllSteps().clear(); // Clear config to be able to load it again
887                 // Load workflow customization
888                 try {
889                         _projectSettings.configure("classpath:test/som.xml");
890                 } catch (FileNotFoundException e) {
891                         Assert.fail("Can't find som.xml: ", e);
892                 }
893                 List<Step> steps = _stepsConfigService.getStepsOf(Scenario.class);
894                 Assert.assertTrue(steps.size() > 0, "No steps are created.");
895
896                 // Create a test user
897                 User.Properties uprop = new User.Properties();
898                 uprop.setUsername("TST_Username").setName("TST_SimanUnitTestsUser")
899                                 .setFirstName("TST_FirstName").setDisplayName("TST_test.user")
900                                 .addRole("TST_user").setMailAddress(
901                                                 "noreply@salome-platform.org");
902                 uprop.disableCheck();
903                 User anAuthor = new User(uprop);
904                 ht.saveOrUpdate(anAuthor);
905
906                 // Create a test study
907                 Study.Properties stprops = new Study.Properties().setReference(
908                                 "TST_SID_01").setTitle("TST_Study").setManager(anAuthor);
909                 Study aStudy = new Study(stprops);
910                 ht.saveOrUpdate(aStudy);
911
912                 // Create a test scenario
913                 Scenario.Properties sprops = new Scenario.Properties().setTitle(
914                                 "TST_Scenario").setManager(anAuthor).setOwnerStudy(aStudy);
915                 Scenario aScenario = new Scenario(sprops);
916                 aStudy.getScenariiList().add(aScenario);
917                 ht.saveOrUpdate(anAuthor);
918                 ht.saveOrUpdate(aStudy);
919                 ht.saveOrUpdate(aScenario);
920
921                 // Create documents for each scenario step
922                 Document.Properties dprop = new Document.Properties().setAuthor(
923                                 anAuthor).setDate(new Date());
924                 int i = 0;
925                 Publication usedPub = null;
926                 Map<Long, Long> usedMap = new HashMap<Long, Long>();
927                 for (Step step : steps) {
928                         LOG.debug("Create scenario step: " + i);
929
930                         org.splat.som.Step aScStep = new org.splat.som.Step(step, aScenario);
931                         List<DocumentType> dtypes = _documentTypeService
932                                         .selectTypesOf(step);
933                         for (DocumentType dtype : dtypes) {
934                                 // Create a document published in the scenario
935                                 // document<i>: document type[0] - first type used on the step
936                                 // <source-file>.brep
937                                 // <attached-file>.med
938                                 dprop.setName("document" + i++).setType(dtype);
939                                 /*
940                                  * if (step.getNumber() > 3) { dprop.setFormat("med"); } else {
941                                  */dprop.setFormat("py");
942                                 // }
943                                 dprop.setLocalPath(dprop.getName() + "." + dprop.getFormat());
944                                 Publication pub = createDoc(aScenario, aScStep, dprop, "med",
945                                                 false);
946                                 if (usedPub != null) {
947                                         pub.addDependency(usedPub);
948                                         ht.saveOrUpdate(pub.value());
949
950                                         usedMap.put(pub.getIndex(), usedPub.getIndex());
951                                 }
952                                 usedPub = pub;
953
954                                 // Create another document with outdated publication
955                                 dprop.setName("document" + i++).setType(dtype).setFormat("py");
956                                 dprop.setLocalPath(dprop.getName() + "." + dprop.getFormat());
957                                 createDoc(aScenario, aScStep, dprop, "med", true);
958
959                         }
960                         if (dtypes.size() <= 0) {
961                                 LOG.debug("No document types are found for scenario step " + i);
962                         }
963                 }
964
965                 // Check that the scenario and its documents have been created correctly.
966
967                 Assert.assertNotNull(ht.find("from Document"),
968                                 "No documents in the database.");
969                 Assert.assertTrue(ht.find("from Document").size() > 0,
970                                 "No documents in the database.");
971
972                 Assert.assertNotNull(ht.find("from Publication where owner="
973                                 + aScenario.getIndex()), "No publications in the database.");
974                 Assert.assertTrue(
975                                 ht.find("from Publication where owner=" + aScenario.getIndex())
976                                                 .size() > 0, "No publications in the database.");
977
978                 for (Publication p : (List<Publication>) ht
979                                 .find("from Publication where owner=" + aScenario.getIndex())) {
980                         LOG.debug("Publication found: [id=" + p.getIndex() + ", owner="
981                                         + p.getOwner().getIndex() + ", doc=" + p.value().getIndex()
982                                         + "]");
983                         Assert.assertEquals(p.getOwner().getIndex(), aScenario.getIndex(),
984                                         "The publication was not attached to the scenario.");
985                 }
986
987                 // Remove the scenario from the current hibernate session.
988                 ht.evict(aScenario);
989                 // Check that the scenario is created in the database.
990                 Scenario aScen = ht.load(Scenario.class, aScenario.getIndex());
991                 Assert.assertNotNull(aScen, "Scenario was not saved in the database.");
992                 Assert.assertTrue(aScen.getDocums().size() > 0,
993                                 "No publications in the scenario.");
994
995                 Assert.assertTrue(i > 0,
996                                 "More then one document must be in the database");
997
998                 // Check created uses relations
999                 Assert
1000                                 .assertTrue(usedMap.size() > 0,
1001                                                 "Uses relations must be created.");
1002                 boolean foundAny = false;
1003                 for (Long usingId : usedMap.keySet()) {
1004                         for (Publication pub : aScen.getDocums()) {
1005                                 if (pub.getIndex() == usingId) {
1006                                         boolean found = false;
1007                                         for (Publication used : aScen.getDocums()) {
1008                                                 found = (used.getIndex() == usedMap.get(usingId));
1009                                                 if (found) {
1010                                                         break;
1011                                                 }
1012                                         }
1013                                         Assert.assertTrue(found,
1014                                                         "Uses relation was not created in the database.");
1015                                         foundAny = foundAny || found;
1016                                 }
1017                         }
1018                 }
1019                 Assert.assertTrue(foundAny,
1020                                 "No Uses relation was created in the database.");
1021
1022                 return aScenario.getIndex();
1023         }
1024
1025         /**
1026          * Create a document published in the scenario. <BR>
1027          * document:<BR>
1028          * document type[0] - first type used on the step <BR>
1029          * &lt;source-file&gt;.brep <BR>
1030          * &lt;attached-file&gt;.med
1031          * 
1032          * @param aScenario
1033          *            the scenario to add the document to
1034          * @param aScStep
1035          *            scenario step where the document to be published
1036          * @param dprop
1037          *            document properties
1038          * @param attachedFileExt
1039          *            extension of the secon attached (exported) file
1040          * @param isOutdated
1041          *            outdated document flag
1042          * @return the publication of the created document
1043          * @throws IOException
1044          * @throws MultiplyDefinedException
1045          * @throws InvalidPropertyException
1046          * @throws MissedPropertyException
1047          */
1048         private Publication createDoc(final Scenario aScenario,
1049                         final org.splat.som.Step aScStep, final Properties dprop,
1050                         final String attachedFileExt, final boolean isOutdated)
1051                         throws MissedPropertyException, InvalidPropertyException,
1052                         MultiplyDefinedException, IOException {
1053                 // Create a document published in the scenario
1054                 // document<i>: document type[0] - first type used on the step
1055                 // <source-file>.brep
1056                 // <attached-file>.med
1057                 createDownloadedFile(aScenario.getAuthor().getIndex(), dprop
1058                                 .getLocalPath());
1059                 Publication pub = _stepService.createDocument(aScStep, dprop);
1060                 Assert.assertNotNull(pub.getOwner(),
1061                                 "The publication must be attached to the scenario.");
1062                 Assert.assertEquals(pub.getOwner().getIndex(), aScenario.getIndex(),
1063                                 "The publication was not attached to the scenario.");
1064
1065                 if (isOutdated) {
1066                         pub.setIsnew('O');
1067                 }
1068                 aScenario.add(pub);
1069                 HibernateTemplate ht = getHibernateTemplate();
1070                 ht.saveOrUpdate(pub);
1071
1072                 // Attach a file
1073                 createDownloadedFile(aScenario.getAuthor().getIndex(), dprop
1074                                 .getLocalPath().substring(0,
1075                                                 dprop.getLocalPath().lastIndexOf(".") - 1),
1076                                 attachedFileExt);
1077                 ht.save(pub.value());
1078                 ht.saveOrUpdate(_publicationService.attach(pub, attachedFileExt));
1079
1080                 return pub;
1081         }
1082
1083         /**
1084          * Test study creation.<BR>
1085          * <B>Description :</B> <BR>
1086          * <i>Create a study.</i><BR>
1087          * <B>Action : </B><BR>
1088          * <i>1. call the method for a not existing product.</i><BR>
1089          * <i>2. call the method for an existing username and an existing product.</i><BR>
1090          * <i>3. call the method for a not existing username expecting an exception.</i><BR>
1091          * <B>Test data : </B><BR>
1092          * <i>no input parameters</i><BR>
1093          * 
1094          * <B>Outcome results:</B><BR>
1095          * <i>
1096          * <ul>
1097          * <li>1: The new study must be created. The new product simulation context must be created.</li>
1098          * <li>2: The new study must be created.</li>
1099          * <li>3: The new study must not be created. Exception must be thrown.</li>
1100          * </ul>
1101          * </i>
1102          * 
1103          * @throws IOException
1104          *             if application configuration loading is failed
1105          * @throws SQLException
1106          *             if application configuration loading is failed
1107          * @throws BusinessException
1108          *             if test data creation is failed
1109          */
1110         @Test(groups = { "study", "sevice", "functional", "business" })
1111         public void testCreateStudy() throws BusinessException, IOException,
1112                         SQLException {
1113                 LOG.debug(">>>>> BEGIN testCreateStudy()");
1114                 startNestedTransaction();
1115
1116                 Database.getInstance().reset();
1117                 _projectSettings.getAllSteps().clear(); // Clear config to be able to load it again
1118                 _projectSettings.configure("classpath:test/som.xml");
1119
1120                 // Create a test user
1121                 User.Properties uprop = new User.Properties();
1122                 uprop.setUsername("TST_Username").setName("TST_SimanUnitTestsUser")
1123                                 .setFirstName("TST_FirstName").setDisplayName("TST_test.user")
1124                                 .addRole("TST_user").setMailAddress(
1125                                                 "noreply@salome-platform.org");
1126                 uprop.disableCheck();
1127                 User anAuthor = new User(uprop);
1128
1129                 getHibernateTemplate().saveOrUpdate(anAuthor);
1130                 KnowledgeElementType ucase = _knowledgeElementTypeService
1131                                 .selectType("usecase");
1132                 Assert.assertNotNull(ucase,
1133                                 "Knowledge type 'usecase' must be created in the database.");
1134                 SimulationContextType prodtype = _simulationContextService
1135                                 .selectType("product");
1136                 Assert
1137                                 .assertNotNull(prodtype,
1138                                                 "Simulation context type 'product' must be created in the database.");
1139
1140                 // Create admin
1141                 uprop.clear();
1142                 uprop.setUsername("TST_Admin").setName("TST_SimanUnitTestsAdmin")
1143                                 .setFirstName("TST_AdminFirstName").setDisplayName(
1144                                                 "TST_test.admin").addRole("TST_user,sysadmin")
1145                                 .setMailAddress("noreply@salome-platform.org");
1146                 uprop.disableCheck();
1147
1148                 getHibernateTemplate().saveOrUpdate(new User(uprop));
1149                 getHibernateTemplate().flush();
1150
1151                 Study.Properties sprop = new Study.Properties();
1152                 sprop.setTitle("Test study creation").setManager(anAuthor);
1153                 Scenario.Properties oprop = new Scenario.Properties();
1154                 oprop.setTitle("Test scenario for the created study");
1155
1156                 // Addition of the entered project context
1157                 SimulationContext.Properties cprop = new SimulationContext.Properties();
1158                 // Input of new project context
1159                 cprop.setType(_simulationContextService.selectType("product"))
1160                                 .setValue("Test Simulation Context: Product");
1161                 Study study = _scenarioService.createStudy(sprop, oprop, cprop);
1162
1163                 Assert.assertNotNull(study);
1164                 Assert.assertTrue(study.getIndex() > 0);
1165
1166                 rollbackNestedTransaction();
1167                 LOG.debug(">>>>> END testCreateStudy()");
1168         }
1169
1170         /**
1171          * Test study creation.<BR>
1172          * <B>Description :</B> <BR>
1173          * <i>Create a study.</i><BR>
1174          * <B>Action : </B><BR>
1175          * <i>1. call the method for a not existing product.</i><BR>
1176          * <i>2. call the method for an existing username and an existing product.</i><BR>
1177          * <i>3. call the method for a not existing username expecting an exception.</i><BR>
1178          * <B>Test data : </B><BR>
1179          * <i>no input parameters</i><BR>
1180          * 
1181          * <B>Outcome results:</B><BR>
1182          * <i>
1183          * <ul>
1184          * <li>1: The new study must be created. The new product simulation context must be created.</li>
1185          * <li>2: The new study must be created.</li>
1186          * <li>3: The new study must not be created. Exception must be thrown.</li>
1187          * </ul>
1188          * </i>
1189          * 
1190          * @throws IOException
1191          *             if application configuration loading is failed
1192          * @throws SQLException
1193          *             if application configuration loading is failed
1194          * @throws BusinessException
1195          *             if test data creation is failed
1196          */
1197         @Test(groups = { "study", "sevice", "functional", "business" })
1198         public void testCreateStudyFromPython() throws IOException, SQLException,
1199                         BusinessException {
1200                 LOG.debug(">>>>> BEGIN testCreateStudyFromPython()");
1201                 startNestedTransaction();
1202
1203                 HibernateTemplate ht = getHibernateTemplate();
1204
1205                 Database.getInstance().reset();
1206                 _projectSettings.getAllSteps().clear(); // Clear config to be able to load it again
1207                 _projectSettings.configure("classpath:test/som.xml");
1208
1209                 // Create a test user
1210                 User goodUser = TestEntitiesGenerator.getTestUser("goodUser");
1211                 _userDAO.create(goodUser);
1212                 SimulationContextType prodtype = _simulationContextService
1213                                 .selectType("product");
1214                 Assert
1215                                 .assertNotNull(prodtype,
1216                                                 "Simulation context type 'product' must be created in the database.");
1217
1218                 String productName = "New Test Product " + new Date().toString();
1219
1220                 ht.flush();
1221                 ht.clear();
1222                 long studyId1 = _scenarioService.createStudy("goodUser",
1223                                 "Test Study 1", productName, "Test description");
1224                 Assert.assertTrue(studyId1 > 0);
1225
1226                 ht.flush();
1227                 ht.clear();
1228                 try {
1229                         _scenarioService.createStudy("badbadUser", "Test Study 2",
1230                                         productName, "Test description");
1231                         Assert.fail("Study must not be created for not existing user.");
1232                 } catch (InvalidPropertyException ipe) {
1233                         LOG.debug("Expected exception: " + ipe.getMessage());
1234                 }
1235
1236                 ht.flush();
1237                 ht.clear();
1238                 long studyId3 = _scenarioService.createStudy("goodUser",
1239                                 "Test Study 3", productName, "Test description");
1240                 Assert.assertTrue(studyId3 > 0);
1241
1242                 // Check that the simulation context is the same
1243                 Study study1 = _studyService.selectStudy(studyId1);
1244                 Study study3 = _studyService.selectStudy(studyId3);
1245                 Assert.assertEquals(study1.SimulationContextIterator().next(), study3
1246                                 .SimulationContextIterator().next());
1247
1248                 // Check the title of the created scenario
1249                 String scTitle = study1.getScenarii()[0].getTitle();
1250                 Assert.assertEquals(scTitle, I18nUtils
1251                                 .getMessageLocaleDefault("label.scenario")
1252                                 + " 1");
1253                 Assert.assertFalse(scTitle.equals("label.scenario 1"));
1254
1255                 rollbackNestedTransaction();
1256                 LOG.debug(">>>>> END testCreateStudyFromPython()");
1257         }
1258
1259         /**
1260          * Test study content copy.<BR>
1261          * <B>Description :</B> <BR>
1262          * <i>Create a study.</i><BR>
1263          * <B>Action : </B><BR>
1264          * <i>1. call the method for a not existing source study.</i><BR>
1265          * <i>2. call the method for a not existing source scenario with not evolving step.</i><BR>
1266          * <i>3. call the method for a not existing source scenario with evolving step.</i><BR>
1267          * <i>4. call the method for an existing source scenario with evolving step.</i><BR>
1268          * <B>Test data : </B><BR>
1269          * <i>no input parameters</i><BR>
1270          * 
1271          * <B>Outcome results:</B><BR>
1272          * <i>
1273          * <ul>
1274          * <li>1: Exception must be thrown.</li>
1275          * <li>2: The study content must be copied.</li>
1276          * <li>3: Exception must be thrown.</li>
1277          * <li>4: The study content must be copied.</li>
1278          * </ul>
1279          * </i>
1280          * 
1281          * @throws IOException
1282          *             if application configuration loading is failed
1283          * @throws SQLException
1284          *             if application configuration loading is failed
1285          * @throws BusinessException
1286          *             if test data creation is failed
1287          */
1288         @Test(groups = { "study", "sevice", "functional", "business" })
1289         public void testCopyStudyContent() throws IOException, SQLException,
1290                         BusinessException {
1291                 LOG.debug(">>>>> BEGIN testCopyStudyContent()");
1292                 startNestedTransaction();
1293
1294                 HibernateTemplate ht = getHibernateTemplate();
1295
1296                 Database.getInstance().reset();
1297                 _projectSettings.getAllSteps().clear(); // Clear config to be able to load it again
1298                 _projectSettings.configure("classpath:test/som.xml");
1299
1300                 User goodUser = TestEntitiesGenerator.getTestUser("GoodUser");
1301                 _userDAO.create(goodUser);
1302                 User otherUser = TestEntitiesGenerator.getTestUser("otherUser");
1303                 _userDAO.create(otherUser);
1304
1305                 // Create private study
1306                 Study aStudy = TestEntitiesGenerator.getTestStudy(goodUser);
1307                 aStudy.setTitle("0.This is private study");
1308                 Long studyId = _studyDAO.create(aStudy);
1309
1310                 // Add a scenario to the study
1311                 Scenario scen = TestEntitiesGenerator.getTestScenario(aStudy);
1312                 _scenarioDAO.create(scen);
1313                 ht.flush();
1314                 // Add a second scenario to the study
1315                 scen = TestEntitiesGenerator.getTestScenario(aStudy);
1316                 Long aScenId = _scenarioDAO.create(scen);
1317                 ht.flush();
1318
1319                 // Add a validation cycle with otherUser as a reviewer
1320                 ValidationCycle.Properties vprop = new ValidationCycle.Properties();
1321                 DocumentType dtype = _documentTypeService.selectType("minutes");
1322                 vprop.setDocumentType(dtype);
1323                 vprop.setActor(ValidationStep.REVIEW, otherUser);
1324                 ValidationCycle cycle = new ValidationCycle(aStudy, vprop);
1325                 _validationCycleDAO.create(cycle);
1326                 ValidationCycleRelation link = cycle.getContext();
1327                 aStudy.addRelation(link);
1328                 ht.flush();
1329
1330                 // Add documents to the first study activity
1331                 // Add a converts relations
1332                 Map<Integer, org.splat.som.Step> stSteps = _projectElementService
1333                                 .getStepsMap(aStudy);
1334                 org.splat.som.Step aStep = stSteps.get(1);
1335                 Publication pub1 = addDoc(aStudy, aStep, "document1", dtype);
1336                 Publication pub2 = addDoc(aStudy, aStep, "document2", dtype);
1337                 Publication pub3 = addDoc(aStudy, aStep, "document3", dtype);
1338                 ht.flush();
1339
1340                 LOG.debug("pub1 version doc: " + pub1.value().getTitle() + " ["
1341                                 + pub1.value().getReference() + "]" + " ["
1342                                 + pub1.value().getRid() + "]");
1343                 LOG.debug("pub2 version doc: " + pub2.value().getTitle() + " ["
1344                                 + pub2.value().getReference() + "]" + " ["
1345                                 + pub2.value().getRid() + "]");
1346                 LOG.debug("pub3 version doc: " + pub3.value().getTitle() + " ["
1347                                 + pub3.value().getReference() + "]" + " ["
1348                                 + pub3.value().getRid() + "]");
1349
1350                 ht.update(aStudy);
1351
1352                 ht.flush();
1353                 LOG.debug("Before versioning:");
1354                 for (Publication doc : _projectElementService.getFirstStep(aStudy)
1355                                 .getAllDocuments()) {
1356                         LOG.debug("Study doc: " + doc.value().getTitle() + " ["
1357                                         + doc.value().getReference() + "]" + " ["
1358                                         + doc.value().getRid() + "]");
1359                 }
1360                 // // Add a version relations
1361                 // Publication pub31 = version(pub3);
1362                 //
1363                 // LOG.debug("pub31 version doc: " + pub31.value().getTitle() + " ["
1364                 // + pub31.value().getReference() + "]" + " ["
1365                 // + pub31.value().getRid() + "]");
1366                 // ht.saveOrUpdate(aStudy);
1367
1368                 // LOG.debug("After versioning:");
1369                 // for (Publication doc : aStudy.getDocums()) {
1370                 // LOG.debug("Study doc: " + doc.value().getTitle() + " ["
1371                 // + doc.value().getReference() + "]" + " ["
1372                 // + doc.value().getRid() + "]");
1373                 // }
1374
1375                 // Add documents to the first scenario activity
1376                 Map<Integer, org.splat.som.Step> scSteps = _projectElementService
1377                                 .getStepsMap(scen);
1378                 aStep = scSteps.get(2);
1379                 Publication spub1 = addDoc(scen, aStep, "sdocument1", dtype);
1380                 Publication spub2 = addDoc(scen, aStep, "sdocument2", dtype);
1381                 Publication spub3 = addDoc(scen, aStep, "sdocument3", dtype);
1382                 LOG.debug("spub1 version doc: " + spub1.value().getTitle() + " ["
1383                                 + spub1.value().getReference() + "]" + " ["
1384                                 + spub1.value().getRid() + "]");
1385                 LOG.debug("spub2 version doc: " + spub2.value().getTitle() + " ["
1386                                 + spub2.value().getReference() + "]" + " ["
1387                                 + spub2.value().getRid() + "]");
1388                 LOG.debug("spub3 version doc: " + spub3.value().getTitle() + " ["
1389                                 + spub3.value().getReference() + "]" + " ["
1390                                 + spub3.value().getRid() + "]");
1391                 ht.flush();
1392
1393                 // Create a scenario document version
1394                 // Publication spub31 = version(spub3);
1395                 // LOG.debug("spub31 version doc: " + spub31.value().getTitle() + " ["
1396                 // + spub31.value().getReference() + "]" + " ["
1397                 // + spub31.value().getRid() + "]");
1398
1399                 // Add uses relations
1400                 pub2.addDependency(pub1);
1401                 ht.saveOrUpdate(pub2.value());
1402                 pub3.addDependency(pub2);
1403                 ht.saveOrUpdate(pub3.value());
1404
1405                 spub2.addDependency(pub1);
1406                 spub2.addDependency(spub1);
1407                 spub2.addDependency(pub2);
1408                 spub2.addDependency(pub3);
1409                 ht.saveOrUpdate(spub2.value());
1410                 spub3.addDependency(spub2);
1411                 ht.saveOrUpdate(spub3.value());
1412                 // spub31.addDependency(spub31);
1413                 // ht.saveOrUpdate(spub31.value());
1414                 ht.flush();
1415
1416                 // Create target study1
1417                 Study aStudy1 = TestEntitiesGenerator.getTestStudy(goodUser);
1418                 aStudy1.setTitle("1.This is a target study1");
1419                 aStudy1.setReference("tst1");
1420                 Long studyId1 = _studyDAO.create(aStudy1);
1421
1422                 // Add a scenario to the study
1423                 Scenario scen1 = TestEntitiesGenerator.getTestScenario(aStudy1);
1424                 _scenarioDAO.create(scen1);
1425                 ht.flush();
1426
1427                 // Create target study2
1428                 Study aStudy2 = TestEntitiesGenerator.getTestStudy(goodUser);
1429                 aStudy2.setTitle("2.This is a target study2");
1430                 aStudy2.setReference("tst2");
1431                 Long studyId2 = _studyDAO.create(aStudy2);
1432
1433                 // Add a scenario to the study
1434                 Scenario scen2 = TestEntitiesGenerator.getTestScenario(aStudy2);
1435                 _scenarioDAO.create(scen2);
1436                 ht.flush();
1437                 ht.clear();
1438
1439                 // //////////////////// TEST CALL /////////////////////////////////////
1440                 // 1. call the method for a not existing source study.
1441                 try {
1442                         _scenarioService.copyStudyContent(-1, -1, -1, -1);
1443                         Assert.fail("Exception must be thrown for not existing study id.");
1444                 } catch (InvalidParameterException e) {
1445                         LOG.debug("Expected exception: " + e.getClass().getSimpleName()
1446                                         + ": " + e.getMessage());
1447                 }
1448
1449                 ht.flush();
1450                 ht.clear();
1451
1452                 // 2. call the method for a not existing source scenario with not evolving step.
1453                 _scenarioService.copyStudyContent(studyId, -1, 1, studyId1);
1454
1455                 ht.flush();
1456                 ht.clear();
1457
1458                 aStudy = _studyService.selectStudy(studyId);
1459                 aStudy1 = _studyService.selectStudy(studyId1);
1460                 for (Publication pub : aStudy.getDocums()) {
1461                         // Find the same document in the created copy of the study
1462                         Publication found = null;
1463                         for (Publication newPub : aStudy1.getDocums()) {
1464                                 if (pub.value().getTitle().equals(newPub.value().getTitle())
1465                                                 && pub.value().getType().equals(
1466                                                                 newPub.value().getType())) {
1467                                         found = newPub;
1468                                         break;
1469                                 }
1470                         }
1471                         Assert.assertNotNull(found, "The document "
1472                                         + pub.value().getTitle() + "is not copied");
1473                         // Check that all files are copied (source and attached)
1474                 }
1475
1476                 // 3. call the method for a not existing source scenario with evolving step.
1477                 try {
1478                         _scenarioService.copyStudyContent(studyId, -1, 2, studyId2);
1479                         Assert
1480                                         .fail("Exception must be thrown for not existing scenario id and evolving step.");
1481                 } catch (InvalidParameterException e) {
1482                         LOG.debug("Expected exception: " + e.getClass().getSimpleName()
1483                                         + ": " + e.getMessage());
1484                 }
1485
1486                 ht.flush();
1487                 ht.clear();
1488
1489                 // 4. call the method for an existing source scenario with evolving step.
1490                 _scenarioService.copyStudyContent(studyId, aScenId, 9, studyId2);
1491                 ht.flush();
1492
1493                 rollbackNestedTransaction();
1494                 LOG.debug(">>>>> END testCopyStudyContent()");
1495         }
1496
1497         /**
1498          * Create a document and publish it in the project element.
1499          * 
1500          * @param aProjElem
1501          *            the project element
1502          * @param aStep
1503          *            the project element step
1504          * @param docname
1505          *            document name
1506          * @param dtype
1507          *            document type
1508          * @return publication of the created document
1509          * @throws BusinessException
1510          *             if document creation is failed
1511          * @throws IOException
1512          *             if file creation is failed
1513          */
1514         private Publication addDoc(final ProjectElement aProjElem,
1515                         final org.splat.som.Step aStep, final String docname,
1516                         final DocumentType dtype) throws BusinessException, IOException {
1517                 HibernateTemplate ht = getHibernateTemplate();
1518                 // Add documents to the study activity
1519                 Document.Properties dprop = new Document.Properties().setAuthor(
1520                                 aProjElem.getAuthor()).setDate(new Date()).setName(docname)
1521                                 .setType(dtype).setFormat("py");
1522                 dprop.setLocalPath(dprop.getName() + "." + dprop.getFormat());
1523                 dprop.setStep(aStep.getStep());
1524                 Publication pub = _stepService.createDocument(aStep, dprop);
1525                 pub.setStep(aStep);
1526                 aProjElem.add(pub);
1527                 aStep.getDocuments().add(pub);
1528                 ht.saveOrUpdate(pub);
1529                 ht.save(pub.value());
1530                 // Add a converts relation
1531                 // Attach a med file
1532                 ht.saveOrUpdate(_publicationService.attach(pub, "med"));
1533                 String filepath = pub.getSourceFile().asFile().getAbsolutePath();
1534                 createFile(filepath);
1535                 createFile(filepath.substring(0, filepath.lastIndexOf(".")) + ".med");
1536                 return pub;
1537         }
1538
1539         /**
1540          * Create a new version of the document.
1541          * 
1542          * @param pub
1543          *            the current document publication
1544          * @return the new document version publication
1545          * @throws IOException
1546          *             if versioning is failed
1547          * @throws BusinessException
1548          *             if versioning is failed
1549          */
1550         private Publication version(final Publication pub)
1551                         throws BusinessException, IOException {
1552                 Document.Properties dprop = new Document.Properties();
1553                 dprop.setDocument(pub.value(), pub.getStep().getStep());
1554                 Publication newpub = _stepService.versionDocument(pub.getStep(), pub,
1555                                 dprop);
1556                 pub.getOwner().getDocums().remove(pub);
1557                 pub.getStep().getDocuments().remove(pub);
1558                 pub.getOwner().add(newpub);
1559                 pub.getStep().getDocuments().add(newpub);
1560                 return newpub;
1561         }
1562
1563         /**
1564          * Test assigning a simulation context to a study.<BR>
1565          * <B>Description :</B> <BR>
1566          * <i>Create a study and assign a simulation context to it.</i><BR>
1567          * <B>Action : </B><BR>
1568          * <i>1. call the method for not existing study id.</i><BR>
1569          * <i>2. call the method for not existing context type and context value.</i><BR>
1570          * <i>3. call the method for existing context type and context value.</i><BR>
1571          * <i>4. call the method for existing context type and not existing context value.</i><BR>
1572          * <i>5. call the method for empty context type.</i><BR>
1573          * <i>6. call the method for empty context value.</i><BR>
1574          * <B>Test data : </B><BR>
1575          * <i>no input parameters</i><BR>
1576          * 
1577          * <B>Outcome results:</B><BR>
1578          * <i>
1579          * <ul>
1580          * <li>1: Exception must be thrown.</li>
1581          * <li>2: The new context type and value must be created. The new context must be assigned to the study first step.</li>
1582          * <li>3: The existing context must be assigned to the study first step.</li>
1583          * <li>4: The new context value must be created. The new context must be assigned to the study first step.</li>
1584          * <li>5: Exception must be thrown.</li>
1585          * <li>6: Exception must be thrown.</li>
1586          * </ul>
1587          * </i>
1588          * 
1589          * @throws IOException
1590          *             if application configuration loading is failed
1591          * @throws SQLException
1592          *             if application configuration loading is failed
1593          * @throws BusinessException
1594          *             if test data creation is failed
1595          */
1596         @Test(groups = { "study", "sevice", "functional", "business" })
1597         public void testAssignStudyContextFromPython() throws IOException,
1598                         SQLException, BusinessException {
1599                 LOG.debug(">>>>> BEGIN testAssignStudyContextFromPython()");
1600                 startNestedTransaction();
1601
1602                 HibernateTemplate ht = getHibernateTemplate();
1603
1604                 Database.getInstance().reset();
1605                 _projectSettings.getAllSteps().clear(); // Clear config to be able to load it again
1606                 _projectSettings.configure("classpath:test/som.xml");
1607
1608                 // Create a test user
1609                 User goodUser = TestEntitiesGenerator.getTestUser("goodUser");
1610                 _userDAO.create(goodUser);
1611                 SimulationContextType prodtype = _simulationContextService
1612                                 .selectType("product");
1613                 Assert
1614                                 .assertNotNull(prodtype,
1615                                                 "Simulation context type 'product' must be created in the database.");
1616
1617                 String productName = "New Test Product " + new Date().toString();
1618
1619                 ht.flush();
1620                 ht.clear();
1621                 long studyId1 = _scenarioService.createStudy("goodUser",
1622                                 "Test Study 1", productName, "Test description");
1623                 Assert.assertTrue(studyId1 > 0);
1624
1625                 ht.flush();
1626                 ht.clear();
1627
1628                 // //////// START OF TESTS
1629                 // 1. call the method for not existing study id.</i><BR>
1630                 try {
1631                         _scenarioService.assignStudyContext(-1L, "new context type",
1632                                         "new context value");
1633                         Assert.fail("Not existing study must not be found.");
1634                 } catch (InvalidPropertyException ipe) {
1635                         LOG.debug("Expected exception: " + ipe.getMessage());
1636                 }
1637
1638                 // 2. call the method for not existing context type and context value.</i><BR>
1639                 _scenarioService.assignStudyContext(studyId1, "new context type",
1640                                 "new context value");
1641
1642                 ht.flush();
1643                 ht.clear();
1644
1645                 // Check the assigned simulation context
1646                 checkCtx(studyId1, "new context type", "new context value");
1647
1648                 // 3. call the method for existing context type and context value.</i><BR>
1649                 _scenarioService.assignStudyContext(studyId1, "new context type",
1650                                 "new context value");
1651
1652                 ht.flush();
1653                 ht.clear();
1654
1655                 // Check the assigned simulation context
1656                 checkCtx(studyId1, "new context type", "new context value");
1657
1658                 // 4. call the method for existing context type and not existing context value.</i><BR>
1659                 _scenarioService.assignStudyContext(studyId1, "new context type",
1660                                 "new context value1");
1661
1662                 ht.flush();
1663                 ht.clear();
1664
1665                 // Check the assigned simulation context
1666                 checkCtx(studyId1, "new context type", "new context value1");
1667
1668                 // 5. call the method for empty context type.</i><BR>
1669                 try {
1670                         _scenarioService.assignStudyContext(studyId1, "",
1671                                         "new context value");
1672                         Assert.fail("Empty context type name must be forbidden.");
1673                 } catch (InvalidPropertyException ipe) {
1674                         LOG.debug("Expected exception: " + ipe.getMessage());
1675                 }
1676                 // 6. call the method for empty context value.</i><BR>
1677                 try {
1678                         _scenarioService.assignStudyContext(studyId1, "new context type",
1679                                         "");
1680                         Assert.fail("Empty context value must be forbidden.");
1681                 } catch (InvalidPropertyException ipe) {
1682                         LOG.debug("Expected exception: " + ipe.getMessage());
1683                 }
1684
1685                 rollbackNestedTransaction();
1686                 LOG.debug(">>>>> END testAssignStudyContextFromPython()");
1687         }
1688
1689         /**
1690          * Test getting a study scenarios DTO list.<BR>
1691          * <B>Description :</B> <BR>
1692          * <i>Create a study and get its scenarios DTO list.</i><BR>
1693          * <B>Action : </B><BR>
1694          * <i>1. call the method for not existing study id.</i><BR>
1695          * <i>2. call the method for a study with one scenario.</i><BR>
1696          * <i>3. call the method for a study with several scenarios.</i><BR>
1697          * <B>Test data : </B><BR>
1698          * <i>no input parameters</i><BR>
1699          * 
1700          * <B>Outcome results:</B><BR>
1701          * <i>
1702          * <ul>
1703          * <li>1: The returned list of DTO must be empty.</li>
1704          * <li>2: The returned list of DTO must contain one scenario DTO.</li>
1705          * <li>3: The returned list of DTO must contain several scenario DTOs.</li>
1706          * </ul>
1707          * </i>
1708          * 
1709          * @throws IOException
1710          *             if application configuration loading is failed
1711          * @throws SQLException
1712          *             if application configuration loading is failed
1713          * @throws BusinessException
1714          *             if test data creation is failed
1715          */
1716         @Test(groups = { "study", "sevice", "functional", "business" })
1717         public void testGetStudyScenarios() throws IOException, SQLException,
1718                         BusinessException {
1719                 LOG.debug(">>>>> BEGIN testGetStudyScenarios()");
1720                 startNestedTransaction();
1721
1722                 HibernateTemplate ht = getHibernateTemplate();
1723
1724                 Database.getInstance().reset();
1725                 _projectSettings.getAllSteps().clear(); // Clear config to be able to load it again
1726                 _projectSettings.configure("classpath:test/som.xml");
1727
1728                 // Create a test user
1729                 User goodUser = TestEntitiesGenerator.getTestUser("goodUser");
1730                 _userDAO.create(goodUser);
1731                 Study study = TestEntitiesGenerator.getTestStudy(goodUser);
1732                 long studyId1 = _studyDAO.create(study);
1733                 ht.flush();
1734                 Scenario scen = TestEntitiesGenerator.getTestScenario(study,
1735                                 "test scen11");
1736                 long id11 = _scenarioDAO.create(scen);
1737                 ht.flush();
1738                 study = TestEntitiesGenerator.getTestStudy(goodUser);
1739                 long studyId2 = _studyDAO.create(study);
1740                 ht.flush();
1741                 scen = TestEntitiesGenerator.getTestScenario(study, "test scen21");
1742                 long id21 = _scenarioDAO.create(scen);
1743                 ht.flush();
1744                 scen = TestEntitiesGenerator.getTestScenario(study, "test scen22");
1745                 long id22 = _scenarioDAO.create(scen);
1746                 ht.flush();
1747                 scen = TestEntitiesGenerator.getTestScenario(study, "test scen23");
1748                 long id23 = _scenarioDAO.create(scen);
1749                 ht.flush();
1750                 ht.clear();
1751
1752                 // //////// START OF TESTS
1753                 // 1. call the method for not existing study id.
1754                 List<ScenarioDTO> scens = _scenarioService.getStudyScenarios(-1L);
1755
1756                 Assert.assertNotNull(scens);
1757                 Assert.assertTrue(scens.isEmpty());
1758
1759                 // 2. call the method for a study with one scenario.
1760                 scens = _scenarioService.getStudyScenarios(studyId1);
1761
1762                 ht.flush();
1763                 ht.clear();
1764                 Assert.assertNotNull(scens);
1765                 Assert.assertEquals(scens.size(), 1);
1766                 Assert.assertEquals(scens.get(0).getIndex().longValue(), id11);
1767                 Assert.assertEquals(scens.get(0).getTitle(), "test scen11");
1768
1769                 // 3. call the method for a study with several scenarios.
1770                 scens = _scenarioService.getStudyScenarios(studyId2);
1771                 Assert.assertEquals(scens.size(), 3);
1772                 Assert.assertEquals(scens.get(0).getIndex().longValue(), id21);
1773                 Assert.assertEquals(scens.get(0).getTitle(), "test scen21");
1774                 Assert.assertEquals(scens.get(1).getIndex().longValue(), id22);
1775                 Assert.assertEquals(scens.get(1).getTitle(), "test scen22");
1776                 Assert.assertEquals(scens.get(2).getIndex().longValue(), id23);
1777                 Assert.assertEquals(scens.get(2).getTitle(), "test scen23");
1778
1779                 ht.flush();
1780                 ht.clear();
1781
1782                 rollbackNestedTransaction();
1783                 LOG.debug(">>>>> END testGetStudyScenarios()");
1784         }
1785
1786         /**
1787          * Check if the context is assigned to the study.
1788          * 
1789          * @param studyId1
1790          *            the study id
1791          * @param ctxType
1792          *            the context type name
1793          * @param ctxValue
1794          *            the context value
1795          */
1796         private void checkCtx(final long studyId1, final String ctxType,
1797                         final String ctxValue) {
1798                 // Check the assigned simulation context
1799                 Study study1 = _studyService.selectStudy(studyId1);
1800                 Iterator<SimulationContext> it = study1.SimulationContextIterator();
1801                 SimulationContext ctx;
1802                 boolean isFound = false;
1803                 while ((!isFound) && it.hasNext()) {
1804                         ctx = it.next();
1805                         isFound = ctx.getType().getName().equals(ctxType)
1806                                         && ctx.getValue().equals(ctxValue);
1807                 }
1808                 Assert.assertTrue(isFound, "Context must be assigned to the study.");
1809         }
1810 }