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("classpath:test/som.xml");
154 } catch (FileNotFoundException e) {
155 Assert.fail("Can't find som.xml: ", e);
157 List<Step> steps = _projectSettings.getAllSteps();
158 Assert.assertTrue(steps.size() > 0, "No steps are created.");
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);
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);
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);
185 // Create documents for each scenario step
186 Document.Properties dprop = new Document.Properties().setAuthor(
187 anAuthor).setDate(new Date());
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;
196 if (step.appliesTo(Study.class)) {
199 projElem = aScenario;
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
211 dprop.setName("document" + stepNum).setType(dtype);
212 if (step.getNumber() > 3) {
213 dprop.setFormat("med");
215 dprop.setFormat("py");
217 Publication pub = createDoc(projElem, aScStep, dprop, "med",
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());
226 usedMap.put(pub.getIndex(), usedPub.getIndex());
230 if (dtypes.size() <= 0) {
231 LOG.debug("No document types are found for scenario step " + i);
235 // Check that the scenario and its documents have been created correctly.
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.");
242 Assert.assertNotNull(ht.find("from Publication where owner="
243 + aScenario.getIndex()), "No publications in the database.");
245 ht.find("from Publication where owner=" + aScenario.getIndex())
246 .size() > 0, "No publications in the database.");
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()
253 Assert.assertEquals(p.getOwner().getIndex(), aScenario.getIndex(),
254 "The publication was not attached to the scenario.");
257 // Remove the scenario from the current hibernate session.
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.");
265 Assert.assertTrue(i > 0,
266 "More then one document must be in the database");
268 // Check created uses relations
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));
284 for (Publication used : aStudy.getDocums()) {
285 found = (used.getIndex() == usedMap.get(usingId));
291 Assert.assertTrue(found,
292 "Uses relation was not created in the database.");
293 foundAny = foundAny || found;
297 Assert.assertTrue(foundAny,
298 "No Uses relation was created in the database.");
300 return aScenario.getOwnerStudy();
304 * Create a document published in the scenario. <BR>
306 * document type - type used on the step <BR>
307 * <source-file>.brep <BR>
308 * <attached-file>.med
311 * the scenario to add the document to
313 * scenario step where the document to be published
315 * document properties
316 * @param attachedFileExt
317 * extension of the secon attached (exported) file
319 * outdated document flag
320 * @return the publication of the created document
321 * @throws IOException
322 * @throws MultiplyDefinedException
323 * @throws InvalidPropertyException
324 * @throws MissedPropertyException
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.");
345 HibernateTemplate ht = getHibernateTemplate();
346 ht.saveOrUpdate(pub);
349 ht.save(pub.value());
351 ht.saveOrUpdate(_publicationService.attach(pub, attachedFileExt));
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>
365 * <B>Outcome results:</B><BR>
368 * <li>The new index must be equal to the incremented old one and saved into the database<BR>
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
389 public void testCreateDoc() throws InvalidPropertyException,
390 MissedPropertyException, MultiplyDefinedException, IOException,
391 SQLException, NotApplicableException, InterruptedException,
393 LOG.debug(">>>>> BEGIN testCreateDoc()");
394 startNestedTransaction();
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.");
404 // Call DAO's get method for an existing id.
406 getHibernateTemplate().evict(aStudy);
407 getHibernateTemplate().clear();
408 Study aStudyFound = _studyDAO.get(id);
409 ht.evict(aStudyFound);
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]);
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());
425 List<DocumentType> dtypes = _documentTypeService.selectTypesOf(step
427 if (dtypes.size() > 0) {
428 DocumentType dtype = dtypes.get(0);
429 int oldInd = ht.get(Study.class, aStudyFound.getIndex())
430 .getLastLocalIndex();
432 // Create a file in the download directory
433 String fname = "filename" + step.getNumber() + ".py";
434 String filePath = getDownloadPath(aStudyFound.getAuthor())
436 LOG.debug(step.getStep().getKey() + ": "
437 + step.getOwner().getClass().getSimpleName()
438 + ": Create test file: " + filePath);
439 FileWriter fw = new FileWriter(filePath);
441 .write("Simulation of filename.py file for creating a new document at "
445 Publication addoc = _publicationService.createDoc(aStudyFound
446 .getIndex(), step, dtype.getIndex(), userId, fname,
447 "tstdoc", ProgressState.inWORK, "", "", new Date(),
453 int ind = ht.get(Study.class, aStudyFound.getIndex())
454 .getLastLocalIndex();
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())
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.");
471 rollbackNestedTransaction();
472 LOG.debug(">>>>> END testCreateDoc()");
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>
484 * <B>Outcome results:</B><BR>
487 * <li>The new ConvertsRelation and the new File object must be created in the database.<BR>
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
508 public void testAttach() throws InvalidPropertyException,
509 MissedPropertyException, MultiplyDefinedException, IOException,
510 SQLException, NotApplicableException, InterruptedException,
512 LOG.debug(">>>>> BEGIN testAttach()");
513 startNestedTransaction();
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.");
523 // Call DAO's get method for an existing id.
525 getHibernateTemplate().evict(aStudy);
526 getHibernateTemplate().clear();
527 Study aStudyFound = _studyDAO.get(id);
529 ht.evict(aStudyFound);
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]);
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());
546 for (Publication pub : step.getAllDocuments()) {
548 ht.evict(step.getOwner());
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();
557 ConvertsRelation rel = _publicationService.attach(pub, "py");
561 Assert.assertNotNull(rel,
562 "Returned ConvertsRelation must not be null.");
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(),
570 "Number of created ConvertsRelations must be 1.");
571 Assert.assertEquals(ht.find("from ConvertsRelation").size(),
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.");
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.");
589 rollbackNestedTransaction();
590 LOG.debug(">>>>> END testAttach()");
594 * Get path to the user's downloads directory. The directory is created if it is not exist yet.
598 * @return absolute path to downloads directory followed by slash
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());
609 return tmpDir.getAbsolutePath() + "/";