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