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.util.ArrayList;
17 import java.util.Date;
18 import java.util.HashMap;
19 import java.util.Iterator;
20 import java.util.List;
24 import org.splat.dal.bo.kernel.Relation;
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.KnowledgeElementType;
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.SimulationContext;
34 import org.splat.dal.bo.som.SimulationContextType;
35 import org.splat.dal.bo.som.Study;
36 import org.splat.dal.bo.som.UsedByRelation;
37 import org.splat.dal.bo.som.UsesRelation;
38 import org.splat.dal.bo.som.ValidationCycle;
39 import org.splat.dal.bo.som.ValidationCycleRelation;
40 import org.splat.dal.bo.som.ValidationStep;
41 import org.splat.dal.bo.som.Document.Properties;
42 import org.splat.dal.dao.kernel.UserDAO;
43 import org.splat.dal.dao.som.Database;
44 import org.splat.dal.dao.som.ScenarioDAO;
45 import org.splat.dal.dao.som.StudyDAO;
46 import org.splat.dal.dao.som.ValidationCycleDAO;
47 import org.splat.exception.BusinessException;
48 import org.splat.exception.InvalidParameterException;
49 import org.splat.i18n.I18nUtils;
50 import org.splat.kernel.InvalidPropertyException;
51 import org.splat.kernel.MismatchException;
52 import org.splat.kernel.MissedPropertyException;
53 import org.splat.kernel.MultiplyDefinedException;
54 import org.splat.kernel.NotApplicableException;
55 import org.splat.log.AppLogger;
56 import org.splat.service.DocumentTypeService;
57 import org.splat.service.KnowledgeElementTypeService;
58 import org.splat.service.ProjectElementService;
59 import org.splat.service.PublicationService;
60 import org.splat.service.ScenarioService;
61 import org.splat.service.SimulationContextService;
62 import org.splat.service.StepService;
63 import org.splat.service.StudyService;
64 import org.splat.service.dto.DocumentDTO;
65 import org.splat.service.dto.FileDTO;
66 import org.splat.service.dto.ScenarioDTO;
67 import org.splat.service.dto.StepDTO;
68 import org.splat.service.technical.ProjectSettingsService;
69 import org.splat.service.technical.RepositoryService;
70 import org.splat.service.technical.StepsConfigService;
71 import org.splat.service.technical.ProjectSettingsService.Step;
72 import org.springframework.beans.factory.annotation.Autowired;
73 import org.springframework.beans.factory.annotation.Qualifier;
74 import org.springframework.orm.hibernate3.HibernateTemplate;
75 import org.testng.Assert;
76 import org.testng.annotations.Test;
77 import org.testng.reporters.Files;
79 import test.splat.common.BaseTest;
80 import test.splat.util.TestEntitiesGenerator;
83 * Test class for ScenarioService.
85 * @author <a href="mailto:roman.kozlov@opencascade.com">Roman Kozlov (RKV)</a>
88 public class TestScenarioService extends BaseTest {
91 * Logger for the class.
93 private static final AppLogger LOG = AppLogger
94 .getLogger(TestScenarioService.class);
97 * The tested ScenarioService. Later injected by Spring.
100 @Qualifier("scenarioService")
101 private transient ScenarioService _scenarioService;
104 * The RepositoryService. Later injected by Spring.
107 @Qualifier("repositoryService")
108 private transient RepositoryService _repositoryService;
111 * The Scenario DAO. Later injected by Spring.
114 @Qualifier("scenarioDAO")
115 private transient ScenarioDAO _scenarioDAO;
118 * The PublicationService. Later injected by Spring.
121 @Qualifier("publicationService")
122 private transient PublicationService _publicationService;
125 * The StepService. Later injected by Spring.
128 @Qualifier("stepService")
129 private transient StepService _stepService;
132 * The SimulationContextService. Later injected by Spring.
135 @Qualifier("simulationContextService")
136 private transient SimulationContextService _simulationContextService;
139 * The ProjectSettingsService. Later injected by Spring.
142 @Qualifier("projectSettings")
143 private transient ProjectSettingsService _projectSettings;
146 * The StepsConfigService. Later injected by Spring.
149 @Qualifier("stepsConfigService")
150 private transient StepsConfigService _stepsConfigService;
153 * The DocumentTypeService. Later injected by Spring.
156 @Qualifier("documentTypeService")
157 private transient DocumentTypeService _documentTypeService;
160 * The KnowledgeElementTypeService. Later injected by Spring.
163 @Qualifier("knowledgeElementTypeService")
164 private transient KnowledgeElementTypeService _knowledgeElementTypeService;
167 * The UserDAO. Later injected by Spring.
170 @Qualifier("userDAO")
171 private transient UserDAO _userDAO;
174 * The StudyService. Later injected by Spring.
177 @Qualifier("studyService")
178 private transient StudyService _studyService;
181 * The StudyDAO. Later injected by Spring.
184 @Qualifier("studyDAO")
185 private transient StudyDAO _studyDAO;
188 * The ValidationCycleDAO. Later injected by Spring.
191 @Qualifier("validationCycleDAO")
192 private transient ValidationCycleDAO _validationCycleDAO;
195 * The ProjectElementService. Later injected by Spring.
198 @Qualifier("projectElementService")
199 private transient ProjectElementService _projectElementService;
202 * Test of getting a scenario content for building siman-salome.conf.<BR>
203 * <B>Description :</B> <BR>
204 * <i>Create a scenario and try to get an info for it.</i><BR>
205 * <B>Action : </B><BR>
206 * <i>1. call the method for an existing scenario id.</i><BR>
207 * <i>2. call the method for a not existing scenario id.</i><BR>
208 * <B>Test data : </B><BR>
209 * <i>no input parameters</i><BR>
210 * <i>no input parameters</i><BR>
212 * <B>Outcome results:</B><BR>
215 * <li>result DTO must contain list of all documents and files<BR>
217 * <li>Exception is thrown<BR>
222 * @throws InvalidPropertyException
223 * if an invalid property is used when creating objects
224 * @throws MultiplyDefinedException
225 * when trying to create an object with already existing id
226 * @throws MissedPropertyException
227 * if a mandatory property is not defined for an object to be created
228 * @throws IOException
229 * if scenario creation is failed
230 * @throws SQLException
231 * if scenario creation is failed
233 @Test(groups = { "checkout", "sevice", "functional", "business" })
234 public void testGetScenarioInfo() throws InvalidPropertyException,
235 MissedPropertyException, MultiplyDefinedException, IOException,
237 LOG.debug(">>>>> BEGIN testGetScenarioInfo()");
238 startNestedTransaction();
240 long scenarioId = createScenario();
241 // Call DAO's create method for a good transient knowledge element.
242 List<StepDTO> steps = _scenarioService.getScenarioInfo(scenarioId);
243 Assert.assertNotNull(steps, "List of steps must not be null.");
244 Assert.assertTrue(steps.size() > 0, "No steps are read.");
246 List<Step> projSteps = _stepsConfigService.getStepsOf(Scenario.class);
247 Assert.assertEquals(steps.size(), projSteps.size(),
248 "Not all steps are listed.");
250 for (StepDTO step : steps) {
251 LOG.debug("check the step " + step.getNumber() + ":\n" + step);
252 Assert.assertNotNull(step, "Step DTO must not be null.");
253 Assert.assertNotNull(step.getKey(), "Step name must not be null.");
254 Assert.assertFalse(step.getKey().isEmpty(),
255 "Step name must not empty.");
256 Assert.assertTrue(step.getNumber() > 0,
257 "Step number must be positive integer.");
258 Assert.assertNotNull(step.getDocs(),
259 "Step documents list must not be null.");
261 Step aProjStep = null;
262 for (Step projStep : projSteps) {
263 if (projStep.getNumber() == step.getNumber()) {
264 aProjStep = projStep;
269 List<DocumentType> dtypes = _documentTypeService
270 .selectTypesOf(aProjStep);
271 for (DocumentType dtype : dtypes) {
272 Assert.assertTrue(step.getDocs().size() > 0,
273 "Step documents list must not be empty.");
274 String docName = "document" + docIndex;
275 for (DocumentDTO doc : step.getDocs()) {
276 if (docName.equals(doc.getTitle())) {
277 Assert.assertTrue(doc.getId() > 0,
278 "Document id must be positive integer.");
279 Assert.assertEquals(doc.getTitle(), docName);
280 Assert.assertNotNull(doc.getFiles(),
281 "Document files list must not be null.");
283 .assertTrue(doc.getFiles().size() > 1,
284 "Document must have more then 1 attached file.");
286 for (FileDTO file : doc.getFiles()) {
287 Assert.assertNotNull(file.getPath(),
288 "File path must not be null.");
289 Assert.assertFalse(file.getPath().isEmpty(),
290 "File path must not be empty.");
292 * <mappings> <document type="geometry"> <import format="brep"/> <!-- Result Shape --> </document> <document
293 * type="model"> <import format="med"/> <!-- Result mesh without input parameters --> </document> <document
294 * type="loads"> <import format="c3m"/> <!-- Input data created interactively --> </document> <document
295 * type="results"> <import format="med"/> <!-- Calculation results source file --> </document> </mappings>
297 // Check state and processing instruction
298 String fileFormat = file.getPath().substring(
299 file.getPath().lastIndexOf('.') + 1);
301 * if (_projectSettings.doImport(dtype.getName(), fileFormat)) { Assert.assertTrue(file.isResult(), "The file
302 * must be a result file."); } else { Assert.assertFalse(file.isResult(), "The file must be a source file."); }
303 */if ((docIndex % 2) == 0) { // New
304 Assert.assertEquals(file.getState(), 'Y',
305 "File state must be actual ('Y').");
306 if (_projectSettings.doImport(dtype.getName(),
308 Assert.assertEquals(file.getProcessing(),
310 "File must be imported.");
312 Assert.assertEquals(file.getProcessing(),
314 "File must be downloaded.");
317 Assert.assertEquals(file.getState(), 'O',
318 "File state must be outdated ('O').");
320 .assertEquals(file.getProcessing(),
322 "Outdated document should not be imported but downloaded.");
331 // Call DAO's get method for a not existing id.
333 steps = _scenarioService.getScenarioInfo(-1L);
334 // getHibernateTemplate().flush();
336 .fail("Getting an object with not existing id must be failed.");
337 } catch (Exception e) {
338 LOG.debug("Expected exception is thrown: "
339 + e.getClass().getSimpleName() + ": " + e.getMessage());
341 rollbackNestedTransaction();
342 LOG.debug(">>>>> END testGetScenarioInfo()");
346 * Test check-in scenario operation to be performed after SALOME session.<BR>
347 * <B>Description :</B> <BR>
348 * <i>Create a scenario and try to check-in it with some simulated SALOME results data.<BR>
349 * After check-in verify following points:
351 * <li>scenario is no more marked as checked out</li>
352 * <li>new document versions are created for checked in documents</li>
353 * <li>presentation of the previous version is removed</li>
354 * <li>uses relations are copied correctly</li>
355 * <li>files are moved correctly</li>
356 * <li>formats of files are new if they are according to the document's type on the study step</li>
357 * <li>new documents are created for new data</li>
358 * <li>new documents have correctly generated names</li>
359 * <li>uses relations are created correctly</li>
360 * <li>files are moved correctly</li>
363 * <B>Action : </B><BR>
364 * <i>1. call the method for an existing scenario id.</i><BR>
365 * <i>2. call the method for a not existing scenario id.</i><BR>
366 * <B>Test data : </B><BR>
367 * <i>no input parameters</i><BR>
368 * <i>no input parameters</i><BR>
370 * <B>Outcome results:</B><BR>
373 * <li>New version of existing documents must be created and new documents must be imported for documents with zero id. Correct
374 * relations must be created.<BR>
376 * <li>Exception is thrown<BR>
381 * @throws InvalidPropertyException
382 * if an invalid property is used when creating objects
383 * @throws MultiplyDefinedException
384 * when trying to create an object with already existing id
385 * @throws MissedPropertyException
386 * if a mandatory property is not defined for an object to be created
387 * @throws IOException
388 * if scenario creation is failed
389 * @throws SQLException
390 * if scenario creation is failed
391 * @throws NotApplicableException
393 * @throws MismatchException
396 @Test(groups = { "checkin", "sevice", "functional", "business" })
397 public void testCheckin() throws InvalidPropertyException,
398 MissedPropertyException, MultiplyDefinedException, IOException,
399 SQLException, MismatchException, NotApplicableException {
400 LOG.debug(">>>>> BEGIN testCheckin()");
401 startNestedTransaction();
403 _projectSettings.getAllSteps().clear(); // Clear config to be able to load it again
404 _projectSettings.configure("classpath:test/som.xml");
405 getHibernateTemplate().flush();
406 long scenarioId = createScenario();
407 Scenario aScen = _scenarioDAO.get(scenarioId);
408 User user = aScen.getAuthor();
409 long userId = user.getIndex();
411 // ////////////////////////////////////////////////////////
412 // Call checkin method for empty list of modules.
415 List<StepDTO> steps = _scenarioService.getScenarioInfo(scenarioId);
416 _scenarioService.checkout(aScen, user);
417 _scenarioDAO.flush();
418 // Check that scenario is no more marked as checked out
419 aScen = _scenarioDAO.get(scenarioId);
420 Assert.assertTrue(aScen.isCheckedout(),
421 "Scenario is not marked as checked out after checkout.");
423 // Prepare test data for checkin
424 // Checkin only two first steps (geom and mesh)
425 List<StepDTO> stepsToCheckin = new ArrayList<StepDTO>();
427 _scenarioService.checkin(scenarioId, userId, stepsToCheckin);
429 _scenarioDAO.flush();
430 // Check that scenario is no more marked as checked out
431 aScen = _scenarioDAO.get(scenarioId);
432 Assert.assertFalse(aScen.isCheckedout(),
433 "Scenario is still marked as checked out after checkin.");
435 // ////////////////////////////////////////////////////////
436 // Call checkin method for good prepared transient data.
439 steps = _scenarioService.getScenarioInfo(scenarioId);
440 _scenarioService.checkout(aScen, user);
442 // Remember modification dates of all attached files
443 Map<Long, Date> dates = new HashMap<Long, Date>();
444 for (Publication p : aScen.getDocums()) {
445 for (Relation r : p.value().getRelations(ConvertsRelation.class)) {
446 org.splat.dal.bo.som.File attach = ((ConvertsRelation) r)
448 dates.put(attach.getIndex(), attach.getDate());
452 // Prepare test data for checkin
453 // Checkin only two first steps (geom and mesh)
454 for (StepDTO step : steps) {
455 // Prepare GEOM: checkin actual brep
456 StepDTO stepToCheckin = createDocDTOForModule(null, "GEOM", "brep",
457 userId, step, stepsToCheckin);
458 createDocDTOForModule(stepToCheckin, "SMESH", "med", userId, step,
462 _scenarioService.checkin(scenarioId, userId, stepsToCheckin);
464 _scenarioDAO.flush();
465 // Check that scenario is no more marked as checked out
466 aScen = _scenarioDAO.get(scenarioId);
467 Assert.assertFalse(aScen.isCheckedout(),
468 "Scenario is still marked as checked out after checkin.");
469 boolean modifDatesChecked = false;
470 // Check that new document versions are created for checked in documents
471 for (StepDTO step : stepsToCheckin) {
472 for (DocumentDTO docDTO : step.getDocs()) {
473 if ((docDTO.getId() != 0) && (docDTO.getId() != null)) {
474 boolean found = false;
475 Document prevDoc = null;
476 Document curDoc = null;
477 Publication newPub = null;
478 for (Publication pub : aScen.getDocums()) {
479 prevDoc = pub.value().getPreviousVersion();
480 if (prevDoc != null) {
481 found = (prevDoc.getIndex() == docDTO.getId());
482 if (found) { // Found next published version of the checked in document
487 if (pub.value().getIndex() == docDTO.getId()) {
488 // Document version was not changed, old document is still published
489 curDoc = pub.value();
493 Assert.assertTrue(found || (curDoc != null),
494 "New version or new attached file of the existing checked in document \""
495 + docDTO.getTitle() + "\" (id="
497 + ") is not found in the scenario.");
498 // If previous version is found then the format must be the same
499 String newFormat = docDTO.getFiles().get(0).getPath()
501 docDTO.getFiles().get(0).getPath()
502 .lastIndexOf('.') + 1);
504 Assert.assertEquals(prevDoc.getFormat(), newFormat,
505 "Formats of versions must be same");
506 Assert.assertFalse(aScen.publishes(prevDoc));
507 // Check that presentation of the previous version is removed
508 checkFiles(docDTO, newPub);
510 // Formats of files are new if they are according to the document's type on the study step
511 if ("py".equals(prevDoc.getFormat())
512 && "geometry".equals(prevDoc.getType()
514 Assert.assertEquals(newPub.value().getFormat(),
516 Assert.assertEquals(newPub.getSourceFile()
517 .getFormat(), "brep");
518 Assert.assertEquals(newPub.getSourceFile()
519 .getRelativePath().substring(
520 newPub.getSourceFile()
522 .lastIndexOf('.') + 1),
526 // Check that uses relations are copied correctly
528 // 1. Get all uses relations of the previous document version
529 for (Relation rel : prevDoc
530 .getRelations(UsesRelation.class)) {
531 Document used = ((UsesRelation) rel).getTo();
532 // 2.1. Get the latest version of the document published in this scenario
533 Publication toBeUsed = aScen.getPublication(used);
534 if (toBeUsed == null) {
535 // Find the latest published version
536 for (Publication lastPub : aScen.getDocums()) {
537 if ((lastPub.value().getPreviousVersion() != null)
539 .getPreviousVersion()
547 if ((toBeUsed != null) && (!toBeUsed.isOutdated())) {
548 // 2.2. For each used document check that its latest not outdated version
549 // is used by the new checked in document version.
550 checkUsesRelation(newPub, toBeUsed);
553 // 1. Get all usedBy relations of the previous document version
554 for (Relation rel : prevDoc
555 .getRelations(UsedByRelation.class)) {
556 Document using = ((UsedByRelation) rel).getTo();
557 // Check that not checked in dependent documents became outdated
558 Publication usingPub = aScen.getPublication(using);
559 if (usingPub != null) { // if the document using the old version is still published
560 Assert.assertTrue(usingPub.isOutdated(),
561 "Not checked in dependent document "
562 + using.getTitle() + " ("
563 + using.getType().getName()
564 + ") must become outdated.");
568 // Otherwise the new file format must differ from the previous one
569 // and the new file must be attached to the same document
570 org.splat.dal.bo.som.File attFile = curDoc
571 .getAttachedFile(newFormat);
572 Assert.assertNotNull(attFile, "File "
573 + docDTO.getFiles().get(0).getPath()
574 + " must be attached to the document "
575 + docDTO.getTitle() + "#" + docDTO.getId());
576 Assert.assertTrue(attFile.asFile().exists(), "File "
577 + docDTO.getFiles().get(0).getPath()
578 + " attached to the document "
579 + docDTO.getTitle() + "#" + docDTO.getId()
581 LOG.debug("Source format: " + curDoc.getFormat()
582 + ", new format: " + newFormat);
583 // Check that attachment with the same format is not duplicated.
585 for (Relation conv : curDoc
586 .getRelations(ConvertsRelation.class)) {
587 if (newFormat.equals(((ConvertsRelation) conv)
588 .getTo().getFormat())) {
593 .assertEquals(attachNb, 1,
594 "Attachment with the same format must be only one.");
596 // Check that the attached file date is updated
597 if (dates.containsKey(attFile.getIndex())) {
599 .assertTrue(attFile.getDate().compareTo(
600 dates.get(attFile.getIndex())) > 0,
601 "Attachment modification date is not updated.");
602 modifDatesChecked = true;
607 // Check that new documents are created for new data
608 boolean found = false;
609 Publication newPub = null;
610 for (Publication pub : aScen.getDocums()) {
611 if (pub.value().getPreviousVersion() == null) {
612 found = (pub.value().getTitle().startsWith(pub
613 .value().getType().getName()));
614 if (found) { // Found next published version of the checked in document
615 String fcontent = Files.readFile(pub
616 .getSourceFile().asFile());
617 found = fcontent.contains(docDTO.getTitle());
620 .debug("Found new document with generated title: "
621 + pub.value().getTitle());
628 Assert.assertTrue(found,
629 "New document is not created for checked in document \""
630 + docDTO.getTitle() + "\".");
632 // Check that uses relations are created correctly
633 Assert.assertTrue(newPub.value().getTitle().startsWith(
634 newPub.value().getType().getName() + "_"),
635 "Document title newPub.value().getTitle() must start with "
636 + newPub.value().getType().getName() + "_");
638 // 1. Find the document type used by this document type
639 Set<DocumentType> usedTypes = newPub.value().getType()
641 // 2. Find documents of used types in the current study step and previous study steps
642 for (Publication pub : aScen.getDocums()) {
643 if ((pub.getStep().getNumber() <= step.getNumber())
644 && (!pub.isOutdated())
645 && usedTypes.contains(pub.value().getType())) {
646 // 3. Check that there is uses relation to the found document
647 // if it is not outdated.
648 checkUsesRelation(newPub, pub);
652 // Check that files are moved correctly
653 checkFiles(docDTO, newPub);
661 "No modification date is checked because no files were attached when attachment with same extension already exists.");
663 // ///////////////////////////////////////////////////////////
664 // Call checkin method for a not existing id.
666 _scenarioService.checkin(-1, userId, stepsToCheckin);
668 .fail("Check in for scenario with not existing id must be failed.");
669 } catch (Exception e) {
670 LOG.debug("Expected exception is thrown: "
671 + e.getClass().getSimpleName() + ": " + e.getMessage());
674 // Test checkin with empty list of steps
675 stepsToCheckin.clear();
676 _scenarioService.checkin(scenarioId, userId, stepsToCheckin);
678 rollbackNestedTransaction();
679 LOG.debug(">>>>> END testCheckin()");
683 * Check if there is uses relation from the newPub to pub.
686 * the new publication
688 * the publication to be used
690 private void checkUsesRelation(final Publication newPub,
691 final Publication pub) {
692 boolean uses = false;
693 boolean usesExist = false;
694 for (Publication usesPub : newPub.getRelations(UsesRelation.class)) {
696 uses = (usesPub.equals(pub));
701 Assert.assertTrue(usesExist && uses, "The created document "
702 + newPub.value().getTitle() + "("
703 + newPub.value().getType().getName() + ")"
704 + " has no uses relation to the document "
705 + pub.value().getTitle() + "("
706 + pub.value().getType().getName() + ")");
710 * Check that files are moved correctly.
713 * checked in document DTO
715 * the created document publication
717 private void checkFiles(final DocumentDTO docDTO, final Publication newPub) {
718 // Check that original files are deleted
719 for (int j = 0; j < docDTO.getFiles().size(); j++) {
720 FileDTO fileDTO = docDTO.getFiles().get(j);
721 Assert.assertFalse(new File(fileDTO.getPath()).exists(), "File"
723 + " was not removed from downloads directory.");
724 String format = fileDTO.getPath().substring(
725 fileDTO.getPath().lastIndexOf('.') + 1);
727 // TODO: Check file by its internal content
728 Assert.assertTrue(newPub.getSourceFile().exists(), "File "
729 + newPub.getSourceFile().asFile().getAbsolutePath()
730 + " for the document " + docDTO.getTitle()
731 + " was not created.");
735 * Prepare a document with a file for check-in.
738 * step DTO with data for check-in
746 * checked out stepDTO
747 * @param stepsToCheckin
749 * @throws IOException
750 * if file creation failed
751 * @return step DTO with data prepared for check-in (stepTo or new if stepTo is null)
753 private StepDTO createDocDTOForModule(final StepDTO stepTo,
754 final String module, final String format, final long userId,
755 final StepDTO stepFrom, final List<StepDTO> stepsToCheckin)
757 StepDTO stepToCheckin = stepTo;
758 if (stepToCheckin == null) {
759 stepToCheckin = new StepDTO();
761 if (module.equals(stepFrom.getModule())) {
762 stepsToCheckin.add(stepToCheckin);
763 stepToCheckin.setNumber(stepFrom.getNumber());
764 for (DocumentDTO doc : stepFrom.getDocs()) {
765 if (doc.getFiles().get(0).getState() != 'O') {
766 DocumentDTO docToCheckin = stepToCheckin.addDoc(
767 doc.getId(), doc.getTitle());
768 for (FileDTO file : doc.getFiles()) {
769 if (file.getPath().endsWith(format)
770 || (file.getPath().endsWith("py") && (format
771 .equals("brep") || format.equals("med")))) {
772 // Create a file in the download directory
773 docToCheckin.addFile(createDownloadedFile(userId,
774 doc.getTitle() + "_result", format));
780 stepToCheckin.addDoc(0, "newdoc" + stepFrom.getNumber()).addFile(
781 createDownloadedFile(userId, "newdoc"
782 + stepFrom.getNumber(), "brep"));
784 return stepToCheckin;
788 * Create a file in the user's repository downloads directory.
796 * @return created file DTO
797 * @throws IOException
798 * if file creation failed
800 private FileDTO createDownloadedFile(final long userId, final String name,
801 final String format) throws IOException {
802 // Create a file in the download directory
803 return createDownloadedFile(userId, name + "." + format);
807 * Create a file in the user's repository downloads directory.
813 * @return created file DTO
814 * @throws IOException
815 * if file creation failed
817 private FileDTO createDownloadedFile(final long userId, final String fname)
819 // Create a file in the download directory
820 String filePath = getDownloadPath(userId) + fname;
821 FileWriter fw = new FileWriter(filePath);
822 fw.write("Simulation of " + fname + " file for checkin at "
825 return new FileDTO(filePath);
833 * @throws IOException
834 * if file creation failed
836 private void createFile(final String fname) throws IOException {
837 // Create a file in the download directory
838 LOG.debug("Create file: " + fname);
839 String filePath = fname;
840 FileWriter fw = new FileWriter(filePath);
841 fw.write("Simulation of " + fname + " data file at " + new Date());
846 * Get path to the user's downloads directory. The directory is created if it is not exist yet.
850 * @return absolute path to downloads directory followed by slash
852 private String getDownloadPath(final long userId) {
853 // Prepare download directory
854 File tmpDir = _repositoryService.getDownloadDirectory(userId);
855 if (!tmpDir.exists()) {
856 Assert.assertTrue(tmpDir.mkdir(),
857 "Can't create temporary directory: "
858 + tmpDir.getAbsolutePath());
861 return tmpDir.getAbsolutePath() + "/";
865 * Create a persistent scenario for tests.
867 * @return a persistent scenario
868 * @throws InvalidPropertyException
869 * if an invalid property is used when creating objects
870 * @throws MultiplyDefinedException
871 * when trying to create an object with already existing id
872 * @throws MissedPropertyException
873 * if a mandatory property is not defined for an object to be created
874 * @throws IOException
875 * if document creation is failed
876 * @throws SQLException
877 * if project settings loading is failed
879 private long createScenario() throws InvalidPropertyException,
880 MissedPropertyException, MultiplyDefinedException, IOException,
882 // Create a scenario for tests
883 HibernateTemplate ht = getHibernateTemplate();
885 Database.getInstance().reset();
886 _projectSettings.getAllSteps().clear(); // Clear config to be able to load it again
887 // Load workflow customization
889 _projectSettings.configure("classpath:test/som.xml");
890 } catch (FileNotFoundException e) {
891 Assert.fail("Can't find som.xml: ", e);
893 List<Step> steps = _stepsConfigService.getStepsOf(Scenario.class);
894 Assert.assertTrue(steps.size() > 0, "No steps are created.");
896 // Create a test user
897 User.Properties uprop = new User.Properties();
898 uprop.setUsername("TST_Username").setName("TST_SimanUnitTestsUser")
899 .setFirstName("TST_FirstName").setDisplayName("TST_test.user")
900 .addRole("TST_user").setMailAddress(
901 "noreply@salome-platform.org");
902 uprop.disableCheck();
903 User anAuthor = new User(uprop);
904 ht.saveOrUpdate(anAuthor);
906 // Create a test study
907 Study.Properties stprops = new Study.Properties().setReference(
908 "TST_SID_01").setTitle("TST_Study").setManager(anAuthor);
909 Study aStudy = new Study(stprops);
910 ht.saveOrUpdate(aStudy);
912 // Create a test scenario
913 Scenario.Properties sprops = new Scenario.Properties().setTitle(
914 "TST_Scenario").setManager(anAuthor).setOwnerStudy(aStudy);
915 Scenario aScenario = new Scenario(sprops);
916 aStudy.getScenariiList().add(aScenario);
917 ht.saveOrUpdate(anAuthor);
918 ht.saveOrUpdate(aStudy);
919 ht.saveOrUpdate(aScenario);
921 // Create documents for each scenario step
922 Document.Properties dprop = new Document.Properties().setAuthor(
923 anAuthor).setDate(new Date());
925 Publication usedPub = null;
926 Map<Long, Long> usedMap = new HashMap<Long, Long>();
927 for (Step step : steps) {
928 LOG.debug("Create scenario step: " + i);
930 org.splat.som.Step aScStep = new org.splat.som.Step(step, aScenario);
931 List<DocumentType> dtypes = _documentTypeService
932 .selectTypesOf(step);
933 for (DocumentType dtype : dtypes) {
934 // Create a document published in the scenario
935 // document<i>: document type[0] - first type used on the step
936 // <source-file>.brep
937 // <attached-file>.med
938 dprop.setName("document" + i++).setType(dtype);
940 * if (step.getNumber() > 3) { dprop.setFormat("med"); } else {
941 */dprop.setFormat("py");
943 dprop.setLocalPath(dprop.getName() + "." + dprop.getFormat());
944 Publication pub = createDoc(aScenario, aScStep, dprop, "med",
946 if (usedPub != null) {
947 pub.addDependency(usedPub);
948 ht.saveOrUpdate(pub.value());
950 usedMap.put(pub.getIndex(), usedPub.getIndex());
954 // Create another document with outdated publication
955 dprop.setName("document" + i++).setType(dtype).setFormat("py");
956 dprop.setLocalPath(dprop.getName() + "." + dprop.getFormat());
957 createDoc(aScenario, aScStep, dprop, "med", true);
960 if (dtypes.size() <= 0) {
961 LOG.debug("No document types are found for scenario step " + i);
965 // Check that the scenario and its documents have been created correctly.
967 Assert.assertNotNull(ht.find("from Document"),
968 "No documents in the database.");
969 Assert.assertTrue(ht.find("from Document").size() > 0,
970 "No documents in the database.");
972 Assert.assertNotNull(ht.find("from Publication where owner="
973 + aScenario.getIndex()), "No publications in the database.");
975 ht.find("from Publication where owner=" + aScenario.getIndex())
976 .size() > 0, "No publications in the database.");
978 for (Publication p : (List<Publication>) ht
979 .find("from Publication where owner=" + aScenario.getIndex())) {
980 LOG.debug("Publication found: [id=" + p.getIndex() + ", owner="
981 + p.getOwner().getIndex() + ", doc=" + p.value().getIndex()
983 Assert.assertEquals(p.getOwner().getIndex(), aScenario.getIndex(),
984 "The publication was not attached to the scenario.");
987 // Remove the scenario from the current hibernate session.
989 // Check that the scenario is created in the database.
990 Scenario aScen = ht.load(Scenario.class, aScenario.getIndex());
991 Assert.assertNotNull(aScen, "Scenario was not saved in the database.");
992 Assert.assertTrue(aScen.getDocums().size() > 0,
993 "No publications in the scenario.");
995 Assert.assertTrue(i > 0,
996 "More then one document must be in the database");
998 // Check created uses relations
1000 .assertTrue(usedMap.size() > 0,
1001 "Uses relations must be created.");
1002 boolean foundAny = false;
1003 for (Long usingId : usedMap.keySet()) {
1004 for (Publication pub : aScen.getDocums()) {
1005 if (pub.getIndex() == usingId) {
1006 boolean found = false;
1007 for (Publication used : aScen.getDocums()) {
1008 found = (used.getIndex() == usedMap.get(usingId));
1013 Assert.assertTrue(found,
1014 "Uses relation was not created in the database.");
1015 foundAny = foundAny || found;
1019 Assert.assertTrue(foundAny,
1020 "No Uses relation was created in the database.");
1022 return aScenario.getIndex();
1026 * Create a document published in the scenario. <BR>
1028 * document type[0] - first type used on the step <BR>
1029 * <source-file>.brep <BR>
1030 * <attached-file>.med
1033 * the scenario to add the document to
1035 * scenario step where the document to be published
1037 * document properties
1038 * @param attachedFileExt
1039 * extension of the secon attached (exported) file
1041 * outdated document flag
1042 * @return the publication of the created document
1043 * @throws IOException
1044 * @throws MultiplyDefinedException
1045 * @throws InvalidPropertyException
1046 * @throws MissedPropertyException
1048 private Publication createDoc(final Scenario aScenario,
1049 final org.splat.som.Step aScStep, final Properties dprop,
1050 final String attachedFileExt, final boolean isOutdated)
1051 throws MissedPropertyException, InvalidPropertyException,
1052 MultiplyDefinedException, IOException {
1053 // Create a document published in the scenario
1054 // document<i>: document type[0] - first type used on the step
1055 // <source-file>.brep
1056 // <attached-file>.med
1057 createDownloadedFile(aScenario.getAuthor().getIndex(), dprop
1059 Publication pub = _stepService.createDocument(aScStep, dprop);
1060 Assert.assertNotNull(pub.getOwner(),
1061 "The publication must be attached to the scenario.");
1062 Assert.assertEquals(pub.getOwner().getIndex(), aScenario.getIndex(),
1063 "The publication was not attached to the scenario.");
1069 HibernateTemplate ht = getHibernateTemplate();
1070 ht.saveOrUpdate(pub);
1073 createDownloadedFile(aScenario.getAuthor().getIndex(), dprop
1074 .getLocalPath().substring(0,
1075 dprop.getLocalPath().lastIndexOf(".") - 1),
1077 ht.save(pub.value());
1078 ht.saveOrUpdate(_publicationService.attach(pub, attachedFileExt));
1084 * Test study creation.<BR>
1085 * <B>Description :</B> <BR>
1086 * <i>Create a study.</i><BR>
1087 * <B>Action : </B><BR>
1088 * <i>1. call the method for a not existing product.</i><BR>
1089 * <i>2. call the method for an existing username and an existing product.</i><BR>
1090 * <i>3. call the method for a not existing username expecting an exception.</i><BR>
1091 * <B>Test data : </B><BR>
1092 * <i>no input parameters</i><BR>
1094 * <B>Outcome results:</B><BR>
1097 * <li>1: The new study must be created. The new product simulation context must be created.</li>
1098 * <li>2: The new study must be created.</li>
1099 * <li>3: The new study must not be created. Exception must be thrown.</li>
1103 * @throws IOException
1104 * if application configuration loading is failed
1105 * @throws SQLException
1106 * if application configuration loading is failed
1107 * @throws BusinessException
1108 * if test data creation is failed
1110 @Test(groups = { "study", "sevice", "functional", "business" })
1111 public void testCreateStudy() throws BusinessException, IOException,
1113 LOG.debug(">>>>> BEGIN testCreateStudy()");
1114 startNestedTransaction();
1116 Database.getInstance().reset();
1117 _projectSettings.getAllSteps().clear(); // Clear config to be able to load it again
1118 _projectSettings.configure("classpath:test/som.xml");
1120 // Create a test user
1121 User.Properties uprop = new User.Properties();
1122 uprop.setUsername("TST_Username").setName("TST_SimanUnitTestsUser")
1123 .setFirstName("TST_FirstName").setDisplayName("TST_test.user")
1124 .addRole("TST_user").setMailAddress(
1125 "noreply@salome-platform.org");
1126 uprop.disableCheck();
1127 User anAuthor = new User(uprop);
1129 getHibernateTemplate().saveOrUpdate(anAuthor);
1130 KnowledgeElementType ucase = _knowledgeElementTypeService
1131 .selectType("usecase");
1132 Assert.assertNotNull(ucase,
1133 "Knowledge type 'usecase' must be created in the database.");
1134 SimulationContextType prodtype = _simulationContextService
1135 .selectType("product");
1137 .assertNotNull(prodtype,
1138 "Simulation context type 'product' must be created in the database.");
1142 uprop.setUsername("TST_Admin").setName("TST_SimanUnitTestsAdmin")
1143 .setFirstName("TST_AdminFirstName").setDisplayName(
1144 "TST_test.admin").addRole("TST_user,sysadmin")
1145 .setMailAddress("noreply@salome-platform.org");
1146 uprop.disableCheck();
1148 getHibernateTemplate().saveOrUpdate(new User(uprop));
1149 getHibernateTemplate().flush();
1151 Study.Properties sprop = new Study.Properties();
1152 sprop.setTitle("Test study creation").setManager(anAuthor);
1153 Scenario.Properties oprop = new Scenario.Properties();
1154 oprop.setTitle("Test scenario for the created study");
1156 // Addition of the entered project context
1157 SimulationContext.Properties cprop = new SimulationContext.Properties();
1158 // Input of new project context
1159 cprop.setType(_simulationContextService.selectType("product"))
1160 .setValue("Test Simulation Context: Product");
1161 Study study = _scenarioService.createStudy(sprop, oprop, cprop);
1163 Assert.assertNotNull(study);
1164 Assert.assertTrue(study.getIndex() > 0);
1166 rollbackNestedTransaction();
1167 LOG.debug(">>>>> END testCreateStudy()");
1171 * Test study creation.<BR>
1172 * <B>Description :</B> <BR>
1173 * <i>Create a study.</i><BR>
1174 * <B>Action : </B><BR>
1175 * <i>1. call the method for a not existing product.</i><BR>
1176 * <i>2. call the method for an existing username and an existing product.</i><BR>
1177 * <i>3. call the method for a not existing username expecting an exception.</i><BR>
1178 * <B>Test data : </B><BR>
1179 * <i>no input parameters</i><BR>
1181 * <B>Outcome results:</B><BR>
1184 * <li>1: The new study must be created. The new product simulation context must be created.</li>
1185 * <li>2: The new study must be created.</li>
1186 * <li>3: The new study must not be created. Exception must be thrown.</li>
1190 * @throws IOException
1191 * if application configuration loading is failed
1192 * @throws SQLException
1193 * if application configuration loading is failed
1194 * @throws BusinessException
1195 * if test data creation is failed
1197 @Test(groups = { "study", "sevice", "functional", "business" })
1198 public void testCreateStudyFromPython() throws IOException, SQLException,
1200 LOG.debug(">>>>> BEGIN testCreateStudyFromPython()");
1201 startNestedTransaction();
1203 HibernateTemplate ht = getHibernateTemplate();
1205 Database.getInstance().reset();
1206 _projectSettings.getAllSteps().clear(); // Clear config to be able to load it again
1207 _projectSettings.configure("classpath:test/som.xml");
1209 // Create a test user
1210 User goodUser = TestEntitiesGenerator.getTestUser("goodUser");
1211 _userDAO.create(goodUser);
1212 SimulationContextType prodtype = _simulationContextService
1213 .selectType("product");
1215 .assertNotNull(prodtype,
1216 "Simulation context type 'product' must be created in the database.");
1218 String productName = "New Test Product " + new Date().toString();
1222 long studyId1 = _scenarioService.createStudy("goodUser",
1223 "Test Study 1", productName, "Test description");
1224 Assert.assertTrue(studyId1 > 0);
1229 _scenarioService.createStudy("badbadUser", "Test Study 2",
1230 productName, "Test description");
1231 Assert.fail("Study must not be created for not existing user.");
1232 } catch (InvalidPropertyException ipe) {
1233 LOG.debug("Expected exception: " + ipe.getMessage());
1238 long studyId3 = _scenarioService.createStudy("goodUser",
1239 "Test Study 3", productName, "Test description");
1240 Assert.assertTrue(studyId3 > 0);
1242 // Check that the simulation context is the same
1243 Study study1 = _studyService.selectStudy(studyId1);
1244 Study study3 = _studyService.selectStudy(studyId3);
1245 Assert.assertEquals(study1.SimulationContextIterator().next(), study3
1246 .SimulationContextIterator().next());
1248 // Check the title of the created scenario
1249 String scTitle = study1.getScenarii()[0].getTitle();
1250 Assert.assertEquals(scTitle, I18nUtils
1251 .getMessageLocaleDefault("label.scenario")
1253 Assert.assertFalse(scTitle.equals("label.scenario 1"));
1255 rollbackNestedTransaction();
1256 LOG.debug(">>>>> END testCreateStudyFromPython()");
1260 * Test study content copy.<BR>
1261 * <B>Description :</B> <BR>
1262 * <i>Create a study.</i><BR>
1263 * <B>Action : </B><BR>
1264 * <i>1. call the method for a not existing source study.</i><BR>
1265 * <i>2. call the method for a not existing source scenario with not evolving step.</i><BR>
1266 * <i>3. call the method for a not existing source scenario with evolving step.</i><BR>
1267 * <i>4. call the method for an existing source scenario with evolving step.</i><BR>
1268 * <B>Test data : </B><BR>
1269 * <i>no input parameters</i><BR>
1271 * <B>Outcome results:</B><BR>
1274 * <li>1: Exception must be thrown.</li>
1275 * <li>2: The study content must be copied.</li>
1276 * <li>3: Exception must be thrown.</li>
1277 * <li>4: The study content must be copied.</li>
1281 * @throws IOException
1282 * if application configuration loading is failed
1283 * @throws SQLException
1284 * if application configuration loading is failed
1285 * @throws BusinessException
1286 * if test data creation is failed
1288 @Test(groups = { "study", "sevice", "functional", "business" })
1289 public void testCopyStudyContent() throws IOException, SQLException,
1291 LOG.debug(">>>>> BEGIN testCopyStudyContent()");
1292 startNestedTransaction();
1294 HibernateTemplate ht = getHibernateTemplate();
1296 Database.getInstance().reset();
1297 _projectSettings.getAllSteps().clear(); // Clear config to be able to load it again
1298 _projectSettings.configure("classpath:test/som.xml");
1300 User goodUser = TestEntitiesGenerator.getTestUser("GoodUser");
1301 _userDAO.create(goodUser);
1302 User otherUser = TestEntitiesGenerator.getTestUser("otherUser");
1303 _userDAO.create(otherUser);
1305 // Create private study
1306 Study aStudy = TestEntitiesGenerator.getTestStudy(goodUser);
1307 aStudy.setTitle("0.This is private study");
1308 Long studyId = _studyDAO.create(aStudy);
1310 // Add a scenario to the study
1311 Scenario scen = TestEntitiesGenerator.getTestScenario(aStudy);
1312 _scenarioDAO.create(scen);
1314 // Add a second scenario to the study
1315 scen = TestEntitiesGenerator.getTestScenario(aStudy);
1316 Long aScenId = _scenarioDAO.create(scen);
1319 // Add a validation cycle with otherUser as a reviewer
1320 ValidationCycle.Properties vprop = new ValidationCycle.Properties();
1321 DocumentType dtype = _documentTypeService.selectType("minutes");
1322 vprop.setDocumentType(dtype);
1323 vprop.setActor(ValidationStep.REVIEW, otherUser);
1324 ValidationCycle cycle = new ValidationCycle(aStudy, vprop);
1325 _validationCycleDAO.create(cycle);
1326 ValidationCycleRelation link = cycle.getContext();
1327 aStudy.addRelation(link);
1330 // Add documents to the first study activity
1331 // Add a converts relations
1332 Map<Integer, org.splat.som.Step> stSteps = _projectElementService
1333 .getStepsMap(aStudy);
1334 org.splat.som.Step aStep = stSteps.get(1);
1335 Publication pub1 = addDoc(aStudy, aStep, "document1", dtype);
1336 Publication pub2 = addDoc(aStudy, aStep, "document2", dtype);
1337 Publication pub3 = addDoc(aStudy, aStep, "document3", dtype);
1340 LOG.debug("pub1 version doc: " + pub1.value().getTitle() + " ["
1341 + pub1.value().getReference() + "]" + " ["
1342 + pub1.value().getRid() + "]");
1343 LOG.debug("pub2 version doc: " + pub2.value().getTitle() + " ["
1344 + pub2.value().getReference() + "]" + " ["
1345 + pub2.value().getRid() + "]");
1346 LOG.debug("pub3 version doc: " + pub3.value().getTitle() + " ["
1347 + pub3.value().getReference() + "]" + " ["
1348 + pub3.value().getRid() + "]");
1353 LOG.debug("Before versioning:");
1354 for (Publication doc : _projectElementService.getFirstStep(aStudy)
1355 .getAllDocuments()) {
1356 LOG.debug("Study doc: " + doc.value().getTitle() + " ["
1357 + doc.value().getReference() + "]" + " ["
1358 + doc.value().getRid() + "]");
1360 // Add a version relations
1361 Publication pub31 = version(pub3);
1364 // LOG.debug("pub31 version doc: " + pub31.value().getTitle() + " ["
1365 // + pub31.value().getReference() + "]" + " ["
1366 // + pub31.value().getRid() + "]");
1367 // ht.saveOrUpdate(aStudy);
1369 // LOG.debug("After versioning:");
1370 // for (Publication doc : aStudy.getDocums()) {
1371 // LOG.debug("Study doc: " + doc.value().getTitle() + " ["
1372 // + doc.value().getReference() + "]" + " ["
1373 // + doc.value().getRid() + "]");
1376 // Add documents to the first scenario activity
1377 Map<Integer, org.splat.som.Step> scSteps = _projectElementService
1379 aStep = scSteps.get(2);
1380 Publication spub1 = addDoc(scen, aStep, "sdocument1", dtype);
1381 Publication spub2 = addDoc(scen, aStep, "sdocument2", dtype);
1382 Publication spub3 = addDoc(scen, aStep, "sdocument3", dtype);
1383 LOG.debug("spub1 version doc: " + spub1.value().getTitle() + " ["
1384 + spub1.value().getReference() + "]" + " ["
1385 + spub1.value().getRid() + "]");
1386 LOG.debug("spub2 version doc: " + spub2.value().getTitle() + " ["
1387 + spub2.value().getReference() + "]" + " ["
1388 + spub2.value().getRid() + "]");
1389 LOG.debug("spub3 version doc: " + spub3.value().getTitle() + " ["
1390 + spub3.value().getReference() + "]" + " ["
1391 + spub3.value().getRid() + "]");
1394 // Create a scenario document version
1395 Publication spub31 = version(spub3);
1396 // LOG.debug("spub31 version doc: " + spub31.value().getTitle() + " ["
1397 // + spub31.value().getReference() + "]" + " ["
1398 // + spub31.value().getRid() + "]");
1401 // Add uses relations
1402 pub2.addDependency(pub1);
1403 ht.saveOrUpdate(pub2.value());
1404 pub3.addDependency(pub2);
1405 ht.saveOrUpdate(pub3.value());
1407 spub2.addDependency(pub1);
1408 spub2.addDependency(spub1);
1409 spub2.addDependency(pub2);
1410 spub2.addDependency(pub3);
1411 ht.saveOrUpdate(spub2.value());
1412 spub3.addDependency(spub2);
1413 ht.saveOrUpdate(spub3.value());
1414 spub31.addDependency(pub31);
1415 ht.saveOrUpdate(spub31.value());
1418 // Create target study1
1419 Study aStudy1 = TestEntitiesGenerator.getTestStudy(goodUser);
1420 aStudy1.setTitle("1.This is a target study1");
1421 aStudy1.setReference("tst1");
1422 Long studyId1 = _studyDAO.create(aStudy1);
1424 // Add a scenario to the study
1425 Scenario scen1 = TestEntitiesGenerator.getTestScenario(aStudy1);
1426 _scenarioDAO.create(scen1);
1429 // Create target study2
1430 Study aStudy2 = TestEntitiesGenerator.getTestStudy(goodUser);
1431 aStudy2.setTitle("2.This is a target study2");
1432 aStudy2.setReference("tst2");
1433 Long studyId2 = _studyDAO.create(aStudy2);
1435 // Add a scenario to the study
1436 Scenario scen2 = TestEntitiesGenerator.getTestScenario(aStudy2);
1437 _scenarioDAO.create(scen2);
1441 // //////////////////// TEST CALL /////////////////////////////////////
1442 // 1. call the method for a not existing source study.
1444 _scenarioService.copyStudyContent(-1, -1, -1, -1);
1445 Assert.fail("Exception must be thrown for not existing study id.");
1446 } catch (InvalidParameterException e) {
1447 LOG.debug("Expected exception: " + e.getClass().getSimpleName()
1448 + ": " + e.getMessage());
1454 // 2. call the method for a not existing source scenario with not evolving step.
1455 _scenarioService.copyStudyContent(studyId, -1, 1, studyId1);
1460 aStudy = _studyService.selectStudy(studyId);
1461 aStudy1 = _studyService.selectStudy(studyId1);
1462 for (Publication pub : aStudy.getDocums()) {
1463 // Find the same document in the created copy of the study
1464 Publication found = null;
1465 for (Publication newPub : aStudy1.getDocums()) {
1466 if (pub.value().getTitle().equals(newPub.value().getTitle())
1467 && pub.value().getType().equals(
1468 newPub.value().getType())) {
1473 Assert.assertNotNull(found, "The document "
1474 + pub.value().getTitle() + "is not copied");
1475 // Check that all files are copied (source and attached)
1478 // 3. call the method for a not existing source scenario with evolving step.
1480 _scenarioService.copyStudyContent(studyId, -1, 2, studyId2);
1482 .fail("Exception must be thrown for not existing scenario id and evolving step.");
1483 } catch (InvalidParameterException e) {
1484 LOG.debug("Expected exception: " + e.getClass().getSimpleName()
1485 + ": " + e.getMessage());
1491 // 4. call the method for an existing source scenario with evolving step.
1492 _scenarioService.copyStudyContent(studyId, aScenId, 9, studyId2);
1495 rollbackNestedTransaction();
1496 LOG.debug(">>>>> END testCopyStudyContent()");
1500 * Create a document and publish it in the project element.
1503 * the project element
1505 * the project element step
1510 * @return publication of the created document
1511 * @throws BusinessException
1512 * if document creation is failed
1513 * @throws IOException
1514 * if file creation is failed
1516 private Publication addDoc(final ProjectElement aProjElem,
1517 final org.splat.som.Step aStep, final String docname,
1518 final DocumentType dtype) throws BusinessException, IOException {
1519 HibernateTemplate ht = getHibernateTemplate();
1520 // Add documents to the study activity
1521 Document.Properties dprop = new Document.Properties().setAuthor(
1522 aProjElem.getAuthor()).setDate(new Date()).setName(docname)
1523 .setType(dtype).setFormat("py");
1524 dprop.setLocalPath(dprop.getName() + "." + dprop.getFormat());
1525 dprop.setStep(aStep.getStep());
1526 Publication pub = _stepService.createDocument(aStep, dprop);
1529 aStep.getDocuments().add(pub);
1530 ht.saveOrUpdate(pub);
1531 ht.save(pub.value());
1532 // Add a converts relation
1533 // Attach a med file
1534 ht.saveOrUpdate(_publicationService.attach(pub, "med"));
1535 String filepath = pub.getSourceFile().asFile().getAbsolutePath();
1536 createFile(filepath);
1537 createFile(filepath.substring(0, filepath.lastIndexOf(".")) + ".med");
1542 * Create a new version of the document.
1545 * the current document publication
1546 * @return the new document version publication
1547 * @throws IOException
1548 * if versioning is failed
1549 * @throws BusinessException
1550 * if versioning is failed
1552 private Publication version(final Publication pub)
1553 throws BusinessException, IOException {
1554 Document.Properties dprop = new Document.Properties();
1555 dprop.setDocument(pub.value(), pub.getStep().getStep());
1556 dprop.setLocalPath(pub.value().getTitle() + "_v1");
1557 Publication newpub = _stepService.versionDocument(pub.getStep(), pub,
1559 pub.getOwner().getDocums().remove(pub);
1560 pub.getStep().getDocuments().remove(pub);
1561 pub.getOwner().add(newpub);
1562 pub.getStep().getDocuments().add(newpub);
1563 String filepath = newpub.getSourceFile().asFile().getAbsolutePath();
1564 createFile(filepath);
1569 * Test assigning a simulation context to a study.<BR>
1570 * <B>Description :</B> <BR>
1571 * <i>Create a study and assign a simulation context to it.</i><BR>
1572 * <B>Action : </B><BR>
1573 * <i>1. call the method for not existing study id.</i><BR>
1574 * <i>2. call the method for not existing context type and context value.</i><BR>
1575 * <i>3. call the method for existing context type and context value.</i><BR>
1576 * <i>4. call the method for existing context type and not existing context value.</i><BR>
1577 * <i>5. call the method for empty context type.</i><BR>
1578 * <i>6. call the method for empty context value.</i><BR>
1579 * <B>Test data : </B><BR>
1580 * <i>no input parameters</i><BR>
1582 * <B>Outcome results:</B><BR>
1585 * <li>1: Exception must be thrown.</li>
1586 * <li>2: The new context type and value must be created. The new context must be assigned to the study first step.</li>
1587 * <li>3: The existing context must be assigned to the study first step.</li>
1588 * <li>4: The new context value must be created. The new context must be assigned to the study first step.</li>
1589 * <li>5: Exception must be thrown.</li>
1590 * <li>6: Exception must be thrown.</li>
1594 * @throws IOException
1595 * if application configuration loading is failed
1596 * @throws SQLException
1597 * if application configuration loading is failed
1598 * @throws BusinessException
1599 * if test data creation is failed
1601 @Test(groups = { "study", "sevice", "functional", "business" })
1602 public void testAssignStudyContextFromPython() throws IOException,
1603 SQLException, BusinessException {
1604 LOG.debug(">>>>> BEGIN testAssignStudyContextFromPython()");
1605 startNestedTransaction();
1607 HibernateTemplate ht = getHibernateTemplate();
1609 Database.getInstance().reset();
1610 _projectSettings.getAllSteps().clear(); // Clear config to be able to load it again
1611 _projectSettings.configure("classpath:test/som.xml");
1613 // Create a test user
1614 User goodUser = TestEntitiesGenerator.getTestUser("goodUser");
1615 _userDAO.create(goodUser);
1616 SimulationContextType prodtype = _simulationContextService
1617 .selectType("product");
1619 .assertNotNull(prodtype,
1620 "Simulation context type 'product' must be created in the database.");
1622 String productName = "New Test Product " + new Date().toString();
1626 long studyId1 = _scenarioService.createStudy("goodUser",
1627 "Test Study 1", productName, "Test description");
1628 Assert.assertTrue(studyId1 > 0);
1633 // //////// START OF TESTS
1634 // 1. call the method for not existing study id.</i><BR>
1636 _scenarioService.assignStudyContext(-1L, "new context type",
1637 "new context value");
1638 Assert.fail("Not existing study must not be found.");
1639 } catch (InvalidPropertyException ipe) {
1640 LOG.debug("Expected exception: " + ipe.getMessage());
1643 // 2. call the method for not existing context type and context value.</i><BR>
1644 _scenarioService.assignStudyContext(studyId1, "new context type",
1645 "new context value");
1650 // Check the assigned simulation context
1651 checkCtx(studyId1, "new context type", "new context value");
1653 // 3. call the method for existing context type and context value.</i><BR>
1654 _scenarioService.assignStudyContext(studyId1, "new context type",
1655 "new context value");
1660 // Check the assigned simulation context
1661 checkCtx(studyId1, "new context type", "new context value");
1663 // 4. call the method for existing context type and not existing context value.</i><BR>
1664 _scenarioService.assignStudyContext(studyId1, "new context type",
1665 "new context value1");
1670 // Check the assigned simulation context
1671 checkCtx(studyId1, "new context type", "new context value1");
1673 // 5. call the method for empty context type.</i><BR>
1675 _scenarioService.assignStudyContext(studyId1, "",
1676 "new context value");
1677 Assert.fail("Empty context type name must be forbidden.");
1678 } catch (InvalidPropertyException ipe) {
1679 LOG.debug("Expected exception: " + ipe.getMessage());
1681 // 6. call the method for empty context value.</i><BR>
1683 _scenarioService.assignStudyContext(studyId1, "new context type",
1685 Assert.fail("Empty context value must be forbidden.");
1686 } catch (InvalidPropertyException ipe) {
1687 LOG.debug("Expected exception: " + ipe.getMessage());
1690 rollbackNestedTransaction();
1691 LOG.debug(">>>>> END testAssignStudyContextFromPython()");
1695 * Test getting a study scenarios DTO list.<BR>
1696 * <B>Description :</B> <BR>
1697 * <i>Create a study and get its scenarios DTO list.</i><BR>
1698 * <B>Action : </B><BR>
1699 * <i>1. call the method for not existing study id.</i><BR>
1700 * <i>2. call the method for a study with one scenario.</i><BR>
1701 * <i>3. call the method for a study with several scenarios.</i><BR>
1702 * <B>Test data : </B><BR>
1703 * <i>no input parameters</i><BR>
1705 * <B>Outcome results:</B><BR>
1708 * <li>1: The returned list of DTO must be empty.</li>
1709 * <li>2: The returned list of DTO must contain one scenario DTO.</li>
1710 * <li>3: The returned list of DTO must contain several scenario DTOs.</li>
1714 * @throws IOException
1715 * if application configuration loading is failed
1716 * @throws SQLException
1717 * if application configuration loading is failed
1718 * @throws BusinessException
1719 * if test data creation is failed
1721 @Test(groups = { "study", "sevice", "functional", "business" })
1722 public void testGetStudyScenarios() throws IOException, SQLException,
1724 LOG.debug(">>>>> BEGIN testGetStudyScenarios()");
1725 startNestedTransaction();
1727 HibernateTemplate ht = getHibernateTemplate();
1729 Database.getInstance().reset();
1730 _projectSettings.getAllSteps().clear(); // Clear config to be able to load it again
1731 _projectSettings.configure("classpath:test/som.xml");
1733 // Create a test user
1734 User goodUser = TestEntitiesGenerator.getTestUser("goodUser");
1735 _userDAO.create(goodUser);
1736 Study study = TestEntitiesGenerator.getTestStudy(goodUser);
1737 long studyId1 = _studyDAO.create(study);
1739 Scenario scen = TestEntitiesGenerator.getTestScenario(study,
1741 long id11 = _scenarioDAO.create(scen);
1743 study = TestEntitiesGenerator.getTestStudy(goodUser);
1744 long studyId2 = _studyDAO.create(study);
1746 scen = TestEntitiesGenerator.getTestScenario(study, "test scen21");
1747 long id21 = _scenarioDAO.create(scen);
1749 scen = TestEntitiesGenerator.getTestScenario(study, "test scen22");
1750 long id22 = _scenarioDAO.create(scen);
1752 scen = TestEntitiesGenerator.getTestScenario(study, "test scen23");
1753 long id23 = _scenarioDAO.create(scen);
1757 // //////// START OF TESTS
1758 // 1. call the method for not existing study id.
1759 List<ScenarioDTO> scens = _scenarioService.getStudyScenarios(-1L);
1761 Assert.assertNotNull(scens);
1762 Assert.assertTrue(scens.isEmpty());
1764 // 2. call the method for a study with one scenario.
1765 scens = _scenarioService.getStudyScenarios(studyId1);
1769 Assert.assertNotNull(scens);
1770 Assert.assertEquals(scens.size(), 1);
1771 Assert.assertEquals(scens.get(0).getIndex().longValue(), id11);
1772 Assert.assertEquals(scens.get(0).getTitle(), "test scen11");
1774 // 3. call the method for a study with several scenarios.
1775 scens = _scenarioService.getStudyScenarios(studyId2);
1776 Assert.assertEquals(scens.size(), 3);
1777 Assert.assertEquals(scens.get(0).getIndex().longValue(), id21);
1778 Assert.assertEquals(scens.get(0).getTitle(), "test scen21");
1779 Assert.assertEquals(scens.get(1).getIndex().longValue(), id22);
1780 Assert.assertEquals(scens.get(1).getTitle(), "test scen22");
1781 Assert.assertEquals(scens.get(2).getIndex().longValue(), id23);
1782 Assert.assertEquals(scens.get(2).getTitle(), "test scen23");
1787 rollbackNestedTransaction();
1788 LOG.debug(">>>>> END testGetStudyScenarios()");
1792 * Check if the context is assigned to the study.
1797 * the context type name
1801 private void checkCtx(final long studyId1, final String ctxType,
1802 final String ctxValue) {
1803 // Check the assigned simulation context
1804 Study study1 = _studyService.selectStudy(studyId1);
1805 Iterator<SimulationContext> it = study1.SimulationContextIterator();
1806 SimulationContext ctx;
1807 boolean isFound = false;
1808 while ((!isFound) && it.hasNext()) {
1810 isFound = ctx.getType().getName().equals(ctxType)
1811 && ctx.getValue().equals(ctxValue);
1813 Assert.assertTrue(isFound, "Context must be assigned to the study.");