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