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.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;
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;
55 import test.splat.common.BaseTest;
58 * Test class for PublicationService.
60 * @author <a href="mailto:roman.kozlov@opencascade.com">Roman Kozlov (RKV)</a>
63 public class TestPublicationService extends BaseTest {
66 * Logger for the class.
68 private static final AppLogger LOG = AppLogger
69 .getLogger(TestPublicationService.class);
72 * The StudyDAO. Later injected by Spring.
75 @Qualifier("studyDAO")
76 private transient StudyDAO _studyDAO;
79 * The PublicationService. Later injected by Spring.
82 @Qualifier("publicationService")
83 private transient PublicationService _publicationService;
86 * The ProjectElementService. Later injected by Spring.
89 @Qualifier("projectElementService")
90 private transient ProjectElementService _projectElementService;
93 * The StepService. Later injected by Spring.
96 @Qualifier("stepService")
97 private transient StepService _stepService;
100 * The ProjectSettingsService. Later injected by Spring.
103 @Qualifier("projectSettings")
104 private transient ProjectSettingsService _projectSettings;
107 * The DocumentTypeService. Later injected by Spring.
110 @Qualifier("documentTypeService")
111 private transient DocumentTypeService _documentTypeService;
114 * The StudyService. Later injected by Spring.
117 @Qualifier("studyService")
118 private transient StudyService _studyService;
121 * The RepositoryService. Later injected by Spring.
124 @Qualifier("repositoryService")
125 private transient RepositoryService _repositoryService;
128 * Create a persistent scenario for tests.
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
142 private Study createStudy() throws InvalidPropertyException,
143 MissedPropertyException, MultiplyDefinedException, IOException,
145 // Create a scenario for tests
146 HibernateTemplate ht = getHibernateTemplate();
148 Database.getInstance().reset();
149 _projectSettings.getAllSteps().clear(); // Clear config to be able to load it again
150 // Load workflow customization
152 _projectSettings.configure(ClassLoader.getSystemResource(
153 "test/som.xml").getPath());
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 for (org.splat.som.Step step : steps) {
422 LOG.debug("Create a document for the step " + step.getNumber());
424 List<DocumentType> dtypes = _documentTypeService.selectTypesOf(step
426 if (dtypes.size() > 0) {
427 DocumentType dtype = dtypes.get(0);
428 int oldInd = ht.get(Study.class, aStudyFound.getIndex())
429 .getLastLocalIndex();
431 // Create a file in the download directory
432 String fname = "filename" + step.getNumber() + ".py";
433 String filePath = getDownloadPath(aStudyFound.getAuthor())
435 LOG.debug(step.getStep().getKey() + ": "
436 + step.getOwner().getClass().getSimpleName()
437 + ": Create test file: " + filePath);
438 FileWriter fw = new FileWriter(filePath);
440 .write("Simulation of filename.py file for creating a new document at "
444 Publication addoc = _publicationService.createDoc(aStudyFound
445 .getIndex(), step, dtype.getIndex(), userId, fname,
446 "tstdoc", ProgressState.inWORK, "", "", new Date(),
452 int ind = ht.get(Study.class, aStudyFound.getIndex())
453 .getLastLocalIndex();
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())
462 Assert.assertEquals(aStudy.getLastLocalIndex(), oldInd + 1,
463 "Incremented index must be saved in the database.");
467 rollbackNestedTransaction();
468 LOG.debug(">>>>> END testCreateDoc()");
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>
480 * <B>Outcome results:</B><BR>
483 * <li>The new ConvertsRelation and the new File object must be created in the database.<BR>
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
504 public void testAttach() throws InvalidPropertyException,
505 MissedPropertyException, MultiplyDefinedException, IOException,
506 SQLException, NotApplicableException, InterruptedException,
508 LOG.debug(">>>>> BEGIN testAttach()");
509 startNestedTransaction();
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.");
519 // Call DAO's get method for an existing id.
521 getHibernateTemplate().evict(aStudy);
522 getHibernateTemplate().clear();
523 Study aStudyFound = _studyDAO.get(id);
525 ht.evict(aStudyFound);
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]);
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());
542 for (Publication pub : step.getAllDocuments()) {
544 ht.evict(step.getOwner());
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();
552 ConvertsRelation rel = _publicationService.attach(pub, "py");
556 Assert.assertNotNull(rel,
557 "Returned ConvertsRelation must not be null.");
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.");
582 rollbackNestedTransaction();
583 LOG.debug(">>>>> END testAttach()");
587 * Get path to the user's downloads directory. The directory is created if it is not exist yet.
591 * @return absolute path to downloads directory followed by slash
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());
602 return tmpDir.getAbsolutePath() + "/";