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