Salome HOME
Copyrights update 2015.
[tools/siman.git] / 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.Document;
21 import org.splat.dal.bo.som.DocumentType;
22 import org.splat.dal.bo.som.ProjectElement;
23 import org.splat.dal.bo.som.Publication;
24 import org.splat.dal.bo.som.Scenario;
25 import org.splat.dal.bo.som.Study;
26 import org.splat.dal.bo.som.Document.Properties;
27 import org.splat.dal.dao.som.Database;
28 import org.splat.dal.dao.som.StudyDAO;
29 import org.splat.kernel.InvalidPropertyException;
30 import org.splat.kernel.MissedPropertyException;
31 import org.splat.kernel.MultiplyDefinedException;
32 import org.splat.log.AppLogger;
33 import org.splat.service.DocumentTypeService;
34 import org.splat.service.PublicationService;
35 import org.splat.service.StepService;
36 import org.splat.service.StudyService;
37 import org.splat.service.technical.ProjectSettingsService;
38 import org.splat.service.technical.ProjectSettingsService.Step;
39 import org.springframework.beans.factory.annotation.Autowired;
40 import org.springframework.beans.factory.annotation.Qualifier;
41 import org.springframework.orm.hibernate3.HibernateTemplate;
42 import org.testng.Assert;
43 import org.testng.annotations.Test;
44
45 import test.splat.common.BaseTest;
46
47 /**
48  * Test class for StudyService.
49  * 
50  * @author <a href="mailto:roman.kozlov@opencascade.com">Roman Kozlov (RKV)</a>
51  * 
52  */
53 public class TestStudyService extends BaseTest {
54
55         /**
56          * Logger for the class.
57          */
58         private static final AppLogger LOG = AppLogger
59                         .getLogger(TestStudyService.class);
60
61         /**
62          * The StudyDAO. Later injected by Spring.
63          */
64         @Autowired
65         @Qualifier("studyDAO")
66         private transient StudyDAO _studyDAO;
67
68         /**
69          * The PublicationService. Later injected by Spring.
70          */
71         @Autowired
72         @Qualifier("publicationService")
73         private transient PublicationService _publicationService;
74
75         /**
76          * The StepService. Later injected by Spring.
77          */
78         @Autowired
79         @Qualifier("stepService")
80         private transient StepService _stepService;
81
82         /**
83          * The ProjectSettingsService. Later injected by Spring.
84          */
85         @Autowired
86         @Qualifier("projectSettings")
87         private transient ProjectSettingsService _projectSettings;
88
89         /**
90          * The DocumentTypeService. Later injected by Spring.
91          */
92         @Autowired
93         @Qualifier("documentTypeService")
94         private transient DocumentTypeService _documentTypeService;
95
96         /**
97          * The StudyService. Later injected by Spring.
98          */
99         @Autowired
100         @Qualifier("studyService")
101         private transient StudyService _studyService;
102
103         /**
104          * Create a persistent scenario for tests.
105          * 
106          * @return a persistent scenario
107          * @throws InvalidPropertyException
108          *             if an invalid property is used when creating objects
109          * @throws MultiplyDefinedException
110          *             when trying to create an object with already existing id
111          * @throws MissedPropertyException
112          *             if a mandatory property is not defined for an object to be created
113          * @throws IOException
114          *             if document creation is failed
115          * @throws SQLException
116          *             if project settings loading is failed
117          */
118         private Study createStudy() throws InvalidPropertyException,
119                         MissedPropertyException, MultiplyDefinedException, IOException,
120                         SQLException {
121                 // Create a scenario for tests
122                 HibernateTemplate ht = getHibernateTemplate();
123
124                 Database.getInstance().reset();
125                 _projectSettings.getAllSteps().clear(); // Clear config to be able to load it again
126                 // Load workflow customization
127                 try {
128                         _projectSettings.configure(ClassLoader.getSystemResource(
129                                         "test/som.xml").getPath());
130                 } catch (FileNotFoundException e) {
131                         Assert.fail("Can't find som.xml: ", e);
132                 }
133                 List<Step> steps = _projectSettings.getAllSteps();
134                 Assert.assertTrue(steps.size() > 0, "No steps are created.");
135
136                 // Create a test user
137                 User.Properties uprop = new User.Properties();
138                 uprop.setUsername("TST_Username").setName("TST_SimanUnitTestsUser")
139                                 .setFirstName("TST_FirstName").setDisplayName("TST_test.user")
140                                 .addRole("TST_user").setMailAddress(
141                                                 "noreply@salome-platform.org");
142                 uprop.disableCheck();
143                 User anAuthor = new User(uprop);
144                 ht.saveOrUpdate(anAuthor);
145
146                 // Create a test study
147                 Study.Properties stprops = new Study.Properties().setReference(
148                                 "TST_SID_01").setTitle("TST_Study").setManager(anAuthor);
149                 Study aStudy = new Study(stprops);
150                 ht.saveOrUpdate(aStudy);
151
152                 // Create a test scenario
153                 Scenario.Properties sprops = new Scenario.Properties().setTitle(
154                                 "TST_Scenario").setManager(anAuthor).setOwnerStudy(aStudy);
155                 Scenario aScenario = new Scenario(sprops);
156                 aStudy.getScenariiList().add(aScenario);
157                 ht.saveOrUpdate(anAuthor);
158                 ht.saveOrUpdate(aStudy);
159                 ht.saveOrUpdate(aScenario);
160
161                 // Create documents for each scenario step
162                 Document.Properties dprop = new Document.Properties().setAuthor(
163                                 anAuthor).setDate(new Date());
164                 int i = 0;
165                 Publication usedPub = null;
166                 Map<Long, Long> usedMap = new HashMap<Long, Long>();
167                 for (int stepNum = 1; stepNum <= steps.size(); stepNum++) {
168                         Step step = _projectSettings.getStep(stepNum);
169                         LOG.debug("Create scenario step: " + stepNum);
170                         ProjectElement projElem;
171
172                         if (step.appliesTo(Study.class)) {
173                                 projElem = aStudy;
174                         } else {
175                                 projElem = aScenario;
176                         }
177                         org.splat.som.Step aScStep = new org.splat.som.Step(step, projElem);
178                         List<DocumentType> dtypes = _documentTypeService
179                                         .selectTypesOf(step);
180                         if (dtypes.size() > 0) {
181                                 DocumentType dtype = dtypes.get(0);
182                                 // Create a document published in the scenario
183                                 // document<i>: document type[0] - first type used on the step
184                                 // <source-file>.brep
185                                 // <attached-file>.med
186                                 i++;
187                                 dprop.setName("document" + stepNum).setType(dtype);
188                                 if (step.getNumber() > 3) {
189                                         dprop.setFormat("med");
190                                 } else {
191                                         dprop.setFormat("py");
192                                 }
193                                 Publication pub = createDoc(projElem, aScStep, dprop, "med",
194                                                 false);
195                                 if (usedPub != null) {
196                                         pub.addDependency(usedPub);
197                                         LOG.debug("Add dependency: " + pub.value().getTitle()
198                                                         + " from " + usedPub.value().getTitle());
199                                         ht.saveOrUpdate(pub.value());
200                                         ht.flush();
201
202                                         usedMap.put(pub.getIndex(), usedPub.getIndex());
203                                 }
204                                 usedPub = pub;
205                         }
206                         if (dtypes.size() <= 0) {
207                                 LOG.debug("No document types are found for scenario step " + i);
208                         }
209                 }
210
211                 // Check that the scenario and its documents have been created correctly.
212
213                 Assert.assertNotNull(ht.find("from Document"),
214                                 "No documents in the database.");
215                 Assert.assertTrue(ht.find("from Document").size() > 0,
216                                 "No documents in the database.");
217
218                 Assert.assertNotNull(ht.find("from Publication where owner="
219                                 + aScenario.getIndex()), "No publications in the database.");
220                 Assert.assertTrue(
221                                 ht.find("from Publication where owner=" + aScenario.getIndex())
222                                                 .size() > 0, "No publications in the database.");
223
224                 for (Publication p : (List<Publication>) ht
225                                 .find("from Publication where owner=" + aScenario.getIndex())) {
226                         LOG.debug("Publication found: [id=" + p.getIndex() + ", owner="
227                                         + p.getOwner().getIndex() + ", doc=" + p.value().getIndex()
228                                         + "]");
229                         Assert.assertEquals(p.getOwner().getIndex(), aScenario.getIndex(),
230                                         "The publication was not attached to the scenario.");
231                 }
232
233                 // Remove the scenario from the current hibernate session.
234                 ht.evict(aScenario);
235                 // Check that the scenario is created in the database.
236                 Scenario aScen = ht.load(Scenario.class, aScenario.getIndex());
237                 Assert.assertNotNull(aScen, "Scenario was not saved in the database.");
238                 Assert.assertTrue(aScen.getDocums().size() > 0,
239                                 "No publications in the scenario.");
240
241                 Assert.assertTrue(i > 0,
242                                 "More then one document must be in the database");
243
244                 // Check created uses relations
245                 Assert
246                                 .assertTrue(usedMap.size() > 0,
247                                                 "Uses relations must be created.");
248                 boolean foundAny = false;
249                 for (Long usingId : usedMap.keySet()) {
250                         for (Publication pub : aScen.getDocums()) {
251                                 if (pub.getIndex() == usingId) {
252                                         boolean found = false;
253                                         for (Publication used : aScen.getDocums()) {
254                                                 found = (used.getIndex() == usedMap.get(usingId));
255                                                 if (found) {
256                                                         break;
257                                                 }
258                                         }
259                                         if (!found) {
260                                                 for (Publication used : aStudy.getDocums()) {
261                                                         found = (used.getIndex() == usedMap.get(usingId));
262                                                         if (found) {
263                                                                 break;
264                                                         }
265                                                 }
266                                         }
267                                         Assert.assertTrue(found,
268                                                         "Uses relation was not created in the database.");
269                                         foundAny = foundAny || found;
270                                 }
271                         }
272                 }
273                 Assert.assertTrue(foundAny,
274                                 "No Uses relation was created in the database.");
275
276                 return aScenario.getOwnerStudy();
277         }
278
279         /**
280          * Create a document published in the scenario. <BR>
281          * document:<BR>
282          * document type - type used on the step <BR>
283          * &lt;source-file&gt;.brep <BR>
284          * &lt;attached-file&gt;.med
285          * 
286          * @param aScenario
287          *            the scenario to add the document to
288          * @param aScStep
289          *            scenario step where the document to be published
290          * @param dprop
291          *            document properties
292          * @param attachedFileExt
293          *            extension of the secon attached (exported) file
294          * @param isOutdated
295          *            outdated document flag
296          * @return the publication of the created document
297          * @throws IOException
298          * @throws MultiplyDefinedException
299          * @throws InvalidPropertyException
300          * @throws MissedPropertyException
301          */
302         private Publication createDoc(final ProjectElement aScenario,
303                         final org.splat.som.Step aScStep, final Properties dprop,
304                         final String attachedFileExt, final boolean isOutdated)
305                         throws MissedPropertyException, InvalidPropertyException,
306                         MultiplyDefinedException, IOException {
307                 // Create a document published in the scenario
308                 // document<i>: document type - type used on the step
309                 // <source-file>.brep
310                 // <attached-file>.med
311                 Publication pub = _stepService.createDocument(aScStep, dprop);
312                 Assert.assertNotNull(pub.getOwner(),
313                                 "The publication must be attached to the scenario.");
314                 Assert.assertEquals(pub.getOwner().getIndex(), aScenario.getIndex(),
315                                 "The publication was not attached to the scenario.");
316
317                 if (isOutdated) {
318                         pub.setIsnew('O');
319                 }
320                 aScenario.add(pub);
321                 HibernateTemplate ht = getHibernateTemplate();
322                 ht.saveOrUpdate(pub);
323
324                 // Attach a file
325                 ht.save(pub.value());
326                 ht.flush();
327                 ht.saveOrUpdate(_publicationService.attach(pub, attachedFileExt));
328
329                 return pub;
330         }
331
332         /**
333          * Test of generating a study document index.<BR>
334          * <B>Description :</B> <BR>
335          * <i>Create a study and try to generate the next document index.</i><BR>
336          * <B>Action : </B><BR>
337          * <i>1. call DAO's read method for an existing id.</i><BR>
338          * <B>Test data : </B><BR>
339          * <i>no input parameters</i><BR>
340          * 
341          * <B>Outcome results:</B><BR>
342          * <i>
343          * <ul>
344          * <li>The new index must be equal to the incremented old one and saved into the database<BR>
345          * </li>
346          * </ul>
347          * </i>
348          * 
349          * @throws InvalidPropertyException
350          *             if an invalid property is used when creating objects
351          * @throws MultiplyDefinedException
352          *             when trying to create an object with already existing id
353          * @throws MissedPropertyException
354          *             if a mandatory property is not defined for an object to be created
355          * @throws SQLException
356          *             if test study creation is failed
357          * @throws IOException
358          *             if test study creation is failed
359          * 
360          */
361         @Test
362         public void testGenerateLocalIndex() throws InvalidPropertyException,
363                         MissedPropertyException, MultiplyDefinedException, IOException,
364                         SQLException {
365                 LOG.debug(">>>>> BEGIN testGenerateLocalIndex()");
366                 startNestedTransaction();
367
368                 HibernateTemplate ht = getHibernateTemplate();
369                 Study aStudy = createStudy();
370                 // Call DAO's create method for a good transient study.
371                 Long id = aStudy.getIndex();
372                 Assert.assertNotNull(id,
373                                 "Create method returns null instead of a new id.");
374                 Assert.assertTrue(id > 0, "The new id is not a positive number.");
375
376                 // Call DAO's get method for an existing id.
377                 _studyDAO.flush();
378                 getHibernateTemplate().evict(aStudy);
379                 getHibernateTemplate().clear();
380                 Study aStudyFound = _studyDAO.get(id);
381
382                 int oldInd = aStudyFound.getLastLocalIndex();
383                 int ind = _studyService.generateLocalIndex(aStudyFound);
384
385                 _studyDAO.flush();
386                 Assert.assertEquals(ind, oldInd + 1, "Index must be incremented.");
387                 Assert.assertEquals(ind, aStudyFound.getLastLocalIndex(),
388                                 "Index must be incremented.");
389                 Assert.assertEquals(ind, ht.get(Study.class, aStudyFound.getIndex())
390                                 .getLastLocalIndex(),
391                                 "Incremented index must be saved in the database.");
392                 aStudy = (Study)ht.find(
393                                 "from Study where rid = " + aStudyFound.getIndex()).get(0);
394                 Assert.assertEquals(ind, aStudy.getLastLocalIndex(),
395                                 "Incremented index must be saved in the database.");
396
397                 rollbackNestedTransaction();
398                 LOG.debug(">>>>> END testGenerateLocalIndex()");
399         }
400 }