]> SALOME platform Git repositories - tools/siman.git/blob - Workspace/Siman-Common/src/test/splat/service/TestStepService.java
Salome HOME
Replace document functionality is implemented.
[tools/siman.git] / Workspace / Siman-Common / src / test / splat / service / TestStepService.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.FileNotFoundException;
12 import java.io.IOException;
13 import java.sql.SQLException;
14 import java.util.ArrayList;
15 import java.util.Date;
16 import java.util.HashMap;
17 import java.util.List;
18 import java.util.Map;
19
20 import org.splat.dal.bo.kernel.User;
21 import org.splat.dal.bo.som.ConvertsRelation;
22 import org.splat.dal.bo.som.Document;
23 import org.splat.dal.bo.som.DocumentType;
24 import org.splat.dal.bo.som.File;
25 import org.splat.dal.bo.som.ProjectElement;
26 import org.splat.dal.bo.som.Publication;
27 import org.splat.dal.bo.som.Scenario;
28 import org.splat.dal.bo.som.StepCommentAttribute;
29 import org.splat.dal.bo.som.Study;
30 import org.splat.dal.bo.som.UsedByRelation;
31 import org.splat.dal.bo.som.UsesRelation;
32 import org.splat.dal.bo.som.Document.Properties;
33 import org.splat.dal.dao.kernel.UserDAO;
34 import org.splat.dal.dao.som.Database;
35 import org.splat.dal.dao.som.FileDAO;
36 import org.splat.dal.dao.som.ScenarioDAO;
37 import org.splat.dal.dao.som.StepCommentAttributeDAO;
38 import org.splat.dal.dao.som.StudyDAO;
39 import org.splat.exception.BusinessException;
40 import org.splat.exception.DocumentIsUsedException;
41 import org.splat.exception.InvalidParameterException;
42 import org.splat.kernel.InvalidPropertyException;
43 import org.splat.kernel.MissedPropertyException;
44 import org.splat.kernel.MultiplyDefinedException;
45 import org.splat.log.AppLogger;
46 import org.splat.service.DocumentTypeService;
47 import org.splat.service.ProjectElementService;
48 import org.splat.service.PublicationService;
49 import org.splat.service.StepService;
50 import org.splat.service.StudyService;
51 import org.splat.service.dto.StepCommentDTO;
52 import org.splat.service.technical.ProjectSettingsService;
53 import org.splat.service.technical.ProjectSettingsService.Step;
54 import org.springframework.beans.factory.annotation.Autowired;
55 import org.springframework.beans.factory.annotation.Qualifier;
56 import org.springframework.orm.hibernate3.HibernateTemplate;
57 import org.testng.Assert;
58 import org.testng.annotations.Test;
59
60 import test.splat.common.BaseTest;
61 import test.splat.util.TestEntitiesGenerator;
62
63 /**
64  * Test class for StepService.
65  * 
66  * @author <a href="mailto:roman.kozlov@opencascade.com">Roman Kozlov (RKV)</a>
67  * 
68  */
69 public class TestStepService extends BaseTest {
70
71         /**
72          * Logger for the class.
73          */
74         private static final AppLogger LOG = AppLogger
75                         .getLogger(TestStepService.class);
76
77         /**
78          * The StudyService. Later injected by Spring.
79          */
80         @Autowired
81         @Qualifier("studyService")
82         private transient StudyService _studyService;
83
84         /**
85          * The Scenario DAO. Later injected by Spring.
86          */
87         @Autowired
88         @Qualifier("scenarioDAO")
89         private transient ScenarioDAO _scenarioDAO;
90
91         /**
92          * The File DAO. Later injected by Spring.
93          */
94         @Autowired
95         @Qualifier("fileDAO")
96         private transient FileDAO _fileDAO;
97
98         /**
99          * The PublicationService. Later injected by Spring.
100          */
101         @Autowired
102         @Qualifier("publicationService")
103         private transient PublicationService _publicationService;
104
105         /**
106          * The StepService. Later injected by Spring.
107          */
108         @Autowired
109         @Qualifier("stepService")
110         private transient StepService _stepService;
111
112         /**
113          * The ProjectSettingsService. Later injected by Spring.
114          */
115         @Autowired
116         @Qualifier("projectSettings")
117         private transient ProjectSettingsService _projectSettings;
118
119         /**
120          * The injected by Spring StepCommentAttributeDAO.
121          */
122         @Autowired
123         @Qualifier("stepCommentAttributeDAO")
124         private transient StepCommentAttributeDAO _stepCommentAttributeDAO;
125
126         /**
127          * The injected by Spring UserDAO.
128          */
129         @Autowired
130         @Qualifier("userDAO")
131         private transient UserDAO _userDAO;
132
133         /**
134          * The injected by Spring StudyDAO.
135          */
136         @Autowired
137         @Qualifier("studyDAO")
138         private transient StudyDAO _studyDAO;
139
140         /**
141          * The DocumentTypeService. Later injected by Spring.
142          */
143         @Autowired
144         @Qualifier("documentTypeService")
145         private transient DocumentTypeService _documentTypeService;
146
147         /**
148          * The ProjectElementService. Later injected by Spring.
149          */
150         @Autowired
151         @Qualifier("projectElementService")
152         private transient ProjectElementService _projectElementService;
153
154         /**
155          * Test removeDocument method.<BR>
156          * <B>Description :</B> <BR>
157          * <i>Create a scenario and try to remove documents from it.<BR>
158          * </i><BR>
159          * <B>Action : </B><BR>
160          * <i>1. call the method for all documents used by other document(s).</i><BR>
161          * <i>2. call the method for all documents starting from the last activity.</i><BR>
162          * <B>Test data : </B><BR>
163          * <i>no input parameters</i><BR>
164          * <i>no input parameters</i><BR>
165          * 
166          * <B>Outcome results:</B><BR>
167          * <i>
168          * <ul>
169          * <li>Exception DocumentIsUsedException is expected<BR>
170          * </li>
171          * <li>All documents and their files and relations must be removed<BR>
172          * </li>
173          * </ul>
174          * </i>
175          * 
176          * @throws BusinessException
177          *             if scenario creation or checkin is failed
178          * @throws IOException
179          *             if scenario creation is failed
180          * @throws SQLException
181          *             if scenario creation is failed
182          */
183         @Test
184         public void testRemoveDocument() throws BusinessException, IOException,
185                         SQLException {
186                 LOG.debug(">>>>> BEGIN testRemoveDocument()");
187                 startNestedTransaction();
188
189                 _projectSettings.getAllSteps().clear(); // Clear config to be able to load it again
190                 _projectSettings.configure("classpath:test/som.xml");
191                 HibernateTemplate ht = getHibernateTemplate();
192                 ht.flush();
193                 long scenarioId = createScenario();
194                 ht.flush();
195                 _scenarioDAO.flush();
196                 Scenario aScen = _scenarioDAO.get(scenarioId);
197
198                 ht.evict(aScen);
199                 ht.evict(aScen.getOwnerStudy());
200
201                 Assert.assertTrue(ht.find("from UsesRelation").size() > 0,
202                                 "Uses relations were not created in the database.");
203
204                 Assert.assertTrue(ht.find("from UsedByRelation").size() > 0,
205                                 "UsedBy relations were not created in the database.");
206
207                 ProjectElement projElem;
208                 boolean ok = false;
209                 long docId;
210                 Step step;
211                 int nbDoc = ht.find("from Document").size();
212                 int nbRemovedDoc = 0;
213                 List<Long> removedDocs = new ArrayList<Long>();
214
215                 // ////////////////////////////////////////////////////////
216                 // Call removeDocument method for each document
217                 // used by other document(s).
218                 // Exception DocumentIsUsedException is expected
219                 for (int i = 1; i <= _projectSettings.getAllSteps().size(); i++) {
220                         LOG.debug("Remove used documents from the step " + i);
221                         step = _projectSettings.getStep(i);
222                         if (step.appliesTo(Study.class)) {
223                                 projElem = _studyService.selectStudy(aScen.getOwnerStudy()
224                                                 .getIndex());
225                         } else {
226                                 projElem = aScen;
227                         }
228
229                         org.splat.som.Step aScStep = new org.splat.som.Step(step, projElem);
230
231                         if (aScStep.getDocuments().size() > 0) {
232                                 docId = aScStep.getDocuments().get(0).value().getIndex();
233                                 ht.flush();
234
235                                 List<UsesRelation> uses = ht
236                                                 .find("from UsesRelation where owner=" + docId);
237                                 List<UsedByRelation> usedBy = ht
238                                                 .find("from UsedByRelation where owner=" + docId);
239                                 if (!usedBy.isEmpty()) {
240                                         int usesRefer = ht.find(
241                                                         "from UsesRelation where refer=" + docId).size();
242                                         int usedByRefer = ht.find(
243                                                         "from UsedByRelation where refer=" + docId).size();
244                                         int convertsNb = ht.find(
245                                                         "from ConvertsRelation where owner=" + docId)
246                                                         .size();
247                                         LOG.debug("Remove used document "
248                                                         + aScStep.getDocument(docId).value().getTitle());
249                                         LOG.debug("From db: It uses following " + uses.size()
250                                                         + " documents: ");
251                                         for (UsesRelation rel : uses) {
252                                                 LOG.debug(rel.getTo().getTitle());
253                                         }
254                                         LOG
255                                                         .debug("From step: It uses following "
256                                                                         + aScStep.getDocument(docId).value()
257                                                                                         .getRelations(UsesRelation.class)
258                                                                                         .size() + " documents: ");
259                                         for (Publication rel : aScStep.getDocument(docId)
260                                                         .getRelations(UsesRelation.class)) {
261                                                 LOG.debug(rel.value().getTitle());
262                                         }
263                                         LOG.debug("From db: It is used by following "
264                                                         + usedBy.size() + " documents: ");
265                                         for (UsedByRelation rel : usedBy) {
266                                                 LOG.debug(rel.getTo().getTitle());
267                                         }
268                                         LOG.debug("From step: It is used by following "
269                                                         + aScStep.getDocument(docId).value().getRelations(
270                                                                         UsedByRelation.class).size()
271                                                         + " documents: ");
272                                         for (Publication rel : aScStep.getDocument(docId)
273                                                         .getRelations(UsedByRelation.class)) {
274                                                 LOG.debug(rel.value().getTitle());
275                                         }
276                                         ht.flush();
277                                         ht.clear();
278                                         try {
279                                                 ok = _stepService.removeDocument(aScStep, docId);
280                                                 Assert.fail("DocumentIsUsedException must be thrown.");
281                                         } catch (DocumentIsUsedException e) {
282                                                 LOG.debug("Expected exception is thrown: "
283                                                                 + e.getLocalizedMessage());
284                                         }
285                                         _scenarioDAO.flush();
286                                         ht.flush();
287                                         Assert
288                                                         .assertEquals(ht.find(
289                                                                         "from UsesRelation where owner=" + docId)
290                                                                         .size(), uses.size(),
291                                                                         "UsesRelation(s) must not be changed.");
292                                         Assert.assertEquals(ht.find(
293                                                         "from UsedByRelation where owner=" + docId).size(),
294                                                         usedBy.size(),
295                                                         "UsedByRelation(s) must not be changed.");
296                                         Assert.assertEquals(ht.find(
297                                                         "from UsesRelation where refer=" + docId).size(),
298                                                         usesRefer,
299                                                         "Referencing UsesRelation(s) must not be changed.");
300                                         Assert
301                                                         .assertEquals(ht.find(
302                                                                         "from UsedByRelation where refer=" + docId)
303                                                                         .size(), usedByRefer,
304                                                                         "Referencing UsedByRelation(s) must not be changed.");
305                                         Assert.assertEquals(ht.find(
306                                                         "from ConvertsRelation where owner=" + docId)
307                                                         .size(), convertsNb,
308                                                         "ConvertsRelation(s) must not be changed.");
309                                 }
310                         }
311                 }
312
313                 // ////////////////////////////////////////////////////////
314                 // Call removeDocument method for each document
315                 // starting from the last activity.
316                 Study aStudy = _studyService.selectStudy(aScen.getOwnerStudy()
317                                 .getIndex());
318                 aScen = aStudy.getScenarii()[0];
319                 Map<Integer, org.splat.som.Step> stSteps = _projectElementService
320                                 .getStepsMap(aStudy);
321                 Map<Integer, org.splat.som.Step> scSteps = _projectElementService
322                                 .getStepsMap(aScen);
323                 org.splat.som.Step aScStep;
324                 for (int i = _projectSettings.getAllSteps().size(); i > 0; i--) {
325                         LOG.debug("Remove documents from the step " + i);
326                         step = _projectSettings.getStep(i);
327                         if (step.appliesTo(Study.class)) {
328                                 projElem = aStudy;
329                                 aScStep = stSteps.get(step.getNumber());
330                         } else {
331                                 projElem = aScen;
332                                 aScStep = scSteps.get(step.getNumber());
333                         }
334
335                         if (aScStep.getDocuments().size() > 0) {
336                                 docId = aScStep.getDocuments().get(0).value().getIndex();
337                                 LOG.debug("Remove document#" + docId + " "
338                                                 + aScStep.getDocument(docId).value().getTitle());
339                                 ht.flush();
340                                 List<UsesRelation> uses = ht
341                                                 .find("from UsesRelation where owner=" + docId);
342                                 List<UsedByRelation> usedBy = ht
343                                                 .find("from UsedByRelation where owner=" + docId);
344                                 LOG.debug("From db: It uses following " + uses.size()
345                                                 + " documents: ");
346                                 for (UsesRelation rel : uses) {
347                                         LOG.debug(rel.getTo().getTitle());
348                                 }
349                                 LOG.debug("From step: It uses following "
350                                                 + aScStep.getDocument(docId).getRelations(
351                                                                 UsesRelation.class).size() + " documents: ");
352                                 for (Publication rel : aScStep.getDocument(docId).getRelations(
353                                                 UsesRelation.class)) {
354                                         LOG.debug(rel.value().getTitle());
355                                 }
356                                 LOG.debug("From db: It is used by following " + usedBy.size()
357                                                 + " documents: ");
358                                 for (UsedByRelation rel : usedBy) {
359                                         LOG.debug(rel.getTo().getTitle());
360                                 }
361                                 LOG.debug("From step: It is used by following "
362                                                 + aScStep.getDocument(docId).getRelations(
363                                                                 UsedByRelation.class).size() + " documents: ");
364                                 for (Publication rel : aScStep.getDocument(docId).getRelations(
365                                                 UsedByRelation.class)) {
366                                         LOG.debug(rel.value().getTitle());
367                                 }
368                                 Assert.assertEquals(ht.find("from Document where rid=" + docId)
369                                                 .size(), 1, "Nothing to delete.");
370
371                                 ht.evict(aScStep.getDocuments().get(0).value().getFile());
372                                 LOG.debug("Load file#"
373                                                 + aScStep.getDocuments().get(0).value().getRelations(
374                                                                 ConvertsRelation.class).get(0).getTo()
375                                                                 .getIndex());
376
377                                 ht.flush();
378                                 ht.clear();
379                                 File f = _fileDAO.get(aScStep.getDocuments().get(0).value()
380                                                 .getRelations(ConvertsRelation.class).get(0).getTo()
381                                                 .getIndex());
382                                 ht.evict(aScStep.getDocuments().get(0).value());
383
384                                 ok = _stepService.removeDocument(aScStep, docId);
385
386                                 nbRemovedDoc++;
387                                 removedDocs.add(docId);
388
389                                 Assert.assertTrue(ok, "Removing was failed.");
390                                 _scenarioDAO.flush();
391                                 ht.flush();
392
393                                 for (Long id : removedDocs) {
394                                         String title = "";
395                                         if (ht.get(Document.class, id) != null) {
396                                                 title = ht.get(Document.class, id).getTitle();
397                                         }
398                                         Assert.assertEquals(ht
399                                                         .find("from Document where rid=" + id).size(), 0,
400                                                         "Document#" + id + "(" + title
401                                                                         + ") was not removed from the database.");
402                                 }
403
404                                 Assert.assertEquals(ht.find("from Document").size(), nbDoc
405                                                 - nbRemovedDoc,
406                                                 "Documents were not removed from the database.");
407                                 Assert.assertEquals(ht.find(
408                                                 "from UsesRelation where owner=" + docId).size(), 0,
409                                                 "UsesRelation(s) were not removed from the database.");
410                                 Assert
411                                                 .assertEquals(ht.find(
412                                                                 "from UsedByRelation where owner=" + docId)
413                                                                 .size(), 0,
414                                                                 "UsedByRelation(s) were not removed from the database.");
415                                 Assert
416                                                 .assertEquals(ht.find(
417                                                                 "from UsesRelation where refer=" + docId)
418                                                                 .size(), 0,
419                                                                 "Referencing UsesRelation(s) were not removed from the database.");
420                                 Assert
421                                                 .assertEquals(ht.find(
422                                                                 "from UsedByRelation where refer=" + docId)
423                                                                 .size(), 0,
424                                                                 "Referencing UsedByRelation(s) were not removed from the database.");
425                                 Assert
426                                                 .assertEquals(ht.find(
427                                                                 "from ConvertsRelation where owner=" + docId)
428                                                                 .size(), 0,
429                                                                 "ConvertsRelation(s) were not removed from the database.");
430                         }
431                 }
432
433                 Assert
434                                 .assertEquals(ht.find("from Document").size(), nbDoc
435                                                 - nbRemovedDoc,
436                                                 "Documents were not removed from the database.");
437
438                 Assert.assertEquals(ht.find("from File").size(), 0,
439                                 "Files were not removed from the database.");
440
441                 Assert.assertEquals(ht.find(
442                                 "from Publication where owner=" + aScen.getIndex()).size(), 0,
443                                 "Publications were not removed from the database.");
444
445                 Assert.assertEquals(ht.find("from UsesRelation").size(), 0,
446                                 "Uses relations were not removed from the database.");
447
448                 Assert.assertEquals(ht.find("from UsedByRelation").size(), 0,
449                                 "UsedBy relations were not removed from the database.");
450
451                 rollbackNestedTransaction();
452                 LOG.debug(">>>>> END testRemoveDocument()");
453         }
454
455         /**
456          * Test removeDocument method for a published document version.<BR>
457          * <B>Description :</B> <BR>
458          * <i>Create a study and a scenario with versioned documents and try to remove published versions.<BR>
459          * </i><BR>
460          * <B>Action : </B><BR>
461          * <i>1. call the method for a version published in the study step.</i><BR>
462          * <i>2. call the method for a version published in the scenario step.</i><BR>
463          * <B>Test data : </B><BR>
464          * <i>no input parameters</i><BR>
465          * <i>no input parameters</i><BR>
466          * 
467          * <B>Outcome results:</B><BR>
468          * <i>
469          * <ul>
470          * <li>The published version must be removed, the previous version must be republished in the study.<BR>
471          * </li>
472          * <li>The published version must be removed, the previous version must be republished in the scenario.<BR>
473          * </li>
474          * </ul>
475          * </i>
476          * 
477          * @throws BusinessException
478          *             if test data creation is failed
479          * @throws IOException
480          *             if application configuration loading or test data creation is failed
481          * @throws SQLException
482          *             if application configuration loading or test data creation is failed
483          */
484         @Test
485         public void testRemoveDocumentVersion() throws BusinessException,
486                         IOException, SQLException {
487                 LOG.debug(">>>>> BEGIN testRemoveDocumentVersion()");
488                 startNestedTransaction();
489
490                 HibernateTemplate ht = getHibernateTemplate();
491
492                 Database.getInstance().reset();
493                 _projectSettings.getAllSteps().clear(); // Clear config to be able to load it again
494                 _projectSettings.configure("classpath:test/som.xml");
495
496                 User goodUser = TestEntitiesGenerator.getTestUser("GoodUser");
497                 _userDAO.create(goodUser);
498
499                 // Create private study
500                 Study aStudy = TestEntitiesGenerator.getTestStudy(goodUser);
501                 aStudy.setTitle("0.This is private study");
502                 Long studyId = _studyDAO.create(aStudy);
503
504                 // Add a scenario to the study
505                 Scenario scen = TestEntitiesGenerator.getTestScenario(aStudy);
506                 Long scenId = _scenarioDAO.create(scen);
507                 ht.flush();
508
509                 DocumentType dtype = _documentTypeService.selectType("minutes");
510
511                 // Add documents to the first study activity
512                 // Add a converts relations
513                 Map<Integer, org.splat.som.Step> stSteps = _projectElementService
514                                 .getStepsMap(aStudy);
515                 org.splat.som.Step aStep = stSteps.get(1);
516                 Publication pub1 = addDoc(aStudy, aStep, "document1", dtype);
517                 ht.flush();
518                 ht.update(aStudy);
519                 ht.flush();
520                 // Add a version relations
521                 Publication pub11 = version(pub1);
522                 ht.flush();
523                 
524                 // Add documents to the first scenario activity
525                 scen = aStudy.getScenariiList().get(0);
526                 Map<Integer, org.splat.som.Step> scSteps = _projectElementService
527                                 .getStepsMap(scen);
528                 aStep = scSteps.get(2);
529                 Publication spub1 = addDoc(scen, aStep, "sdocument1", dtype);
530                 ht.flush();
531                 // Add a version relations
532                 Publication spub11 = version(spub1);
533                 ht.flush();
534
535                 Long id1 = pub1.value().getIndex(), id11 = pub11.value().getIndex(), id2 = spub1
536                                 .value().getIndex(), id21 = spub11.value().getIndex();
537
538                 ht.evict(scen);
539                 ht.evict(scen.getOwnerStudy());
540                 ht.clear();
541
542                 Assert.assertTrue(ht.find("from VersionsRelation").size() >= 2,
543                                 "Uses relations were not created in the database.");
544
545                 // TEST CALL: Remove version from study step
546                 aStudy = _studyService.selectStudy(studyId);
547                 stSteps = _projectElementService.getStepsMap(aStudy);
548                 aStep = stSteps.get(1);
549                 Assert.assertTrue(_stepService.removeDocument(aStep, id11));
550                 ht.flush();
551
552                 // TEST CALL: Remove version from scenario
553                 scen = aStudy.getScenariiList().get(0);
554                 scSteps = _projectElementService.getStepsMap(scen);
555                 aStep = scSteps.get(2);
556                 Assert.assertTrue(_stepService.removeDocument(aStep, id21));
557                 ht.flush();
558
559                 Assert.assertEquals(ht.find("from Document where rid=" + id11).size(),
560                                 0, "Document#" + id11 + " was not removed from the database.");
561                 Assert.assertEquals(ht
562                                 .find("from VersionsRelation where owner=" + id11).size(), 0,
563                                 "VersionsRelation(s) were not removed from the database.");
564                 Assert.assertEquals(ht.find(
565                                 "from Publication where owner=" + studyId + " and mydoc="
566                                                 + id11).size(), 0,
567                                 "Version publication were not removed from the study.");
568                 Assert.assertEquals(ht.find("from Document where rid=" + id21).size(),
569                                 0, "Document#" + id21 + " was not removed from the database.");
570                 Assert.assertEquals(ht
571                                 .find("from VersionsRelation where owner=" + id21).size(), 0,
572                                 "VersionsRelation(s) were not removed from the database.");
573                 Assert.assertEquals(ht.find(
574                                 "from Publication where owner=" + studyId + " and mydoc="
575                                                 + id11).size(), 0,
576                                 "Version publication were not removed from the study.");
577                 Assert.assertEquals(ht
578                                 .find(
579                                                 "from Publication where owner=" + studyId
580                                                                 + " and mydoc=" + id1).size(), 1,
581                                 "First version were not republished in the study.");
582                 Assert.assertEquals(ht
583                                 .find(
584                                                 "from Publication where owner=" + scenId
585                                                                 + " and mydoc=" + id21).size(), 0,
586                                 "Version publication were not removed from the scenario.");
587                 Assert.assertEquals(ht.find(
588                                 "from Publication where owner=" + scenId + " and mydoc=" + id2)
589                                 .size(), 1,
590                                 "First version were not republished in the scenario.");
591
592                 rollbackNestedTransaction();
593                 LOG.debug(">>>>> END testRemoveDocumentVersion()");
594         }
595
596         /**
597          * Create a persistent scenario for tests.
598          * 
599          * @return a persistent scenario
600          * @throws InvalidPropertyException
601          *             if an invalid property is used when creating objects
602          * @throws MultiplyDefinedException
603          *             when trying to create an object with already existing id
604          * @throws MissedPropertyException
605          *             if a mandatory property is not defined for an object to be created
606          * @throws IOException
607          *             if document creation is failed
608          * @throws SQLException
609          *             if project settings loading is failed
610          */
611         private long createScenario() throws InvalidPropertyException,
612                         MissedPropertyException, MultiplyDefinedException, IOException,
613                         SQLException {
614                 // Create a scenario for tests
615                 HibernateTemplate ht = getHibernateTemplate();
616
617                 Database.getInstance().reset();
618                 _projectSettings.getAllSteps().clear(); // Clear config to be able to load it again
619                 // Load workflow customization
620                 try {
621                         _projectSettings.configure("classpath:test/som.xml");
622                 } catch (FileNotFoundException e) {
623                         Assert.fail("Can't find som.xml: ", e);
624                 }
625                 List<Step> steps = _projectSettings.getAllSteps();
626                 Assert.assertTrue(steps.size() > 0, "No steps are created.");
627
628                 // Create a test user
629                 User.Properties uprop = new User.Properties();
630                 uprop.setUsername("TST_Username").setName("TST_SimanUnitTestsUser")
631                                 .setFirstName("TST_FirstName").setDisplayName("TST_test.user")
632                                 .addRole("TST_user").setMailAddress(
633                                                 "noreply@salome-platform.org");
634                 uprop.disableCheck();
635                 User anAuthor = new User(uprop);
636                 ht.saveOrUpdate(anAuthor);
637
638                 // Create a test study
639                 Study.Properties stprops = new Study.Properties().setReference(
640                                 "TST_SID_01").setTitle("TST_Study").setManager(anAuthor);
641                 Study aStudy = new Study(stprops);
642                 ht.saveOrUpdate(aStudy);
643
644                 // Create a test scenario
645                 Scenario.Properties sprops = new Scenario.Properties().setTitle(
646                                 "TST_Scenario").setManager(anAuthor).setOwnerStudy(aStudy);
647                 Scenario aScenario = new Scenario(sprops);
648                 aStudy.getScenariiList().add(aScenario);
649                 ht.saveOrUpdate(anAuthor);
650                 ht.saveOrUpdate(aStudy);
651                 ht.saveOrUpdate(aScenario);
652
653                 // Create documents for each scenario step
654                 Document.Properties dprop = new Document.Properties().setAuthor(
655                                 anAuthor).setDate(new Date());
656                 int i = 0;
657                 Publication usedPub = null;
658                 Map<Long, Long> usedMap = new HashMap<Long, Long>();
659                 for (int stepNum = 1; stepNum <= steps.size(); stepNum++) {
660                         Step step = _projectSettings.getStep(stepNum);
661                         LOG.debug("Create scenario step: " + stepNum);
662                         ProjectElement projElem;
663
664                         if (step.appliesTo(Study.class)) {
665                                 projElem = aStudy;
666                         } else {
667                                 projElem = aScenario;
668                         }
669                         org.splat.som.Step aScStep = new org.splat.som.Step(step, projElem);
670                         List<DocumentType> dtypes = _documentTypeService
671                                         .selectTypesOf(step);
672                         if (dtypes.size() > 0) {
673                                 DocumentType dtype = dtypes.get(0);
674                                 // Create a document published in the scenario
675                                 // document<i>: document type[0] - first type used on the step
676                                 // <source-file>.brep
677                                 // <attached-file>.med
678                                 i++;
679                                 dprop.setName("document" + stepNum).setType(dtype);
680                                 if (step.getNumber() > 3) {
681                                         dprop.setFormat("med");
682                                 } else {
683                                         dprop.setFormat("py");
684                                 }
685                                 Publication pub = createDoc(projElem, aScStep, dprop, "med",
686                                                 false);
687                                 if (usedPub != null) {
688                                         pub.addDependency(usedPub);
689                                         LOG.debug("Add dependency: " + pub.value().getTitle()
690                                                         + " from " + usedPub.value().getTitle());
691                                         ht.saveOrUpdate(pub.value());
692                                         ht.flush();
693
694                                         usedMap.put(pub.getIndex(), usedPub.getIndex());
695                                 }
696                                 usedPub = pub;
697                         }
698                         if (dtypes.size() <= 0) {
699                                 LOG.debug("No document types are found for scenario step " + i);
700                         }
701                 }
702
703                 // Check that the scenario and its documents have been created correctly.
704
705                 Assert.assertNotNull(ht.find("from Document"),
706                                 "No documents in the database.");
707                 Assert.assertTrue(ht.find("from Document").size() > 0,
708                                 "No documents in the database.");
709
710                 Assert.assertNotNull(ht.find("from Publication where owner="
711                                 + aScenario.getIndex()), "No publications in the database.");
712                 Assert.assertTrue(
713                                 ht.find("from Publication where owner=" + aScenario.getIndex())
714                                                 .size() > 0, "No publications in the database.");
715
716                 for (Publication p : (List<Publication>) ht
717                                 .find("from Publication where owner=" + aScenario.getIndex())) {
718                         LOG.debug("Publication found: [id=" + p.getIndex() + ", owner="
719                                         + p.getOwner().getIndex() + ", doc=" + p.value().getIndex()
720                                         + "]");
721                         Assert.assertEquals(p.getOwner().getIndex(), aScenario.getIndex(),
722                                         "The publication was not attached to the scenario.");
723                 }
724
725                 // Remove the scenario from the current hibernate session.
726                 ht.evict(aScenario);
727                 // Check that the scenario is created in the database.
728                 Scenario aScen = ht.load(Scenario.class, aScenario.getIndex());
729                 Assert.assertNotNull(aScen, "Scenario was not saved in the database.");
730                 Assert.assertTrue(aScen.getDocums().size() > 0,
731                                 "No publications in the scenario.");
732
733                 Assert.assertTrue(i > 0,
734                                 "More then one document must be in the database");
735
736                 // Check created uses relations
737                 Assert
738                                 .assertTrue(usedMap.size() > 0,
739                                                 "Uses relations must be created.");
740                 boolean foundAny = false;
741                 for (Long usingId : usedMap.keySet()) {
742                         for (Publication pub : aScen.getDocums()) {
743                                 if (pub.getIndex() == usingId) {
744                                         boolean found = false;
745                                         for (Publication used : aScen.getDocums()) {
746                                                 found = (used.getIndex() == usedMap.get(usingId));
747                                                 if (found) {
748                                                         break;
749                                                 }
750                                         }
751                                         if (!found) {
752                                                 for (Publication used : aStudy.getDocums()) {
753                                                         found = (used.getIndex() == usedMap.get(usingId));
754                                                         if (found) {
755                                                                 break;
756                                                         }
757                                                 }
758                                         }
759                                         Assert.assertTrue(found,
760                                                         "Uses relation was not created in the database.");
761                                         foundAny = foundAny || found;
762                                 }
763                         }
764                 }
765                 Assert.assertTrue(foundAny,
766                                 "No Uses relation was created in the database.");
767
768                 return aScenario.getIndex();
769         }
770
771         /**
772          * Create a document published in the scenario. <BR>
773          * document:<BR>
774          * document type - type used on the step <BR>
775          * &lt;source-file&gt;.brep <BR>
776          * &lt;attached-file&gt;.med
777          * 
778          * @param aScenario
779          *            the scenario to add the document to
780          * @param aScStep
781          *            scenario step where the document to be published
782          * @param dprop
783          *            document properties
784          * @param attachedFileExt
785          *            extension of the secon attached (exported) file
786          * @param isOutdated
787          *            outdated document flag
788          * @return the publication of the created document
789          * @throws IOException
790          * @throws MultiplyDefinedException
791          * @throws InvalidPropertyException
792          * @throws MissedPropertyException
793          */
794         private Publication createDoc(final ProjectElement aScenario,
795                         final org.splat.som.Step aScStep, final Properties dprop,
796                         final String attachedFileExt, final boolean isOutdated)
797                         throws MissedPropertyException, InvalidPropertyException,
798                         MultiplyDefinedException, IOException {
799                 // Create a document published in the scenario
800                 // document<i>: document type - type used on the step
801                 // <source-file>.brep
802                 // <attached-file>.med
803                 Publication pub = _stepService.createDocument(aScStep, dprop);
804                 Assert.assertNotNull(pub.getOwner(),
805                                 "The publication must be attached to the scenario.");
806                 Assert.assertEquals(pub.getOwner().getIndex(), aScenario.getIndex(),
807                                 "The publication was not attached to the scenario.");
808
809                 if (isOutdated) {
810                         pub.setIsnew('O');
811                 }
812                 aScenario.add(pub);
813                 HibernateTemplate ht = getHibernateTemplate();
814                 ht.saveOrUpdate(pub);
815
816                 // Attach a file
817                 ht.save(pub.value());
818                 ht.flush();
819                 ht.saveOrUpdate(_publicationService.attach(pub, attachedFileExt));
820
821                 return pub;
822         }
823
824         /**
825          * Test of addition of a new step comment.
826          * 
827          * @throws BusinessException
828          *             if there is something wrong likely unrelated to the tested method
829          */
830         @Test
831         public void testAddStepComment() throws BusinessException {
832
833                 User goodUser = TestEntitiesGenerator.getTestUser("goodUser");
834                 _userDAO.create(goodUser);
835                 Study goodStudy = TestEntitiesGenerator.getTestStudy(goodUser);
836                 _studyDAO.create(goodStudy);
837                 getHibernateTemplate().flush();
838                 StepCommentDTO goodStepCommentDTO = createStepCommentDTO(goodUser,
839                                 goodStudy);
840
841                 // valid DTO, existing params
842                 _stepService.addStepComment(goodStepCommentDTO);
843                 Long id = goodStepCommentDTO.getId();
844                 Assert
845                                 .assertNotNull(id,
846                                                 "Add method returns null instead of a new id.");
847                 Assert.assertTrue(id > 0, "The new id is not a positive number.");
848                 StepCommentDTO retrievedComment = getDTOfromStepCommentAttribute(_stepCommentAttributeDAO
849                                 .get(id));
850                 Assert.assertTrue(compareStepCommentDTO(goodStepCommentDTO,
851                                 retrievedComment),
852                                 "The comment created in database has wrong data");
853
854                 // valid DTO, non-existing user
855                 {
856                         // get a non-existing id
857                         User badUser = TestEntitiesGenerator.getTestUser("badUser");
858                         _userDAO.create(badUser);
859                         getHibernateTemplate().evict(badUser);// so createStepCommentDTO will invoke an
860                         // actual query to the base, not cache, in order to check if the user already exists
861                         StepCommentDTO aBadDTO = createStepCommentDTO(badUser, goodStudy);
862
863                         try {
864                                 _stepService.addStepComment(aBadDTO);
865                                 getHibernateTemplate().flush();
866                                 Assert.fail("Creation with non-existing user must be failed.");
867                         } catch (InvalidParameterException e) {
868                                 LOG.debug("Expected exception is thrown: "
869                                                 + e.getClass().getSimpleName() + ": " + e.getMessage());
870                         }
871                 }
872
873                 // valid DTO, non-existing project element
874                 {
875                         Study badStudy = TestEntitiesGenerator.getTestStudy(goodUser);
876                         _studyDAO.create(badStudy);
877                         getHibernateTemplate().evict(badStudy);// so createStepCommentDTO will invoke an
878                         // actual query to the base, not cache in order to check if the study already exists
879                         StepCommentDTO aBadDTO = createStepCommentDTO(goodUser, badStudy);
880
881                         try {
882                                 _stepService.addStepComment(aBadDTO);
883                                 Assert.fail("Creation with non-existing user must be failed.");
884                         } catch (InvalidParameterException e) {
885                                 LOG.debug("Expected exception is thrown: "
886                                                 + e.getClass().getSimpleName() + ": " + e.getMessage());
887                         }
888                 }
889
890                 // not valid DTO (id filled in)
891                 {
892                         StepCommentDTO aBadDTO = createStepCommentDTO(goodUser, goodStudy);
893                         aBadDTO.setId(goodStepCommentDTO.getId());
894
895                         try {
896                                 _stepService.addStepComment(aBadDTO);
897                                 Assert.fail("Creation with filled in id must be failed.");
898                         } catch (InvalidParameterException e) {
899                                 LOG.debug("Expected exception is thrown: "
900                                                 + e.getClass().getSimpleName() + ": " + e.getMessage());
901                         }
902                 }
903         }
904
905         /**
906          * Test of retrieval of all comments corresponding to a step.
907          * 
908          * @throws BusinessException
909          *             if there is something wrong likely unrelated to the tested method
910          */
911         @Test
912         public void testGetStepComments() throws BusinessException {
913
914                 User user = TestEntitiesGenerator.getTestUser("goodUser");
915                 _userDAO.create(user);
916                 Study study = TestEntitiesGenerator.getTestStudy(user);
917
918                 // Before we create the study in the database:
919                 org.splat.som.Step step = new org.splat.som.Step(_projectSettings
920                                 .getStep(1), study);
921                 try {
922                         _stepService.getStepComments(step);
923                         Assert
924                                         .fail("Retrieval by step with non-existing owner project element must be failed.");
925                 } catch (InvalidParameterException e) {
926                         LOG.debug("Expected exception is thrown: "
927                                         + e.getClass().getSimpleName() + ": " + e.getMessage());
928                 }
929
930                 _studyDAO.create(study);
931
932                 StepCommentAttribute matchingStepComment = new StepCommentAttribute(
933                                 study, "matching test comment", new Date(), step.getNumber(),
934                                 user, "matching test comment title");
935                 StepCommentAttribute notMatchingStepComment = new StepCommentAttribute(
936                                 study, "not matching test comment", new Date(), 2, user,
937                                 "not matching test comment title");
938                 _stepCommentAttributeDAO.create(matchingStepComment);
939                 _stepCommentAttributeDAO.create(notMatchingStepComment);
940                 getHibernateTemplate().flush();
941
942                 List<StepCommentDTO> stepComments = _stepService.getStepComments(step);
943                 Assert.assertTrue(stepComments.size() == 1,
944                                 "Wrong number of retrieved comments");
945                 StepCommentDTO stepCommentDTO = stepComments.get(0);
946                 Assert
947                                 .assertTrue(
948                                                 stepCommentDTO.getId().equals(
949                                                                 matchingStepComment.getRid())
950                                                                 && stepCommentDTO.getDate().equals(
951                                                                                 matchingStepComment.getDate())
952                                                                 && stepCommentDTO.getText().equals(
953                                                                                 matchingStepComment.getValue())
954                                                                 && stepCommentDTO.getUser().getIndex() == matchingStepComment
955                                                                                 .getUser().getRid()
956                                                                 && stepCommentDTO.getTitle().equals(
957                                                                                 matchingStepComment.getTitle()),
958                                                 "some of the needed fields of the retrieved comment doesn't match with original.");
959         }
960
961         /**
962          * Test of retrieval of all comments corresponding to a step.
963          * 
964          * @throws BusinessException
965          *             if there is something wrong likely unrelated to the tested method
966          */
967         @Test
968         public void testEditStepComments() throws BusinessException {
969                 LOG.debug(">>>>> BEGIN testEditStepComments()");
970                 startNestedTransaction();
971
972                 User goodUser = TestEntitiesGenerator.getTestUser("goodUser");
973                 _userDAO.create(goodUser);
974                 Study goodStudy = TestEntitiesGenerator.getTestStudy(goodUser);
975                 _studyDAO.create(goodStudy);
976                 getHibernateTemplate().flush();
977
978                 org.splat.som.Step step = new org.splat.som.Step(_projectSettings
979                                 .getStep(1), goodStudy);
980
981                 StepCommentAttribute comment = new StepCommentAttribute(goodStudy,
982                                 "commentValue", new Date(), Integer.valueOf(step.getNumber()),
983                                 goodUser, "commentTitle");
984                 _stepCommentAttributeDAO.saveOrUpdate(comment);
985
986                 getHibernateTemplate().flush();
987
988                 // non-existing id
989                 StepCommentAttribute tmpComment = new StepCommentAttribute(goodStudy,
990                                 "tmpCommentValue", new Date(), Integer
991                                                 .valueOf(step.getNumber()), goodUser, "tmpCommentTitle");
992                 _stepCommentAttributeDAO.create(tmpComment);
993                 long nonExistingId = tmpComment.getIndex();
994                 _stepCommentAttributeDAO.delete(tmpComment);
995                 // getHibernateTemplate().evict(goodUser);
996
997                 try {
998                         _stepService.editStepComment(nonExistingId, "newValue", "newTitle");
999                         getHibernateTemplate().flush();
1000                         Assert.fail("Creation with non-existing user must be failed.");
1001                 } catch (InvalidParameterException e) {
1002                         LOG.debug("Expected exception is thrown: "
1003                                         + e.getClass().getSimpleName() + ": " + e.getMessage());
1004                 }
1005
1006                 // different configurations with valid comment id
1007                 testEdit(comment, "newValue", null);
1008                 testEdit(comment, null, "newTitle");
1009                 testEdit(comment, "veryNewValue", "veryNewTitle");
1010
1011                 rollbackNestedTransaction();
1012                 LOG.debug(">>>>> END testEditStepComments()");
1013         }
1014
1015         /**
1016          * Test of comment editing.
1017          * 
1018          * @param comment
1019          *            the comment
1020          * @param value
1021          *            the value
1022          * @param title
1023          *            the title
1024          * @throws InvalidParameterException
1025          *             if there is something wrong likely unrelated to the tested method
1026          */
1027         private void testEdit(final StepCommentAttribute comment,
1028                         final String value, final String title)
1029                         throws InvalidParameterException {
1030                 String oldValue = comment.getValue();
1031                 String oldTitle = comment.getTitle();
1032
1033                 _stepService.editStepComment(comment.getIndex(), value, title);
1034                 _stepCommentAttributeDAO.flush();
1035                 getHibernateTemplate().evict(comment);
1036                 _stepCommentAttributeDAO.refresh(comment);
1037                 if (value == null) {
1038                         Assert.assertEquals(comment.getValue(), oldValue);
1039                 } else {
1040                         Assert.assertEquals(comment.getValue(), value);
1041                 }
1042                 if (title == null) {
1043                         Assert.assertEquals(comment.getTitle(), oldTitle);
1044                 } else {
1045                         Assert.assertEquals(comment.getTitle(), title);
1046                 }
1047         }
1048
1049         /**
1050          * Create a transient StepCommentDTO.
1051          * 
1052          * @param study
1053          *            must be already persisted into the database
1054          * @param user
1055          *            must be already persisted into the database
1056          * @return a transient StepCommentDTO
1057          * @throws BusinessException
1058          *             if something's wrong
1059          */
1060         private StepCommentDTO createStepCommentDTO(final User user,
1061                         final Study study) throws BusinessException {
1062
1063                 return new StepCommentDTO(null, "A good comment", study.getRid(),
1064                                 new Integer(0), new Date(), user.getRid(), user.getName(),
1065                                 "Good comment title");
1066         }
1067
1068         /**
1069          * Create StepCommentDTO with all the fields filled in from StepCommentAttribute.
1070          * 
1071          * @param comment
1072          *            the comment
1073          * @return Step Comment DTO
1074          */
1075         private StepCommentDTO getDTOfromStepCommentAttribute(
1076                         final StepCommentAttribute comment) {
1077
1078                 StepCommentDTO stepCommentDTO = new StepCommentDTO(comment.getRid(),
1079                                 comment.getValue(), comment.getFrom().getRid(), comment
1080                                                 .getStep(), comment.getDate(), comment.getUser()
1081                                                 .getRid(), comment.getUser().getName(), comment
1082                                                 .getTitle());
1083                 return stepCommentDTO;
1084         }
1085
1086         /**
1087          * Compare StepCommentDTO.
1088          * 
1089          * @param a
1090          *            the first DTO to compare
1091          * @param b
1092          *            the second DTO to compare
1093          * @return true if comments are equal
1094          */
1095         private Boolean compareStepCommentDTO(final StepCommentDTO a,
1096                         final StepCommentDTO b) {
1097                 return a.getId().equals(b.getId()) && a.getId().equals(b.getId())
1098                                 && a.getDate().equals(b.getDate())
1099                                 && a.getStep().equals(b.getStep())
1100                                 && a.getText().equals(b.getText())
1101                                 && a.getUserId().equals(b.getUserId())
1102                                 && a.getProjectElementId().equals(b.getProjectElementId())
1103                                 && a.getTitle().equals(b.getTitle());
1104         }
1105 }