1 /*****************************************************************************
5 * Creation date 12 Oct 2012
8 *****************************************************************************/
9 package test.splat.service;
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;
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;
56 import test.splat.common.BaseTest;
59 * Test class for PublicationService.
61 * @author <a href="mailto:roman.kozlov@opencascade.com">Roman Kozlov (RKV)</a>
64 public class TestPublicationService extends BaseTest {
67 * Logger for the class.
69 private static final AppLogger LOG = AppLogger
70 .getLogger(TestPublicationService.class);
73 * The StudyDAO. Later injected by Spring.
76 @Qualifier("studyDAO")
77 private transient StudyDAO _studyDAO;
80 * The PublicationService. Later injected by Spring.
83 @Qualifier("publicationService")
84 private transient PublicationService _publicationService;
87 * The ProjectElementService. Later injected by Spring.
90 @Qualifier("projectElementService")
91 private transient ProjectElementService _projectElementService;
94 * The StepService. Later injected by Spring.
97 @Qualifier("stepService")
98 private transient StepService _stepService;
101 * The ProjectSettingsService. Later injected by Spring.
104 @Qualifier("projectSettings")
105 private transient ProjectSettingsService _projectSettings;
108 * The DocumentTypeService. Later injected by Spring.
111 @Qualifier("documentTypeService")
112 private transient DocumentTypeService _documentTypeService;
115 * The StudyService. Later injected by Spring.
118 @Qualifier("studyService")
119 private transient StudyService _studyService;
122 * The RepositoryService. Later injected by Spring.
125 @Qualifier("repositoryService")
126 private transient RepositoryService _repositoryService;
129 * Create a persistent scenario for tests.
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
143 private Study createStudy() throws InvalidPropertyException,
144 MissedPropertyException, MultiplyDefinedException, IOException,
146 // Create a scenario for tests
147 HibernateTemplate ht = getHibernateTemplate();
149 Database.getInstance().reset();
150 _projectSettings.getAllSteps().clear(); // Clear config to be able to load it again
151 // Load workflow customization
153 _projectSettings.configure(ClassLoader.getSystemResource(
154 "test/som.xml").getPath());
155 } catch (FileNotFoundException e) {
156 Assert.fail("Can't find som.xml: ", e);
158 List<Step> steps = _projectSettings.getAllSteps();
159 Assert.assertTrue(steps.size() > 0, "No steps are created.");
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);
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);
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);
186 // Create documents for each scenario step
187 Document.Properties dprop = new Document.Properties().setAuthor(
188 anAuthor).setDate(new Date());
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;
197 if (step.appliesTo(Study.class)) {
200 projElem = aScenario;
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
212 dprop.setName("document" + stepNum).setType(dtype);
213 if (step.getNumber() > 3) {
214 dprop.setFormat("med");
216 dprop.setFormat("py");
218 Publication pub = createDoc(projElem, aScStep, dprop, "med",
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());
227 usedMap.put(pub.getIndex(), usedPub.getIndex());
231 if (dtypes.size() <= 0) {
232 LOG.debug("No document types are found for scenario step " + i);
236 // Check that the scenario and its documents have been created correctly.
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.");
243 Assert.assertNotNull(ht.find("from Publication where owner="
244 + aScenario.getIndex()), "No publications in the database.");
246 ht.find("from Publication where owner=" + aScenario.getIndex())
247 .size() > 0, "No publications in the database.");
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()
254 Assert.assertEquals(p.getOwner().getIndex(), aScenario.getIndex(),
255 "The publication was not attached to the scenario.");
258 // Remove the scenario from the current hibernate session.
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.");
266 Assert.assertTrue(i > 0,
267 "More then one document must be in the database");
269 // Check created uses relations
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));
285 for (Publication used : aStudy.getDocums()) {
286 found = (used.getIndex() == usedMap.get(usingId));
292 Assert.assertTrue(found,
293 "Uses relation was not created in the database.");
294 foundAny = foundAny || found;
298 Assert.assertTrue(foundAny,
299 "No Uses relation was created in the database.");
301 return aScenario.getOwnerStudy();
305 * Create a document published in the scenario. <BR>
307 * document type - type used on the step <BR>
308 * <source-file>.brep <BR>
309 * <attached-file>.med
312 * the scenario to add the document to
314 * scenario step where the document to be published
316 * document properties
317 * @param attachedFileExt
318 * extension of the secon attached (exported) file
320 * outdated document flag
321 * @return the publication of the created document
322 * @throws IOException
323 * @throws MultiplyDefinedException
324 * @throws InvalidPropertyException
325 * @throws MissedPropertyException
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.");
346 HibernateTemplate ht = getHibernateTemplate();
347 ht.saveOrUpdate(pub);
350 ht.save(pub.value());
352 ht.saveOrUpdate(_publicationService.attach(pub, attachedFileExt));
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>
366 * <B>Outcome results:</B><BR>
369 * <li>The new index must be equal to the incremented old one and saved into the database<BR>
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
390 public void testCreateDoc() throws InvalidPropertyException,
391 MissedPropertyException, MultiplyDefinedException, IOException,
392 SQLException, NotApplicableException, InterruptedException,
394 LOG.debug(">>>>> BEGIN testCreateDoc()");
395 startNestedTransaction();
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.");
405 // Call DAO's get method for an existing id.
407 getHibernateTemplate().evict(aStudy);
408 getHibernateTemplate().clear();
409 Study aStudyFound = _studyDAO.get(id);
410 ht.evict(aStudyFound);
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]);
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());
426 List<DocumentType> dtypes = _documentTypeService.selectTypesOf(step
428 if (dtypes.size() > 0) {
429 DocumentType dtype = dtypes.get(0);
430 int oldInd = ht.get(Study.class, aStudyFound.getIndex())
431 .getLastLocalIndex();
433 // Create a file in the download directory
434 String fname = "filename" + step.getNumber() + ".py";
435 String filePath = getDownloadPath(aStudyFound.getAuthor())
437 LOG.debug(step.getStep().getKey() + ": "
438 + step.getOwner().getClass().getSimpleName()
439 + ": Create test file: " + filePath);
440 FileWriter fw = new FileWriter(filePath);
442 .write("Simulation of filename.py file for creating a new document at "
446 Publication addoc = _publicationService.createDoc(aStudyFound
447 .getIndex(), step, dtype.getIndex(), userId, fname,
448 "tstdoc", ProgressState.inWORK, "", "", new Date(),
454 int ind = ht.get(Study.class, aStudyFound.getIndex())
455 .getLastLocalIndex();
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())
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.");
472 rollbackNestedTransaction();
473 LOG.debug(">>>>> END testCreateDoc()");
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>
485 * <B>Outcome results:</B><BR>
488 * <li>The new ConvertsRelation and the new File object must be created in the database.<BR>
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
509 public void testAttach() throws InvalidPropertyException,
510 MissedPropertyException, MultiplyDefinedException, IOException,
511 SQLException, NotApplicableException, InterruptedException,
513 LOG.debug(">>>>> BEGIN testAttach()");
514 startNestedTransaction();
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.");
524 // Call DAO's get method for an existing id.
526 getHibernateTemplate().evict(aStudy);
527 getHibernateTemplate().clear();
528 Study aStudyFound = _studyDAO.get(id);
530 ht.evict(aStudyFound);
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]);
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());
547 for (Publication pub : step.getAllDocuments()) {
549 ht.evict(step.getOwner());
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();
558 ConvertsRelation rel = _publicationService.attach(pub, "py");
562 Assert.assertNotNull(rel,
563 "Returned ConvertsRelation must not be null.");
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(),
571 "Number of created ConvertsRelations must be 1.");
572 Assert.assertEquals(ht.find("from ConvertsRelation").size(),
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.");
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.");
590 rollbackNestedTransaction();
591 LOG.debug(">>>>> END testAttach()");
595 * Get path to the user's downloads directory. The directory is created if it is not exist yet.
599 * @return absolute path to downloads directory followed by slash
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());
610 return tmpDir.getAbsolutePath() + "/";