]> SALOME platform Git repositories - tools/siman.git/blob - Workspace/Siman-Common/src/test/splat/service/TestPublicationService.java
Salome HOME
ProjectSettings are now configured when the bean is created (without call to a struts...
[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("classpath:test/som.xml");
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                 DecimalFormat tostring = new DecimalFormat(Document.suformat);
422                 for (org.splat.som.Step step : steps) {
423                         LOG.debug("Create a document for the step " + step.getNumber());
424
425                         List<DocumentType> dtypes = _documentTypeService.selectTypesOf(step
426                                         .getStep());
427                         if (dtypes.size() > 0) {
428                                 DocumentType dtype = dtypes.get(0);
429                                 int oldInd = ht.get(Study.class, aStudyFound.getIndex())
430                                                 .getLastLocalIndex();
431
432                                 // Create a file in the download directory
433                                 String fname = "filename" + step.getNumber() + ".py";
434                                 String filePath = getDownloadPath(aStudyFound.getAuthor())
435                                                 + fname;
436                                 LOG.debug(step.getStep().getKey() + ": "
437                                                 + step.getOwner().getClass().getSimpleName()
438                                                 + ": Create test file: " + filePath);
439                                 FileWriter fw = new FileWriter(filePath);
440                                 fw
441                                                 .write("Simulation of filename.py file for creating a new document at "
442                                                                 + new Date());
443                                 fw.close();
444
445                                 Publication addoc = _publicationService.createDoc(aStudyFound
446                                                 .getIndex(), step, dtype.getIndex(), userId, fname,
447                                                 "tstdoc", ProgressState.inWORK, "", "", new Date(),
448                                                 null);
449
450                                 _studyDAO.flush();
451                                 ht.flush();
452
453                                 int ind = ht.get(Study.class, aStudyFound.getIndex())
454                                                 .getLastLocalIndex();
455
456                                 LOG.debug("Previous index: " + oldInd + ", new index: " + ind);
457                                 Assert.assertEquals(ht.get(Study.class, aStudyFound.getIndex())
458                                                 .getLastLocalIndex(), oldInd + 1,
459                                                 "Incremented index must be saved in the database.");
460                                 aStudy = (Study) ht.find(
461                                                 "from Study where rid = " + aStudyFound.getIndex())
462                                                 .get(0);
463                                 Assert.assertEquals(aStudy.getLastLocalIndex(), oldInd + 1,
464                                                 "Incremented index must be saved in the database.");
465                                 Assert.assertEquals(addoc.getSourceFile().getName(), tostring
466                                                 .format(aStudy.getLastLocalIndex())
467                                                 + "_" + fname, "The generated file name is incorrect.");
468                         }
469                 }
470
471                 rollbackNestedTransaction();
472                 LOG.debug(">>>>> END testCreateDoc()");
473         }
474
475         /**
476          * Test of file attaching to a study document.<BR>
477          * <B>Description :</B> <BR>
478          * <i>Create a study and try to attach a new file to its each document.</i><BR>
479          * <B>Action : </B><BR>
480          * <i>1. call attach method for each document publication of the study.</i><BR>
481          * <B>Test data : </B><BR>
482          * <i>no input parameters</i><BR>
483          * 
484          * <B>Outcome results:</B><BR>
485          * <i>
486          * <ul>
487          * <li>The new ConvertsRelation and the new File object must be created in the database.<BR>
488          * </li>
489          * </ul>
490          * </i>
491          * 
492          * @throws InvalidPropertyException
493          *             if an invalid property is used when creating objects
494          * @throws MultiplyDefinedException
495          *             when trying to create an object with already existing id
496          * @throws MissedPropertyException
497          *             if a mandatory property is not defined for an object to be created
498          * @throws SQLException
499          *             if test study creation is failed
500          * @throws IOException
501          *             if test study creation is failed
502          * @throws ParseException
503          * @throws InterruptedException
504          * @throws NotApplicableException
505          * 
506          */
507         @Test
508         public void testAttach() throws InvalidPropertyException,
509                         MissedPropertyException, MultiplyDefinedException, IOException,
510                         SQLException, NotApplicableException, InterruptedException,
511                         ParseException {
512                 LOG.debug(">>>>> BEGIN testAttach()");
513                 startNestedTransaction();
514
515                 HibernateTemplate ht = getHibernateTemplate();
516                 Study aStudy = createStudy();
517                 // Call DAO's create method for a good transient study.
518                 Long id = aStudy.getIndex();
519                 Assert.assertNotNull(id,
520                                 "Create method returns null instead of a new id.");
521                 Assert.assertTrue(id > 0, "The new id is not a positive number.");
522
523                 // Call DAO's get method for an existing id.
524                 _studyDAO.flush();
525                 getHibernateTemplate().evict(aStudy);
526                 getHibernateTemplate().clear();
527                 Study aStudyFound = _studyDAO.get(id);
528                 ht.clear();
529                 ht.evict(aStudyFound);
530
531                 long userId = aStudyFound.getAuthor().getIndex();
532                 org.splat.som.Step[] studySteps = _projectElementService
533                                 .getSteps(aStudyFound);
534                 org.splat.som.Step[] scSteps = _projectElementService
535                                 .getSteps(aStudyFound.getScenarii()[0]);
536
537                 List<org.splat.som.Step> steps = new ArrayList<org.splat.som.Step>();
538                 steps.addAll(Arrays.asList(studySteps));
539                 steps.addAll(Arrays.asList(scSteps));
540                 steps.addAll(Arrays.asList(studySteps));
541                 for (org.splat.som.Step step : steps) {
542                         LOG.debug("Attach a new .py file to documents of the step "
543                                         + step.getNumber() + ": " + step.getStep().getKey() + ": "
544                                         + step.getOwner().getClass().getSimpleName());
545
546                         for (Publication pub : step.getAllDocuments()) {
547
548                                 ht.evict(step.getOwner());
549                                 ht.evict(pub);
550                                 ht.evict(pub.value());
551                                 int nbConverts = ht.find("from ConvertsRelation").size();
552                                 int nbDocConverts = ht.find(
553                                                 "from ConvertsRelation where owner="
554                                                                 + pub.value().getIndex()).size();
555                                 int nbFiles = ht.find("from File").size();
556
557                                 ConvertsRelation rel = _publicationService.attach(pub, "py");
558
559                                 _studyDAO.flush();
560                                 ht.flush();
561                                 Assert.assertNotNull(rel,
562                                                 "Returned ConvertsRelation must not be null.");
563                                 Assert
564                                                 .assertTrue(rel.isSaved(),
565                                                                 "Returned ConvertsRelation must be saved in the database.");
566                                 Assert.assertEquals(ht.find(
567                                                 "from ConvertsRelation where owner="
568                                                                 + pub.value().getIndex()).size(),
569                                                 nbDocConverts + 1,
570                                                 "Number of created ConvertsRelations must be 1.");
571                                 Assert.assertEquals(ht.find("from ConvertsRelation").size(),
572                                                 nbConverts + 1,
573                                                 "Number of created ConvertsRelations must be 1.");
574                                 Assert.assertNotNull(rel.getTo(),
575                                                 "Attached File must not be null.");
576                                 Assert.assertTrue(rel.isSaved(),
577                                                 "Attached File must be saved in the database.");
578                                 Assert
579                                                 .assertEquals(ht
580                                                                 .find(
581                                                                                 "from File where rid="
582                                                                                                 + rel.getTo().getIndex())
583                                                                 .size(), 1, "Number of created File must be 1.");
584                                 Assert.assertEquals(ht.find("from File").size(), nbFiles + 1,
585                                                 "Number of created Files must be 1.");
586                         }
587                 }
588
589                 rollbackNestedTransaction();
590                 LOG.debug(">>>>> END testAttach()");
591         }
592
593         /**
594          * Get path to the user's downloads directory. The directory is created if it is not exist yet.
595          * 
596          * @param user
597          *            user
598          * @return absolute path to downloads directory followed by slash
599          */
600         private String getDownloadPath(final User user) {
601                 // Prepare download directory
602                 File tmpDir = _repositoryService.getDownloadDirectory(user);
603                 if (!tmpDir.exists()) {
604                         Assert.assertTrue(tmpDir.mkdir(),
605                                         "Can't create temporary directory: "
606                                                         + tmpDir.getAbsolutePath());
607                 }
608
609                 return tmpDir.getAbsolutePath() + "/";
610         }
611
612 }