]> SALOME platform Git repositories - tools/siman.git/blob - Workspace/Siman-Common/src/test/splat/service/TestStudyService.java
Salome HOME
ProjectSettings are now configured when the bean is created (without call to a struts...
[tools/siman.git] / Workspace / Siman-Common / src / test / splat / service / TestStudyService.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.Date;
15 import java.util.HashMap;
16 import java.util.List;
17 import java.util.Map;
18
19 import org.splat.dal.bo.kernel.User;
20 import org.splat.dal.bo.som.DescriptionAttribute;
21 import org.splat.dal.bo.som.Document;
22 import org.splat.dal.bo.som.DocumentType;
23 import org.splat.dal.bo.som.ProjectElement;
24 import org.splat.dal.bo.som.Publication;
25 import org.splat.dal.bo.som.Scenario;
26 import org.splat.dal.bo.som.Study;
27 import org.splat.dal.bo.som.Document.Properties;
28 import org.splat.dal.dao.kernel.UserDAO;
29 import org.splat.dal.dao.som.Database;
30 import org.splat.dal.dao.som.StudyDAO;
31 import org.splat.exception.BusinessException;
32 import org.splat.exception.InvalidParameterException;
33 import org.splat.kernel.InvalidPropertyException;
34 import org.splat.kernel.MissedPropertyException;
35 import org.splat.kernel.MultiplyDefinedException;
36 import org.splat.log.AppLogger;
37 import org.splat.service.DocumentTypeService;
38 import org.splat.service.PublicationService;
39 import org.splat.service.StepService;
40 import org.splat.service.StudyService;
41 import org.splat.service.technical.ProjectSettingsService;
42 import org.splat.service.technical.ProjectSettingsService.Step;
43 import org.springframework.beans.factory.annotation.Autowired;
44 import org.springframework.beans.factory.annotation.Qualifier;
45 import org.springframework.orm.hibernate3.HibernateTemplate;
46 import org.testng.Assert;
47 import org.testng.annotations.Test;
48
49 import test.splat.common.BaseTest;
50 import test.splat.util.TestEntitiesGenerator;
51
52 /**
53  * Test class for StudyService.
54  * 
55  * @author <a href="mailto:roman.kozlov@opencascade.com">Roman Kozlov (RKV)</a>
56  * 
57  */
58 public class TestStudyService extends BaseTest {
59
60         /**
61          * Logger for the class.
62          */
63         private static final AppLogger LOG = AppLogger
64                         .getLogger(TestStudyService.class);
65
66         /**
67          * The StudyDAO. Later injected by Spring.
68          */
69         @Autowired
70         @Qualifier("studyDAO")
71         private transient StudyDAO _studyDAO;
72
73         /**
74          * The PublicationService. Later injected by Spring.
75          */
76         @Autowired
77         @Qualifier("publicationService")
78         private transient PublicationService _publicationService;
79
80         /**
81          * The StepService. Later injected by Spring.
82          */
83         @Autowired
84         @Qualifier("stepService")
85         private transient StepService _stepService;
86
87         /**
88          * The ProjectSettingsService. Later injected by Spring.
89          */
90         @Autowired
91         @Qualifier("projectSettings")
92         private transient ProjectSettingsService _projectSettings;
93
94         /**
95          * The DocumentTypeService. Later injected by Spring.
96          */
97         @Autowired
98         @Qualifier("documentTypeService")
99         private transient DocumentTypeService _documentTypeService;
100
101         /**
102          * The StudyService. Later injected by Spring.
103          */
104         @Autowired
105         @Qualifier("studyService")
106         private transient StudyService _studyService;
107         
108         /**
109          * The UserDAO. Later injected by Spring.
110          */
111         @Autowired
112         @Qualifier("userDAO")
113         private transient UserDAO _userDAO;
114
115         /**
116          * Create a persistent scenario for tests.
117          * 
118          * @return a persistent scenario
119          * @throws InvalidPropertyException
120          *             if an invalid property is used when creating objects
121          * @throws MultiplyDefinedException
122          *             when trying to create an object with already existing id
123          * @throws MissedPropertyException
124          *             if a mandatory property is not defined for an object to be created
125          * @throws IOException
126          *             if document creation is failed
127          * @throws SQLException
128          *             if project settings loading is failed
129          */
130         private Study createStudy() throws InvalidPropertyException,
131                         MissedPropertyException, MultiplyDefinedException, IOException,
132                         SQLException {
133                 // Create a scenario for tests
134                 HibernateTemplate ht = getHibernateTemplate();
135
136                 Database.getInstance().reset();
137                 _projectSettings.getAllSteps().clear(); // Clear config to be able to load it again
138                 // Load workflow customization
139                 try {
140                         _projectSettings.configure("classpath:test/som.xml");
141                 } catch (FileNotFoundException e) {
142                         Assert.fail("Can't find som.xml: ", e);
143                 }
144                 List<Step> steps = _projectSettings.getAllSteps();
145                 Assert.assertTrue(steps.size() > 0, "No steps are created.");
146
147                 // Create a test user
148                 User.Properties uprop = new User.Properties();
149                 uprop.setUsername("TST_Username").setName("TST_SimanUnitTestsUser")
150                                 .setFirstName("TST_FirstName").setDisplayName("TST_test.user")
151                                 .addRole("TST_user").setMailAddress(
152                                                 "noreply@salome-platform.org");
153                 uprop.disableCheck();
154                 User anAuthor = new User(uprop);
155                 ht.saveOrUpdate(anAuthor);
156
157                 // Create a test study
158                 Study.Properties stprops = new Study.Properties().setReference(
159                                 "TST_SID_01").setTitle("TST_Study").setManager(anAuthor);
160                 Study aStudy = new Study(stprops);
161                 ht.saveOrUpdate(aStudy);
162
163                 // Create a test scenario
164                 Scenario.Properties sprops = new Scenario.Properties().setTitle(
165                                 "TST_Scenario").setManager(anAuthor).setOwnerStudy(aStudy);
166                 Scenario aScenario = new Scenario(sprops);
167                 aStudy.getScenariiList().add(aScenario);
168                 ht.saveOrUpdate(anAuthor);
169                 ht.saveOrUpdate(aStudy);
170                 ht.saveOrUpdate(aScenario);
171
172                 // Create documents for each scenario step
173                 Document.Properties dprop = new Document.Properties().setAuthor(
174                                 anAuthor).setDate(new Date());
175                 int i = 0;
176                 Publication usedPub = null;
177                 Map<Long, Long> usedMap = new HashMap<Long, Long>();
178                 for (int stepNum = 1; stepNum <= steps.size(); stepNum++) {
179                         Step step = _projectSettings.getStep(stepNum);
180                         LOG.debug("Create scenario step: " + stepNum);
181                         ProjectElement projElem;
182
183                         if (step.appliesTo(Study.class)) {
184                                 projElem = aStudy;
185                         } else {
186                                 projElem = aScenario;
187                         }
188                         org.splat.som.Step aScStep = new org.splat.som.Step(step, projElem);
189                         List<DocumentType> dtypes = _documentTypeService
190                                         .selectTypesOf(step);
191                         if (dtypes.size() > 0) {
192                                 DocumentType dtype = dtypes.get(0);
193                                 // Create a document published in the scenario
194                                 // document<i>: document type[0] - first type used on the step
195                                 // <source-file>.brep
196                                 // <attached-file>.med
197                                 i++;
198                                 dprop.setName("document" + stepNum).setType(dtype);
199                                 if (step.getNumber() > 3) {
200                                         dprop.setFormat("med");
201                                 } else {
202                                         dprop.setFormat("py");
203                                 }
204                                 Publication pub = createDoc(projElem, aScStep, dprop, "med",
205                                                 false);
206                                 if (usedPub != null) {
207                                         pub.addDependency(usedPub);
208                                         LOG.debug("Add dependency: " + pub.value().getTitle()
209                                                         + " from " + usedPub.value().getTitle());
210                                         ht.saveOrUpdate(pub.value());
211                                         ht.flush();
212
213                                         usedMap.put(pub.getIndex(), usedPub.getIndex());
214                                 }
215                                 usedPub = pub;
216                         }
217                         if (dtypes.size() <= 0) {
218                                 LOG.debug("No document types are found for scenario step " + i);
219                         }
220                 }
221
222                 // Check that the scenario and its documents have been created correctly.
223
224                 Assert.assertNotNull(ht.find("from Document"),
225                                 "No documents in the database.");
226                 Assert.assertTrue(ht.find("from Document").size() > 0,
227                                 "No documents in the database.");
228
229                 Assert.assertNotNull(ht.find("from Publication where owner="
230                                 + aScenario.getIndex()), "No publications in the database.");
231                 Assert.assertTrue(
232                                 ht.find("from Publication where owner=" + aScenario.getIndex())
233                                                 .size() > 0, "No publications in the database.");
234
235                 for (Publication p : (List<Publication>) ht
236                                 .find("from Publication where owner=" + aScenario.getIndex())) {
237                         LOG.debug("Publication found: [id=" + p.getIndex() + ", owner="
238                                         + p.getOwner().getIndex() + ", doc=" + p.value().getIndex()
239                                         + "]");
240                         Assert.assertEquals(p.getOwner().getIndex(), aScenario.getIndex(),
241                                         "The publication was not attached to the scenario.");
242                 }
243
244                 // Remove the scenario from the current hibernate session.
245                 ht.evict(aScenario);
246                 // Check that the scenario is created in the database.
247                 Scenario aScen = ht.load(Scenario.class, aScenario.getIndex());
248                 Assert.assertNotNull(aScen, "Scenario was not saved in the database.");
249                 Assert.assertTrue(aScen.getDocums().size() > 0,
250                                 "No publications in the scenario.");
251
252                 Assert.assertTrue(i > 0,
253                                 "More then one document must be in the database");
254
255                 // Check created uses relations
256                 Assert
257                                 .assertTrue(usedMap.size() > 0,
258                                                 "Uses relations must be created.");
259                 boolean foundAny = false;
260                 for (Long usingId : usedMap.keySet()) {
261                         for (Publication pub : aScen.getDocums()) {
262                                 if (pub.getIndex() == usingId) {
263                                         boolean found = false;
264                                         for (Publication used : aScen.getDocums()) {
265                                                 found = (used.getIndex() == usedMap.get(usingId));
266                                                 if (found) {
267                                                         break;
268                                                 }
269                                         }
270                                         if (!found) {
271                                                 for (Publication used : aStudy.getDocums()) {
272                                                         found = (used.getIndex() == usedMap.get(usingId));
273                                                         if (found) {
274                                                                 break;
275                                                         }
276                                                 }
277                                         }
278                                         Assert.assertTrue(found,
279                                                         "Uses relation was not created in the database.");
280                                         foundAny = foundAny || found;
281                                 }
282                         }
283                 }
284                 Assert.assertTrue(foundAny,
285                                 "No Uses relation was created in the database.");
286
287                 return aScenario.getOwnerStudy();
288         }
289
290         /**
291          * Create a document published in the scenario. <BR>
292          * document:<BR>
293          * document type - type used on the step <BR>
294          * &lt;source-file&gt;.brep <BR>
295          * &lt;attached-file&gt;.med
296          * 
297          * @param aScenario
298          *            the scenario to add the document to
299          * @param aScStep
300          *            scenario step where the document to be published
301          * @param dprop
302          *            document properties
303          * @param attachedFileExt
304          *            extension of the secon attached (exported) file
305          * @param isOutdated
306          *            outdated document flag
307          * @return the publication of the created document
308          * @throws IOException
309          * @throws MultiplyDefinedException
310          * @throws InvalidPropertyException
311          * @throws MissedPropertyException
312          */
313         private Publication createDoc(final ProjectElement aScenario,
314                         final org.splat.som.Step aScStep, final Properties dprop,
315                         final String attachedFileExt, final boolean isOutdated)
316                         throws MissedPropertyException, InvalidPropertyException,
317                         MultiplyDefinedException, IOException {
318                 // Create a document published in the scenario
319                 // document<i>: document type - type used on the step
320                 // <source-file>.brep
321                 // <attached-file>.med
322                 Publication pub = _stepService.createDocument(aScStep, dprop);
323                 Assert.assertNotNull(pub.getOwner(),
324                                 "The publication must be attached to the scenario.");
325                 Assert.assertEquals(pub.getOwner().getIndex(), aScenario.getIndex(),
326                                 "The publication was not attached to the scenario.");
327
328                 if (isOutdated) {
329                         pub.setIsnew('O');
330                 }
331                 aScenario.add(pub);
332                 HibernateTemplate ht = getHibernateTemplate();
333                 ht.saveOrUpdate(pub);
334
335                 // Attach a file
336                 ht.save(pub.value());
337                 ht.flush();
338                 ht.saveOrUpdate(_publicationService.attach(pub, attachedFileExt));
339
340                 return pub;
341         }
342
343         /**
344          * Test of generating a study document index.<BR>
345          * <B>Description :</B> <BR>
346          * <i>Create a study and try to generate the next document index.</i><BR>
347          * <B>Action : </B><BR>
348          * <i>1. call DAO's read method for an existing id.</i><BR>
349          * <B>Test data : </B><BR>
350          * <i>no input parameters</i><BR>
351          * 
352          * <B>Outcome results:</B><BR>
353          * <i>
354          * <ul>
355          * <li>The new index must be equal to the incremented old one and saved into the database<BR>
356          * </li>
357          * </ul>
358          * </i>
359          * 
360          * @throws InvalidPropertyException
361          *             if an invalid property is used when creating objects
362          * @throws MultiplyDefinedException
363          *             when trying to create an object with already existing id
364          * @throws MissedPropertyException
365          *             if a mandatory property is not defined for an object to be created
366          * @throws SQLException
367          *             if test study creation is failed
368          * @throws IOException
369          *             if test study creation is failed
370          * 
371          */
372         @Test
373         public void testGenerateLocalIndex() throws InvalidPropertyException,
374                         MissedPropertyException, MultiplyDefinedException, IOException,
375                         SQLException {
376                 LOG.debug(">>>>> BEGIN testGenerateLocalIndex()");
377                 startNestedTransaction();
378
379                 HibernateTemplate ht = getHibernateTemplate();
380                 Study aStudy = createStudy();
381                 // Call DAO's create method for a good transient study.
382                 Long id = aStudy.getIndex();
383                 Assert.assertNotNull(id,
384                                 "Create method returns null instead of a new id.");
385                 Assert.assertTrue(id > 0, "The new id is not a positive number.");
386
387                 // Call DAO's get method for an existing id.
388                 _studyDAO.flush();
389                 getHibernateTemplate().evict(aStudy);
390                 getHibernateTemplate().clear();
391                 Study aStudyFound = _studyDAO.get(id);
392
393                 int oldInd = aStudyFound.getLastLocalIndex();
394                 int ind = _studyService.generateLocalIndex(aStudyFound);
395
396                 _studyDAO.flush();
397                 Assert.assertEquals(ind, oldInd + 1, "Index must be incremented.");
398                 Assert.assertEquals(ind, aStudyFound.getLastLocalIndex(),
399                                 "Index must be incremented.");
400                 Assert.assertEquals(ind, ht.get(Study.class, aStudyFound.getIndex())
401                                 .getLastLocalIndex(),
402                                 "Incremented index must be saved in the database.");
403                 aStudy = (Study)ht.find(
404                                 "from Study where rid = " + aStudyFound.getIndex()).get(0);
405                 Assert.assertEquals(ind, aStudy.getLastLocalIndex(),
406                                 "Incremented index must be saved in the database.");
407
408                 rollbackNestedTransaction();
409                 LOG.debug(">>>>> END testGenerateLocalIndex()");
410         }
411         
412         /**
413          * Test of retrieval of a study description.
414          *
415          * @throws BusinessException if there is something wrong likely unrelated to the tested method
416          */
417         @Test
418         public void testGetDescription() throws BusinessException {
419                 LOG.debug(">>>>> BEGIN testGetDescription()");
420                 startNestedTransaction();
421                 
422                 User user = TestEntitiesGenerator.getTestUser("GoodUser");
423                 _userDAO.create(user);
424                 Study study = TestEntitiesGenerator.getTestStudy(user);
425                 _studyDAO.create(study);
426                 _studyDAO.flush();
427                 Long studyId = Long.valueOf(study.getIndex());
428                 
429                 //Empty description:
430                 Assert.assertNull(_studyService.getDescription(studyId), 
431                                 "returned value for study without description must be null");
432                 
433                 //Not empty description:
434                 study.setAttribute(new DescriptionAttribute(study, "description"));
435                 _studyDAO.update(study);
436                 _studyDAO.flush();
437                 Assert.assertEquals("description", _studyService.getDescription(studyId));
438                 
439                 //null id
440                 try {
441                         _studyService.getDescription(null);
442                         Assert.fail("retrieval with null study id must fail");
443                 } catch(InvalidParameterException e){
444                         LOG.debug("Expected exception is thrown: "
445                                 + e.getClass().getSimpleName() + ": " + e.getMessage());
446                 }
447                 
448                 //Non-existing id
449                 Study tmpStudy = TestEntitiesGenerator.getTestStudy(user);
450                 _studyDAO.create(tmpStudy);
451                 Long nonExistingId = tmpStudy.getIndex();
452                 _studyDAO.delete(tmpStudy);
453                 try {
454                         _studyService.getDescription(nonExistingId);
455                         Assert.fail("retrieval with non-existing study id must fail");
456                 } catch(InvalidParameterException e){
457                         LOG.debug("Expected exception is thrown: "
458                                 + e.getClass().getSimpleName() + ": " + e.getMessage());
459                 }
460
461                 rollbackNestedTransaction();
462                 LOG.debug(">>>>> END testGetDescription()");
463         }
464         
465         /**
466          * Test of setting of a study description.
467          *
468          * @throws BusinessException if there is something wrong likely unrelated to the tested method
469          */
470         @Test
471         public void testSetDescription() throws BusinessException {
472                 LOG.debug(">>>>> BEGIN testSetDescription()");
473                 startNestedTransaction();
474                 
475                 User user = TestEntitiesGenerator.getTestUser("GoodUser");
476                 _userDAO.create(user);
477                 Study study = TestEntitiesGenerator.getTestStudy(user);
478                 _studyDAO.create(study);
479                 _studyDAO.flush();
480                 Long studyId = Long.valueOf(study.getIndex());
481                 
482                 //Setting description for study without any
483                 _studyService.setDescription(studyId, "description");
484
485                 //Resetting description
486                 _studyService.setDescription(studyId, "replaced description");
487                 
488                 //null id
489                 try {
490                         _studyService.setDescription(null, "description");
491                         Assert.fail("setting with null study id must fail");
492                 } catch(InvalidParameterException e){
493                         LOG.debug("Expected exception is thrown: "
494                                 + e.getClass().getSimpleName() + ": " + e.getMessage());
495                 }
496                 
497                 //Non-existing id
498                 Study tmpStudy = TestEntitiesGenerator.getTestStudy(user);
499                 _studyDAO.create(tmpStudy);
500                 Long nonExistingId = tmpStudy.getIndex();
501                 _studyDAO.delete(tmpStudy);
502                 
503                 try {
504                         _studyService.setDescription(nonExistingId, "description");
505                         Assert.fail("retrieval with non-existing study id must fail");
506                 } catch(InvalidParameterException e){
507                         LOG.debug("Expected exception is thrown: "
508                                 + e.getClass().getSimpleName() + ": " + e.getMessage());
509                 }
510
511                 rollbackNestedTransaction();
512                 LOG.debug(">>>>> END testSetDescription()");
513         }
514         
515         /**
516          * Test of removal of a study description.
517          *
518          * @throws BusinessException if there is something wrong likely unrelated to the tested method
519          */
520         @Test
521         public void testRemoveDescription() throws BusinessException {
522                 LOG.debug(">>>>> BEGIN testRemoveDescription()");
523                 startNestedTransaction();
524                 
525                 User user = TestEntitiesGenerator.getTestUser("GoodUser");
526                 _userDAO.create(user);
527                 Study study = TestEntitiesGenerator.getTestStudy(user);
528                 _studyDAO.create(study);
529                 _studyDAO.flush();
530                 Long studyId = Long.valueOf(study.getIndex());
531                 
532                 //Empty description:
533                 Assert.assertFalse(_studyService.removeDescription(studyId), 
534                                 "returned value for study without description must be null");
535                 
536                 //Not empty description:
537                 study.setAttribute(new DescriptionAttribute(study, "description"));
538                 _studyDAO.update(study);
539                 _studyDAO.flush();
540                 Assert.assertTrue(_studyService.removeDescription(studyId), "existing description removal must return true");
541                 
542                 
543                 Assert.assertNull(_studyService.getDescription(studyId), "description hasn't been successfully removed");
544                 
545                 //null id
546                 try {
547                         _studyService.removeDescription(null);
548                         Assert.fail("removal with null study id must fail");
549                 } catch(InvalidParameterException e){
550                         LOG.debug("Expected exception is thrown: "
551                                 + e.getClass().getSimpleName() + ": " + e.getMessage());
552                 }
553                 
554                 //Non-existing id
555                 Study tmpStudy = TestEntitiesGenerator.getTestStudy(user);
556                 _studyDAO.create(tmpStudy);
557                 Long nonExistingId = tmpStudy.getIndex();
558                 _studyDAO.delete(tmpStudy);
559                 try {
560                         _studyService.removeDescription(nonExistingId);
561                         Assert.fail("removal with non-existing study id must fail");
562                 } catch(InvalidParameterException e){
563                         LOG.debug("Expected exception is thrown: "
564                                 + e.getClass().getSimpleName() + ": " + e.getMessage());
565                 }
566
567                 rollbackNestedTransaction();
568                 LOG.debug(">>>>> END testGetDescription()");
569         }
570 }