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