Salome HOME
Default document types mappings are moved from application settings (my.xml) to proje...
[tools/siman.git] / Workspace / Siman-Common / src / test / splat / service / TestScenarioService.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.List;
17
18 import org.splat.dal.bo.kernel.User;
19 import org.splat.dal.bo.som.Document;
20 import org.splat.dal.bo.som.DocumentType;
21 import org.splat.dal.bo.som.Publication;
22 import org.splat.dal.bo.som.Scenario;
23 import org.splat.dal.bo.som.Study;
24 import org.splat.dal.dao.som.ScenarioDAO;
25 import org.splat.kernel.InvalidPropertyException;
26 import org.splat.kernel.MismatchException;
27 import org.splat.kernel.MissedPropertyException;
28 import org.splat.kernel.MultiplyDefinedException;
29 import org.splat.kernel.NotApplicableException;
30 import org.splat.log.AppLogger;
31 import org.splat.service.DocumentTypeService;
32 import org.splat.service.PublicationService;
33 import org.splat.service.ScenarioService;
34 import org.splat.service.StepService;
35 import org.splat.service.dto.DocumentDTO;
36 import org.splat.service.dto.FileDTO;
37 import org.splat.service.dto.StepDTO;
38 import org.splat.service.technical.ProjectSettingsService;
39 import org.splat.service.technical.ProjectSettingsService.Step;
40 import org.springframework.beans.factory.annotation.Autowired;
41 import org.springframework.beans.factory.annotation.Qualifier;
42 import org.springframework.orm.hibernate3.HibernateTemplate;
43 import org.testng.Assert;
44 import org.testng.annotations.Test;
45
46 import test.splat.common.BaseTest;
47
48 /**
49  * Test class for KnowledgeElementDAO.
50  * 
51  * @author <a href="mailto:roman.kozlov@opencascade.com">Roman Kozlov (RKV)</a>
52  * 
53  */
54 public class TestScenarioService extends BaseTest {
55
56         /**
57          * Logger for the class.
58          */
59         private static final AppLogger LOG = AppLogger
60                         .getLogger(TestScenarioService.class);
61
62         /**
63          * The tested ScenarioService. Later injected by Spring.
64          */
65         @Autowired
66         @Qualifier("scenarioService")
67         private transient ScenarioService _scenarioService;
68
69         /**
70          * The Scenario DAO. Later injected by Spring.
71          */
72         @Autowired
73         @Qualifier("scenarioDAO")
74         private transient ScenarioDAO _scenarioDAO;
75
76         /**
77          * The PublicationService. Later injected by Spring.
78          */
79         @Autowired
80         @Qualifier("publicationService")
81         private transient PublicationService _publicationService;
82
83         /**
84          * The StepService. Later injected by Spring.
85          */
86         @Autowired
87         @Qualifier("stepService")
88         private transient StepService _stepService;
89
90         /**
91          * The ProjectSettingsService. Later injected by Spring.
92          */
93         @Autowired
94         @Qualifier("projectSettings")
95         private transient ProjectSettingsService _projectSettings;
96
97         /**
98          * The DocumentTypeService. Later injected by Spring.
99          */
100         @Autowired
101         @Qualifier("documentTypeService")
102         private transient DocumentTypeService _documentTypeService;
103
104         /**
105          * Test of getting a scenario content for building siman-salome.conf.<BR>
106          * <B>Description :</B> <BR>
107          * <i>Create a scenario and try to get an info for it.</i><BR>
108          * <B>Action : </B><BR>
109          * <i>1. call the method for an existing scenario id.</i><BR>
110          * <i>2. call the method for a not existing scenario id.</i><BR>
111          * <B>Test data : </B><BR>
112          * <i>no input parameters</i><BR>
113          * <i>no input parameters</i><BR>
114          * 
115          * <B>Outcome results:</B><BR>
116          * <i>
117          * <ul>
118          * <li>result DTO must contain list of all documents and files<BR>
119          * </li>
120          * <li>Exception is thrown<BR>
121          * </li>
122          * </ul>
123          * </i>
124          * 
125          * @throws InvalidPropertyException
126          *             if an invalid property is used when creating objects
127          * @throws MultiplyDefinedException
128          *             when trying to create an object with already existing id
129          * @throws MissedPropertyException
130          *             if a mandatory property is not defined for an object to be created
131          * @throws IOException
132          *             if scenario creation is failed
133          * @throws SQLException
134          *             if scenario creation is failed
135          */
136         @Test
137         public void testGetScenarioInfo() throws InvalidPropertyException,
138                         MissedPropertyException, MultiplyDefinedException, IOException,
139                         SQLException {
140                 LOG.debug(">>>>> BEGIN testGetScenarioInfo()");
141                 long scenarioId = createScenario();
142                 // Call DAO's create method for a good transient knowledge element.
143                 List<StepDTO> steps = _scenarioService.getScenarioInfo(scenarioId);
144                 Assert.assertNotNull(steps, "List of steps must not be null.");
145                 Assert.assertTrue(steps.size() > 0, "No steps are read.");
146
147                 List<Step> projSteps = _projectSettings.getStepsOf(Scenario.class);
148                 Assert.assertEquals(steps.size(), projSteps.size(),
149                                 "Not all steps are listed.");
150                 int docIndex = 0;
151                 for (StepDTO step : steps) {
152                         LOG.debug("check the step " + step.getNumber() + ":\n" + step);
153                         Assert.assertNotNull(step, "Step DTO must not be null.");
154                         Assert.assertNotNull(step.getKey(), "Step name must not be null.");
155                         Assert.assertFalse(step.getKey().isEmpty(),
156                                         "Step name must not empty.");
157                         Assert.assertTrue(step.getNumber() > 0,
158                                         "Step number must be positive integer.");
159                         Assert.assertNotNull(step.getDocs(),
160                                         "Step documents list must not be null.");
161
162                         Step aProjStep = null;
163                         for (Step projStep : projSteps) {
164                                 if (projStep.getNumber() == step.getNumber()) {
165                                         aProjStep = projStep;
166                                         break;
167                                 }
168                         }
169
170                         List<DocumentType> dtypes = _documentTypeService
171                                         .selectTypesOf(aProjStep);
172                         for (DocumentType dtype : dtypes) {
173                                 Assert.assertTrue(step.getDocs().size() > 0,
174                                                 "Step documents list must not be empty.");
175                                 String docName = "document" + docIndex;
176                                 for (DocumentDTO doc : step.getDocs()) {
177                                         if (docName.equals(doc.getTitle())) {
178                                                 Assert.assertTrue(doc.getId() > 0,
179                                                                 "Document id must be positive integer.");
180                                                 Assert.assertEquals(doc.getTitle(), docName);
181                                                 Assert.assertNotNull(doc.getFiles(),
182                                                                 "Document files list must not be null.");
183                                                 Assert
184                                                                 .assertTrue(doc.getFiles().size() > 1,
185                                                                                 "Document must have more then 1 attached file.");
186
187                                                 for (FileDTO file : doc.getFiles()) {
188                                                         Assert.assertNotNull(file.getPath(),
189                                                                         "File path must not be null.");
190                                                         Assert.assertFalse(file.getPath().isEmpty(),
191                                                                         "File path must not be empty.");
192                                                         /*
193                                                          * <mappings> <document type="geometry"> <import format="brep"/> <!-- Result Shape --> </document> <document
194                                                          * type="model"> <import format="med"/> <!-- Result mesh without input parameters --> </document> <document
195                                                          * type="loads"> <import format="c3m"/> <!-- Input data created interactively --> </document> <document
196                                                          * type="results"> <import format="med"/> <!-- Calculation results source file --> </document> </mappings>
197                                                          */
198                                                         // Check state and processing instruction
199                                                         String fileFormat = file.getPath().substring(
200                                                                         file.getPath().lastIndexOf('.') + 1);
201                                                         /*
202                                                          * if (_projectSettings.doImport(dtype.getName(), fileFormat)) { Assert.assertTrue(file.isResult(), "The file
203                                                          * must be a result file."); } else { Assert.assertFalse(file.isResult(), "The file must be a source file."); }
204                                                          */if ((docIndex % 2) == 0) { // New
205                                                                 Assert.assertEquals(file.getState(), 'Y',
206                                                                                 "File state must be actual ('Y').");
207                                                                 if (_projectSettings.doImport(dtype.getName(),
208                                                                                 fileFormat)) {
209                                                                         Assert.assertEquals(file.getProcessing(),
210                                                                                         "file-import",
211                                                                                         "File must be imported.");
212                                                                 } else {
213                                                                         Assert.assertEquals(file.getProcessing(),
214                                                                                         "file-download",
215                                                                                         "File must be downloaded.");
216                                                                 }
217                                                         } else { // Outdated
218                                                                 Assert.assertEquals(file.getState(), 'O',
219                                                                                 "File state must be actual ('O').");
220                                                                 Assert
221                                                                                 .assertEquals(file.getProcessing(),
222                                                                                                 "file-download",
223                                                                                                 "Outdated document should not be imported but downloaded.");
224                                                         }
225                                                 }
226                                         }
227                                 }
228                                 docIndex++;
229                         }
230                 }
231
232                 // Call DAO's get method for a not existing id.
233                 try {
234                         steps = _scenarioService.getScenarioInfo(-1L);
235                         // getHibernateTemplate().flush();
236                         Assert
237                                         .fail("Getting an object with not existing id must be failed.");
238                 } catch (Exception e) {
239                         LOG.debug("Expected exception is thrown: "
240                                         + e.getClass().getSimpleName() + ": " + e.getMessage());
241                 }
242                 LOG.debug(">>>>> END testGetScenarioInfo()");
243         }
244
245         /**
246          * Test check-in scenario operation to be performed after SALOME session.<BR>
247          * <B>Description :</B> <BR>
248          * <i>Create a scenario and try to check-in it with some simulated SALOME results data.</i><BR>
249          * <B>Action : </B><BR>
250          * <i>1. call the method for an existing scenario id.</i><BR>
251          * <i>2. call the method for a not existing scenario id.</i><BR>
252          * <B>Test data : </B><BR>
253          * <i>no input parameters</i><BR>
254          * <i>no input parameters</i><BR>
255          * 
256          * <B>Outcome results:</B><BR>
257          * <i>
258          * <ul>
259          * <li>New version of existing documents must be created and new documents must be imported for documents with zero id. Correct
260          * relations must be created.<BR>
261          * </li>
262          * <li>Exception is thrown<BR>
263          * </li>
264          * </ul>
265          * </i>
266          * 
267          * @throws InvalidPropertyException
268          *             if an invalid property is used when creating objects
269          * @throws MultiplyDefinedException
270          *             when trying to create an object with already existing id
271          * @throws MissedPropertyException
272          *             if a mandatory property is not defined for an object to be created
273          * @throws IOException
274          *             if scenario creation is failed
275          * @throws SQLException
276          *             if scenario creation is failed
277          * @throws NotApplicableException
278          *             if checkin failed
279          * @throws MismatchException
280          *             if checkin failed
281          */
282         @Test
283         public void testCheckin() throws InvalidPropertyException,
284                         MissedPropertyException, MultiplyDefinedException, IOException,
285                         SQLException, MismatchException, NotApplicableException {
286                 LOG.debug(">>>>> BEGIN testCheckin()");
287                 _projectSettings.configure(ClassLoader
288                                 .getSystemResource("test/som.xml").getPath());
289                 long scenarioId = createScenario();
290                 Scenario aScen = _scenarioDAO.get(scenarioId);
291                 User user = aScen.getAuthor();
292                 long userId = user.getIndex(); // TODO: get id of a test user
293                 // Call DAO's create method for a good transient knowledge element.
294                 List<StepDTO> steps = new ArrayList<StepDTO>();
295
296                 _scenarioService.checkin(scenarioId, userId, steps);
297
298                 // Call DAO's get method for a not existing id.
299                 try {
300                         _scenarioService.checkin(-1, userId, steps);
301                         Assert
302                                         .fail("Check in for scenario with not existing id must be failed.");
303                 } catch (Exception e) {
304                         LOG.debug("Expected exception is thrown: "
305                                         + e.getClass().getSimpleName() + ": " + e.getMessage());
306                 }
307                 LOG.debug(">>>>> END testCheckin()");
308         }
309
310         /**
311          * Create a persistent scenario for tests.
312          * 
313          * @return a persistent scenario
314          * @throws InvalidPropertyException
315          *             if an invalid property is used when creating objects
316          * @throws MultiplyDefinedException
317          *             when trying to create an object with already existing id
318          * @throws MissedPropertyException
319          *             if a mandatory property is not defined for an object to be created
320          * @throws IOException
321          *             if document creation is failed
322          * @throws SQLException
323          *             if project settings loading is failed
324          */
325         private long createScenario() throws InvalidPropertyException,
326                         MissedPropertyException, MultiplyDefinedException, IOException,
327                         SQLException {
328                 // Create a scenario for tests
329                 HibernateTemplate ht = getHibernateTemplate();
330
331                 // Load workflow customization
332                 try {
333                         _projectSettings.configure(ClassLoader.getSystemResource(
334                                         "test/som.xml").getPath());
335                 } catch (FileNotFoundException e) {
336                         Assert.fail("Can't find som.xml: ", e);
337                 }
338                 List<Step> steps = _projectSettings.getStepsOf(Scenario.class);
339                 Assert.assertTrue(steps.size() > 0, "No steps are created.");
340
341                 // Create a test user
342                 User.Properties uprop = new User.Properties();
343                 uprop.setUsername("TST_Username").setName("TST_SimanUnitTestsUser")
344                                 .setFirstName("TST_FirstName").setDisplayName("TST_test.user")
345                                 .addRole("TST_user").setMailAddress(
346                                                 "noreply@salome-platform.org");
347                 uprop.disableCheck();
348                 User anAuthor = new User(uprop);
349                 ht.save(anAuthor);
350
351                 // Create a test study
352                 Study.Properties stprops = new Study.Properties().setReference(
353                                 "TST_SID_01").setTitle("TST_Study").setManager(anAuthor);
354                 Study aStudy = new Study(stprops);
355                 ht.saveOrUpdate(aStudy);
356
357                 // Create a test scenario
358                 Scenario.Properties sprops = new Scenario.Properties().setTitle(
359                                 "TST_Study").setManager(anAuthor).setOwnerStudy(aStudy);
360                 Scenario aScenario = new Scenario(sprops);
361                 aStudy.getScenariiList().add(aScenario);
362                 ht.saveOrUpdate(anAuthor);
363                 ht.saveOrUpdate(aStudy);
364                 ht.saveOrUpdate(aScenario);
365
366                 Document.Properties dprop = new Document.Properties().setAuthor(
367                                 anAuthor).setDate(new Date());
368                 // Create documents
369                 int i = 0;
370                 for (Step step : steps) {
371                         LOG.debug("Create scenario step: " + i);
372
373                         org.splat.som.Step aScStep = new org.splat.som.Step(step, aScenario);
374                         List<DocumentType> dtypes = _documentTypeService
375                                         .selectTypesOf(step);
376                         for (DocumentType dtype : dtypes) {
377                                 dprop.setName("document" + i++).setType(dtype)
378                                                 .setFormat("brep");
379                                 // Create a document published in the scenario
380                                 // document<i>: document type[0] - first type used on the step
381                                 // <source-file>.brep
382                                 // <attached-file>.med
383                                 Publication pub = _stepService.createDocument(aScStep, dprop);
384                                 Assert.assertNotNull(pub.getOwner(),
385                                                 "The publication must be attached to the scenario.");
386                                 Assert.assertEquals(pub.getOwner().getIndex(), aScenario
387                                                 .getIndex(),
388                                                 "The publication was not attached to the scenario.");
389
390                                 aScenario.add(pub);
391                                 ht.saveOrUpdate(pub);
392
393                                 // Attach a file
394                                 ht.saveOrUpdate(pub.value());
395                                 ht.saveOrUpdate(_publicationService.attach(pub, "med"));
396
397                                 // Create a document with outdated publication
398                                 dprop.setName("document" + i++).setType(dtype)
399                                                 .setFormat("brep");
400                                 // Create a document published in the scenario
401                                 // document<i>: document type[0] - first type used on the step
402                                 // <source-file>.brep
403                                 // <attached-file>.med
404                                 pub = _stepService.createDocument(aScStep, dprop);
405                                 Assert.assertNotNull(pub.getOwner(),
406                                                 "The publication must be attached to the scenario.");
407                                 Assert.assertEquals(pub.getOwner().getIndex(), aScenario
408                                                 .getIndex(),
409                                                 "The publication was not attached to the scenario.");
410
411                                 pub.setIsnew('O');
412                                 aScenario.add(pub);
413                                 ht.saveOrUpdate(pub);
414
415                                 // Attach a file
416                                 ht.saveOrUpdate(pub.value());
417                                 ht.saveOrUpdate(_publicationService.attach(pub, "med"));
418
419                         }
420                         if (dtypes.size() <= 0) {
421                                 LOG.debug("No document types are found for scenario step " + i);
422                         }
423                 }
424
425                 Assert.assertNotNull(ht.find("from Document"),
426                                 "No documents in the database.");
427                 Assert.assertTrue(ht.find("from Document").size() > 0,
428                                 "No documents in the database.");
429
430                 Assert.assertNotNull(ht.find("from Publication where owner="
431                                 + aScenario.getIndex()), "No publications in the database.");
432                 Assert.assertTrue(
433                                 ht.find("from Publication where owner=" + aScenario.getIndex())
434                                                 .size() > 0, "No publications in the database.");
435
436                 for (Publication p : (List<Publication>) ht
437                                 .find("from Publication where owner=" + aScenario.getIndex())) {
438                         LOG.debug("Publication found: [id=" + p.getIndex() + ", owner="
439                                         + p.getOwner().getIndex() + ", doc=" + p.value().getIndex()
440                                         + "]");
441                         Assert.assertEquals(p.getOwner().getIndex(), aScenario.getIndex(),
442                                         "The publication was not attached to the scenario.");
443                 }
444
445                 ht.evict(aScenario);
446                 Scenario aScen = ht.load(Scenario.class, aScenario.getIndex());
447                 Assert.assertNotNull(aScen, "Scenario was not saved in the database.");
448                 Assert.assertTrue(aScen.getDocums().size() > 0,
449                                 "No publications in the scenario.");
450
451                 Assert.assertTrue(i > 0,
452                                 "More then one document must be in the database");
453
454                 return aScenario.getIndex();
455         }
456 }