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