]> SALOME platform Git repositories - tools/siman.git/blob - Workspace/Siman-Common/src/test/splat/service/TestStepService.java
Salome HOME
Fix of checkin and removeDocument.
[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.getStepsMap(aStudy);
320                 Map<Integer, org.splat.som.Step> scSteps = _projectElementService.getStepsMap(aScen);
321                 org.splat.som.Step aScStep;
322                 for (int i = _projectSettings.getAllSteps().size(); i > 0; i--) {
323                         LOG.debug("Remove documents from the step " + i);
324                         step = _projectSettings.getStep(i);
325                         if (step.appliesTo(Study.class)) {
326                                 projElem = aStudy;
327                                 aScStep = stSteps.get(step.getNumber());
328                         } else {
329                                 projElem = aScen;
330                                 aScStep = scSteps.get(step.getNumber());
331                         }
332
333                         if (aScStep.getDocuments().size() > 0) {
334                                 docId = aScStep.getDocuments().get(0).value().getIndex();
335                                 LOG.debug("Remove document#" + docId + " "
336                                                 + aScStep.getDocument(docId).value().getTitle());
337                                 ht.flush();
338                                 List<UsesRelation> uses = ht
339                                                 .find("from UsesRelation where owner=" + docId);
340                                 List<UsedByRelation> usedBy = ht
341                                                 .find("from UsedByRelation where owner=" + docId);
342                                 LOG.debug("From db: It uses following " + uses.size()
343                                                 + " documents: ");
344                                 for (UsesRelation rel : uses) {
345                                         LOG.debug(rel.getTo().getTitle());
346                                 }
347                                 LOG.debug("From step: It uses following "
348                                                 + aScStep.getDocument(docId).getRelations(
349                                                                 UsesRelation.class).size() + " documents: ");
350                                 for (Publication rel : aScStep.getDocument(docId).getRelations(
351                                                 UsesRelation.class)) {
352                                         LOG.debug(rel.value().getTitle());
353                                 }
354                                 LOG.debug("From db: It is used by following " + usedBy.size()
355                                                 + " documents: ");
356                                 for (UsedByRelation rel : usedBy) {
357                                         LOG.debug(rel.getTo().getTitle());
358                                 }
359                                 LOG.debug("From step: It is used by following "
360                                                 + aScStep.getDocument(docId).getRelations(
361                                                                 UsedByRelation.class).size() + " documents: ");
362                                 for (Publication rel : aScStep.getDocument(docId).getRelations(
363                                                 UsedByRelation.class)) {
364                                         LOG.debug(rel.value().getTitle());
365                                 }
366                                 Assert.assertEquals(ht.find("from Document where rid=" + docId)
367                                                 .size(), 1, "Nothing to delete.");
368
369                                  ht.evict(aScStep.getDocuments().get(0).value()
370                                  .getFile());
371                                  LOG.debug("Load file#" + aScStep.getDocuments().get(0).value()
372                                  .getRelations(ConvertsRelation.class).get(0).getTo().getIndex());
373                                 
374                                 ht.flush();
375                                 ht.clear();
376                                  File f = _fileDAO.get(aScStep.getDocuments().get(0).value()
377                                  .getRelations(ConvertsRelation.class).get(0).getTo().getIndex());
378                                  ht.evict(aScStep.getDocuments().get(0).value());
379
380                                 ok = _stepService.removeDocument(aScStep, docId);
381
382                                 nbRemovedDoc++;
383                                 removedDocs.add(docId);
384
385                                 Assert.assertTrue(ok, "Removing was failed.");
386                                 _scenarioDAO.flush();
387                                 ht.flush();
388
389                                 for (Long id : removedDocs) {
390                                         String title = "";
391                                         if (ht.get(Document.class, id) != null) {
392                                                 title = ht.get(Document.class, id).getTitle();
393                                         }
394                                         Assert.assertEquals(ht
395                                                         .find("from Document where rid=" + id).size(), 0,
396                                                         "Document#" + id + "(" + title
397                                                                         + ") was not removed from the database.");
398                                 }
399
400                                 Assert.assertEquals(ht.find("from Document").size(), nbDoc
401                                                 - nbRemovedDoc,
402                                                 "Documents were not removed from the database.");
403                                 Assert.assertEquals(ht.find(
404                                                 "from UsesRelation where owner=" + docId).size(), 0,
405                                                 "UsesRelation(s) were not removed from the database.");
406                                 Assert
407                                                 .assertEquals(ht.find(
408                                                                 "from UsedByRelation where owner=" + docId)
409                                                                 .size(), 0,
410                                                                 "UsedByRelation(s) were not removed from the database.");
411                                 Assert
412                                                 .assertEquals(ht.find(
413                                                                 "from UsesRelation where refer=" + docId)
414                                                                 .size(), 0,
415                                                                 "Referencing UsesRelation(s) were not removed from the database.");
416                                 Assert
417                                                 .assertEquals(ht.find(
418                                                                 "from UsedByRelation where refer=" + docId)
419                                                                 .size(), 0,
420                                                                 "Referencing UsedByRelation(s) were not removed from the database.");
421                                 Assert
422                                                 .assertEquals(ht.find(
423                                                                 "from ConvertsRelation where owner=" + docId)
424                                                                 .size(), 0,
425                                                                 "ConvertsRelation(s) were not removed from the database.");
426                         }
427                 }
428
429                 Assert
430                                 .assertEquals(ht.find("from Document").size(), nbDoc
431                                                 - nbRemovedDoc,
432                                                 "Documents were not removed from the database.");
433
434                 Assert.assertEquals(ht.find("from File").size(), 0,
435                                 "Files were not removed from the database.");
436
437                 Assert.assertEquals(ht.find(
438                                 "from Publication where owner=" + aScen.getIndex()).size(), 0,
439                                 "Publications were not removed from the database.");
440
441                 Assert.assertEquals(ht.find("from UsesRelation").size(), 0,
442                                 "Uses relations were not removed from the database.");
443
444                 Assert.assertEquals(ht.find("from UsedByRelation").size(), 0,
445                                 "UsedBy relations were not removed from the database.");
446
447                 rollbackNestedTransaction();
448                 LOG.debug(">>>>> END testRemoveDocument()");
449         }
450
451         /**
452          * Create a persistent scenario for tests.
453          * 
454          * @return a persistent scenario
455          * @throws InvalidPropertyException
456          *             if an invalid property is used when creating objects
457          * @throws MultiplyDefinedException
458          *             when trying to create an object with already existing id
459          * @throws MissedPropertyException
460          *             if a mandatory property is not defined for an object to be created
461          * @throws IOException
462          *             if document creation is failed
463          * @throws SQLException
464          *             if project settings loading is failed
465          */
466         private long createScenario() throws InvalidPropertyException,
467                         MissedPropertyException, MultiplyDefinedException, IOException,
468                         SQLException {
469                 // Create a scenario for tests
470                 HibernateTemplate ht = getHibernateTemplate();
471
472                 Database.getInstance().reset();
473                 _projectSettings.getAllSteps().clear(); // Clear config to be able to load it again
474                 // Load workflow customization
475                 try {
476                         _projectSettings.configure("classpath:test/som.xml");
477                 } catch (FileNotFoundException e) {
478                         Assert.fail("Can't find som.xml: ", e);
479                 }
480                 List<Step> steps = _projectSettings.getAllSteps();
481                 Assert.assertTrue(steps.size() > 0, "No steps are created.");
482
483                 // Create a test user
484                 User.Properties uprop = new User.Properties();
485                 uprop.setUsername("TST_Username").setName("TST_SimanUnitTestsUser")
486                                 .setFirstName("TST_FirstName").setDisplayName("TST_test.user")
487                                 .addRole("TST_user").setMailAddress(
488                                                 "noreply@salome-platform.org");
489                 uprop.disableCheck();
490                 User anAuthor = new User(uprop);
491                 ht.saveOrUpdate(anAuthor);
492
493                 // Create a test study
494                 Study.Properties stprops = new Study.Properties().setReference(
495                                 "TST_SID_01").setTitle("TST_Study").setManager(anAuthor);
496                 Study aStudy = new Study(stprops);
497                 ht.saveOrUpdate(aStudy);
498
499                 // Create a test scenario
500                 Scenario.Properties sprops = new Scenario.Properties().setTitle(
501                                 "TST_Scenario").setManager(anAuthor).setOwnerStudy(aStudy);
502                 Scenario aScenario = new Scenario(sprops);
503                 aStudy.getScenariiList().add(aScenario);
504                 ht.saveOrUpdate(anAuthor);
505                 ht.saveOrUpdate(aStudy);
506                 ht.saveOrUpdate(aScenario);
507
508                 // Create documents for each scenario step
509                 Document.Properties dprop = new Document.Properties().setAuthor(
510                                 anAuthor).setDate(new Date());
511                 int i = 0;
512                 Publication usedPub = null;
513                 Map<Long, Long> usedMap = new HashMap<Long, Long>();
514                 for (int stepNum = 1; stepNum <= steps.size(); stepNum++) {
515                         Step step = _projectSettings.getStep(stepNum);
516                         LOG.debug("Create scenario step: " + stepNum);
517                         ProjectElement projElem;
518
519                         if (step.appliesTo(Study.class)) {
520                                 projElem = aStudy;
521                         } else {
522                                 projElem = aScenario;
523                         }
524                         org.splat.som.Step aScStep = new org.splat.som.Step(step, projElem);
525                         List<DocumentType> dtypes = _documentTypeService
526                                         .selectTypesOf(step);
527                         if (dtypes.size() > 0) {
528                                 DocumentType dtype = dtypes.get(0);
529                                 // Create a document published in the scenario
530                                 // document<i>: document type[0] - first type used on the step
531                                 // <source-file>.brep
532                                 // <attached-file>.med
533                                 i++;
534                                 dprop.setName("document" + stepNum).setType(dtype);
535                                 if (step.getNumber() > 3) {
536                                         dprop.setFormat("med");
537                                 } else {
538                                         dprop.setFormat("py");
539                                 }
540                                 Publication pub = createDoc(projElem, aScStep, dprop, "med",
541                                                 false);
542                                 if (usedPub != null) {
543                                         pub.addDependency(usedPub);
544                                         LOG.debug("Add dependency: " + pub.value().getTitle()
545                                                         + " from " + usedPub.value().getTitle());
546                                         ht.saveOrUpdate(pub.value());
547                                         ht.flush();
548
549                                         usedMap.put(pub.getIndex(), usedPub.getIndex());
550                                 }
551                                 usedPub = pub;
552                         }
553                         if (dtypes.size() <= 0) {
554                                 LOG.debug("No document types are found for scenario step " + i);
555                         }
556                 }
557
558                 // Check that the scenario and its documents have been created correctly.
559
560                 Assert.assertNotNull(ht.find("from Document"),
561                                 "No documents in the database.");
562                 Assert.assertTrue(ht.find("from Document").size() > 0,
563                                 "No documents in the database.");
564
565                 Assert.assertNotNull(ht.find("from Publication where owner="
566                                 + aScenario.getIndex()), "No publications in the database.");
567                 Assert.assertTrue(
568                                 ht.find("from Publication where owner=" + aScenario.getIndex())
569                                                 .size() > 0, "No publications in the database.");
570
571                 for (Publication p : (List<Publication>) ht
572                                 .find("from Publication where owner=" + aScenario.getIndex())) {
573                         LOG.debug("Publication found: [id=" + p.getIndex() + ", owner="
574                                         + p.getOwner().getIndex() + ", doc=" + p.value().getIndex()
575                                         + "]");
576                         Assert.assertEquals(p.getOwner().getIndex(), aScenario.getIndex(),
577                                         "The publication was not attached to the scenario.");
578                 }
579
580                 // Remove the scenario from the current hibernate session.
581                 ht.evict(aScenario);
582                 // Check that the scenario is created in the database.
583                 Scenario aScen = ht.load(Scenario.class, aScenario.getIndex());
584                 Assert.assertNotNull(aScen, "Scenario was not saved in the database.");
585                 Assert.assertTrue(aScen.getDocums().size() > 0,
586                                 "No publications in the scenario.");
587
588                 Assert.assertTrue(i > 0,
589                                 "More then one document must be in the database");
590
591                 // Check created uses relations
592                 Assert
593                                 .assertTrue(usedMap.size() > 0,
594                                                 "Uses relations must be created.");
595                 boolean foundAny = false;
596                 for (Long usingId : usedMap.keySet()) {
597                         for (Publication pub : aScen.getDocums()) {
598                                 if (pub.getIndex() == usingId) {
599                                         boolean found = false;
600                                         for (Publication used : aScen.getDocums()) {
601                                                 found = (used.getIndex() == usedMap.get(usingId));
602                                                 if (found) {
603                                                         break;
604                                                 }
605                                         }
606                                         if (!found) {
607                                                 for (Publication used : aStudy.getDocums()) {
608                                                         found = (used.getIndex() == usedMap.get(usingId));
609                                                         if (found) {
610                                                                 break;
611                                                         }
612                                                 }
613                                         }
614                                         Assert.assertTrue(found,
615                                                         "Uses relation was not created in the database.");
616                                         foundAny = foundAny || found;
617                                 }
618                         }
619                 }
620                 Assert.assertTrue(foundAny,
621                                 "No Uses relation was created in the database.");
622
623                 return aScenario.getIndex();
624         }
625
626         /**
627          * Create a document published in the scenario. <BR>
628          * document:<BR>
629          * document type - type used on the step <BR>
630          * &lt;source-file&gt;.brep <BR>
631          * &lt;attached-file&gt;.med
632          * 
633          * @param aScenario
634          *            the scenario to add the document to
635          * @param aScStep
636          *            scenario step where the document to be published
637          * @param dprop
638          *            document properties
639          * @param attachedFileExt
640          *            extension of the secon attached (exported) file
641          * @param isOutdated
642          *            outdated document flag
643          * @return the publication of the created document
644          * @throws IOException
645          * @throws MultiplyDefinedException
646          * @throws InvalidPropertyException
647          * @throws MissedPropertyException
648          */
649         private Publication createDoc(final ProjectElement aScenario,
650                         final org.splat.som.Step aScStep, final Properties dprop,
651                         final String attachedFileExt, final boolean isOutdated)
652                         throws MissedPropertyException, InvalidPropertyException,
653                         MultiplyDefinedException, IOException {
654                 // Create a document published in the scenario
655                 // document<i>: document type - type used on the step
656                 // <source-file>.brep
657                 // <attached-file>.med
658                 Publication pub = _stepService.createDocument(aScStep, dprop);
659                 Assert.assertNotNull(pub.getOwner(),
660                                 "The publication must be attached to the scenario.");
661                 Assert.assertEquals(pub.getOwner().getIndex(), aScenario.getIndex(),
662                                 "The publication was not attached to the scenario.");
663
664                 if (isOutdated) {
665                         pub.setIsnew('O');
666                 }
667                 aScenario.add(pub);
668                 HibernateTemplate ht = getHibernateTemplate();
669                 ht.saveOrUpdate(pub);
670
671                 // Attach a file
672                 ht.save(pub.value());
673                 ht.flush();
674                 ht.saveOrUpdate(_publicationService.attach(pub, attachedFileExt));
675
676                 return pub;
677         }
678
679         /**
680          * Test of addition of a new step comment.
681          * 
682          * @throws BusinessException
683          *             if there is something wrong likely unrelated to the tested method
684          */
685         @Test
686         public void testAddStepComment() throws BusinessException {
687
688                 User goodUser = TestEntitiesGenerator.getTestUser("goodUser");
689                 _userDAO.create(goodUser);
690                 Study goodStudy = TestEntitiesGenerator.getTestStudy(goodUser);
691                 _studyDAO.create(goodStudy);
692                 getHibernateTemplate().flush();
693                 StepCommentDTO goodStepCommentDTO = createStepCommentDTO(goodUser,
694                                 goodStudy);
695
696                 // valid DTO, existing params
697                 _stepService.addStepComment(goodStepCommentDTO);
698                 Long id = goodStepCommentDTO.getId();
699                 Assert
700                                 .assertNotNull(id,
701                                                 "Add method returns null instead of a new id.");
702                 Assert.assertTrue(id > 0, "The new id is not a positive number.");
703                 StepCommentDTO retrievedComment = getDTOfromStepCommentAttribute(_stepCommentAttributeDAO
704                                 .get(id));
705                 Assert.assertTrue(compareStepCommentDTO(goodStepCommentDTO,
706                                 retrievedComment),
707                                 "The comment created in database has wrong data");
708
709                 // valid DTO, non-existing user
710                 {
711                         // get a non-existing id
712                         User badUser = TestEntitiesGenerator.getTestUser("badUser");
713                         _userDAO.create(badUser);
714                         getHibernateTemplate().evict(badUser);// so createStepCommentDTO will invoke an
715                         // actual query to the base, not cache, in order to check if the user already exists
716                         StepCommentDTO aBadDTO = createStepCommentDTO(badUser, goodStudy);
717
718                         try {
719                                 _stepService.addStepComment(aBadDTO);
720                                 getHibernateTemplate().flush();
721                                 Assert.fail("Creation with non-existing user must be failed.");
722                         } catch (InvalidParameterException e) {
723                                 LOG.debug("Expected exception is thrown: "
724                                                 + e.getClass().getSimpleName() + ": " + e.getMessage());
725                         }
726                 }
727
728                 // valid DTO, non-existing project element
729                 {
730                         Study badStudy = TestEntitiesGenerator.getTestStudy(goodUser);
731                         _studyDAO.create(badStudy);
732                         getHibernateTemplate().evict(badStudy);// so createStepCommentDTO will invoke an
733                         // actual query to the base, not cache in order to check if the study already exists
734                         StepCommentDTO aBadDTO = createStepCommentDTO(goodUser, badStudy);
735
736                         try {
737                                 _stepService.addStepComment(aBadDTO);
738                                 Assert.fail("Creation with non-existing user must be failed.");
739                         } catch (InvalidParameterException e) {
740                                 LOG.debug("Expected exception is thrown: "
741                                                 + e.getClass().getSimpleName() + ": " + e.getMessage());
742                         }
743                 }
744
745                 // not valid DTO (id filled in)
746                 {
747                         StepCommentDTO aBadDTO = createStepCommentDTO(goodUser, goodStudy);
748                         aBadDTO.setId(goodStepCommentDTO.getId());
749
750                         try {
751                                 _stepService.addStepComment(aBadDTO);
752                                 Assert.fail("Creation with filled in id must be failed.");
753                         } catch (InvalidParameterException e) {
754                                 LOG.debug("Expected exception is thrown: "
755                                                 + e.getClass().getSimpleName() + ": " + e.getMessage());
756                         }
757                 }
758         }
759
760         /**
761          * Test of retrieval of all comments corresponding to a step.
762          * 
763          * @throws BusinessException
764          *             if there is something wrong likely unrelated to the tested method
765          */
766         @Test
767         public void testGetStepComments() throws BusinessException {
768
769                 User user = TestEntitiesGenerator.getTestUser("goodUser");
770                 _userDAO.create(user);
771                 Study study = TestEntitiesGenerator.getTestStudy(user);
772
773                 // Before we create the study in the database:
774                 org.splat.som.Step step = new org.splat.som.Step(_projectSettings
775                                 .getStep(1), study);
776                 try {
777                         _stepService.getStepComments(step);
778                         Assert
779                                         .fail("Retrieval by step with non-existing owner project element must be failed.");
780                 } catch (InvalidParameterException e) {
781                         LOG.debug("Expected exception is thrown: "
782                                         + e.getClass().getSimpleName() + ": " + e.getMessage());
783                 }
784
785                 _studyDAO.create(study);
786
787                 StepCommentAttribute matchingStepComment = new StepCommentAttribute(
788                                 study, "matching test comment", new Date(), step.getNumber(),
789                                 user, "matching test comment title");
790                 StepCommentAttribute notMatchingStepComment = new StepCommentAttribute(
791                                 study, "not matching test comment", new Date(), 2, user,
792                                 "not matching test comment title");
793                 _stepCommentAttributeDAO.create(matchingStepComment);
794                 _stepCommentAttributeDAO.create(notMatchingStepComment);
795                 getHibernateTemplate().flush();
796
797                 List<StepCommentDTO> stepComments = _stepService.getStepComments(step);
798                 Assert.assertTrue(stepComments.size() == 1,
799                                 "Wrong number of retrieved comments");
800                 StepCommentDTO stepCommentDTO = stepComments.get(0);
801                 Assert
802                                 .assertTrue(
803                                                 stepCommentDTO.getId().equals(
804                                                                 matchingStepComment.getRid())
805                                                                 && stepCommentDTO.getDate().equals(
806                                                                                 matchingStepComment.getDate())
807                                                                 && stepCommentDTO.getText().equals(
808                                                                                 matchingStepComment.getValue())
809                                                                 && stepCommentDTO.getUser().getIndex() == matchingStepComment
810                                                                                 .getUser().getRid()
811                                                                 && stepCommentDTO.getTitle().equals(
812                                                                                 matchingStepComment.getTitle()),
813                                                 "some of the needed fields of the retrieved comment doesn't match with original.");
814         }
815
816         /**
817          * Test of retrieval of all comments corresponding to a step.
818          * 
819          * @throws BusinessException
820          *             if there is something wrong likely unrelated to the tested method
821          */
822         @Test
823         public void testEditStepComments() throws BusinessException {
824                 LOG.debug(">>>>> BEGIN testEditStepComments()");
825                 startNestedTransaction();
826
827                 User goodUser = TestEntitiesGenerator.getTestUser("goodUser");
828                 _userDAO.create(goodUser);
829                 Study goodStudy = TestEntitiesGenerator.getTestStudy(goodUser);
830                 _studyDAO.create(goodStudy);
831                 getHibernateTemplate().flush();
832
833                 org.splat.som.Step step = new org.splat.som.Step(_projectSettings
834                                 .getStep(1), goodStudy);
835
836                 StepCommentAttribute comment = new StepCommentAttribute(goodStudy,
837                                 "commentValue", new Date(), Integer.valueOf(step.getNumber()),
838                                 goodUser, "commentTitle");
839                 _stepCommentAttributeDAO.saveOrUpdate(comment);
840
841                 getHibernateTemplate().flush();
842
843                 // non-existing id
844                 StepCommentAttribute tmpComment = new StepCommentAttribute(goodStudy,
845                                 "tmpCommentValue", new Date(), Integer
846                                                 .valueOf(step.getNumber()), goodUser, "tmpCommentTitle");
847                 _stepCommentAttributeDAO.create(tmpComment);
848                 long nonExistingId = tmpComment.getIndex();
849                 _stepCommentAttributeDAO.delete(tmpComment);
850                 // getHibernateTemplate().evict(goodUser);
851
852                 try {
853                         _stepService.editStepComment(nonExistingId, "newValue", "newTitle");
854                         getHibernateTemplate().flush();
855                         Assert.fail("Creation with non-existing user must be failed.");
856                 } catch (InvalidParameterException e) {
857                         LOG.debug("Expected exception is thrown: "
858                                         + e.getClass().getSimpleName() + ": " + e.getMessage());
859                 }
860
861                 // different configurations with valid comment id
862                 testEdit(comment, "newValue", null);
863                 testEdit(comment, null, "newTitle");
864                 testEdit(comment, "veryNewValue", "veryNewTitle");
865
866                 rollbackNestedTransaction();
867                 LOG.debug(">>>>> END testEditStepComments()");
868         }
869
870         /**
871          * Test of comment editing.
872          * 
873          * @param comment
874          *            the comment
875          * @param value
876          *            the value
877          * @param title
878          *            the title
879          * @throws InvalidParameterException
880          *             if there is something wrong likely unrelated to the tested method
881          */
882         private void testEdit(final StepCommentAttribute comment,
883                         final String value, final String title)
884                         throws InvalidParameterException {
885                 String oldValue = comment.getValue();
886                 String oldTitle = comment.getTitle();
887
888                 _stepService.editStepComment(comment.getIndex(), value, title);
889                 _stepCommentAttributeDAO.flush();
890                 getHibernateTemplate().evict(comment);
891                 _stepCommentAttributeDAO.refresh(comment);
892                 if (value == null) {
893                         Assert.assertEquals(comment.getValue(), oldValue);
894                 } else {
895                         Assert.assertEquals(comment.getValue(), value);
896                 }
897                 if (title == null) {
898                         Assert.assertEquals(comment.getTitle(), oldTitle);
899                 } else {
900                         Assert.assertEquals(comment.getTitle(), title);
901                 }
902         }
903
904         /**
905          * Create a transient StepCommentDTO.
906          * 
907          * @param study
908          *            must be already persisted into the database
909          * @param user
910          *            must be already persisted into the database
911          * @return a transient StepCommentDTO
912          * @throws BusinessException
913          *             if something's wrong
914          */
915         private StepCommentDTO createStepCommentDTO(final User user,
916                         final Study study) throws BusinessException {
917
918                 return new StepCommentDTO(null, "A good comment", study.getRid(),
919                                 new Integer(0), new Date(), user.getRid(), user.getName(),
920                                 "Good comment title");
921         }
922
923         /**
924          * Create StepCommentDTO with all the fields filled in from StepCommentAttribute.
925          * 
926          * @param comment
927          *            the comment
928          * @return Step Comment DTO
929          */
930         private StepCommentDTO getDTOfromStepCommentAttribute(
931                         final StepCommentAttribute comment) {
932
933                 StepCommentDTO stepCommentDTO = new StepCommentDTO(comment.getRid(),
934                                 comment.getValue(), comment.getFrom().getRid(), comment
935                                                 .getStep(), comment.getDate(), comment.getUser()
936                                                 .getRid(), comment.getUser().getName(), comment
937                                                 .getTitle());
938                 return stepCommentDTO;
939         }
940
941         /**
942          * Compare StepCommentDTO.
943          * 
944          * @param a
945          *            the first DTO to compare
946          * @param b
947          *            the second DTO to compare
948          * @return true if comments are equal
949          */
950         private Boolean compareStepCommentDTO(final StepCommentDTO a,
951                         final StepCommentDTO b) {
952                 return a.getId().equals(b.getId()) && a.getId().equals(b.getId())
953                                 && a.getDate().equals(b.getDate())
954                                 && a.getStep().equals(b.getStep())
955                                 && a.getText().equals(b.getText())
956                                 && a.getUserId().equals(b.getUserId())
957                                 && a.getProjectElementId().equals(b.getProjectElementId())
958                                 && a.getTitle().equals(b.getTitle());
959         }
960 }