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