]> SALOME platform Git repositories - tools/siman.git/blob - Workspace/Siman-Common/src/test/splat/service/TestScenarioService.java
Salome HOME
Fixed case when translation is not found. Now default translation parameter is used...
[tools/siman.git] / Workspace / Siman-Common / src / test / splat / service / TestScenarioService.java
1 /*****************************************************************************
2  * Company         OPEN CASCADE
3  * Application     SIMAN
4  * File            $Id$ 
5  * Creation date   12 Oct 2012
6  * @author         $Author$
7  * @version        $Revision$
8  *****************************************************************************/
9 package test.splat.service;
10
11 import java.io.File;
12 import java.io.FileNotFoundException;
13 import java.io.FileWriter;
14 import java.io.IOException;
15 import java.sql.SQLException;
16 import java.util.ArrayList;
17 import java.util.Date;
18 import java.util.HashMap;
19 import java.util.List;
20 import java.util.Map;
21 import java.util.Set;
22
23 import org.splat.dal.bo.kernel.Relation;
24 import org.splat.dal.bo.kernel.User;
25 import org.splat.dal.bo.som.Document;
26 import org.splat.dal.bo.som.DocumentType;
27 import org.splat.dal.bo.som.KnowledgeElementType;
28 import org.splat.dal.bo.som.Publication;
29 import org.splat.dal.bo.som.Scenario;
30 import org.splat.dal.bo.som.SimulationContext;
31 import org.splat.dal.bo.som.SimulationContextType;
32 import org.splat.dal.bo.som.Study;
33 import org.splat.dal.bo.som.UsedByRelation;
34 import org.splat.dal.bo.som.UsesRelation;
35 import org.splat.dal.bo.som.Document.Properties;
36 import org.splat.dal.dao.som.Database;
37 import org.splat.dal.dao.som.ScenarioDAO;
38 import org.splat.kernel.InvalidPropertyException;
39 import org.splat.kernel.MismatchException;
40 import org.splat.kernel.MissedPropertyException;
41 import org.splat.kernel.MultiplyDefinedException;
42 import org.splat.kernel.NotApplicableException;
43 import org.splat.log.AppLogger;
44 import org.splat.service.DocumentTypeService;
45 import org.splat.service.KnowledgeElementTypeService;
46 import org.splat.service.PublicationService;
47 import org.splat.service.ScenarioService;
48 import org.splat.service.SimulationContextService;
49 import org.splat.service.StepService;
50 import org.splat.service.dto.DocumentDTO;
51 import org.splat.service.dto.FileDTO;
52 import org.splat.service.dto.StepDTO;
53 import org.splat.service.technical.ProjectSettingsService;
54 import org.splat.service.technical.RepositoryService;
55 import org.splat.service.technical.ProjectSettingsService.Step;
56 import org.springframework.beans.factory.annotation.Autowired;
57 import org.springframework.beans.factory.annotation.Qualifier;
58 import org.springframework.orm.hibernate3.HibernateTemplate;
59 import org.testng.Assert;
60 import org.testng.annotations.Test;
61 import org.testng.reporters.Files;
62
63 import test.splat.common.BaseTest;
64
65 /**
66  * Test class for ScenarioService.
67  * 
68  * @author <a href="mailto:roman.kozlov@opencascade.com">Roman Kozlov (RKV)</a>
69  * 
70  */
71 public class TestScenarioService extends BaseTest {
72
73         /**
74          * Logger for the class.
75          */
76         private static final AppLogger LOG = AppLogger
77                         .getLogger(TestScenarioService.class);
78
79         /**
80          * The tested ScenarioService. Later injected by Spring.
81          */
82         @Autowired
83         @Qualifier("scenarioService")
84         private transient ScenarioService _scenarioService;
85
86         /**
87          * The RepositoryService. Later injected by Spring.
88          */
89         @Autowired
90         @Qualifier("repositoryService")
91         private transient RepositoryService _repositoryService;
92
93         /**
94          * The Scenario DAO. Later injected by Spring.
95          */
96         @Autowired
97         @Qualifier("scenarioDAO")
98         private transient ScenarioDAO _scenarioDAO;
99
100         /**
101          * The PublicationService. Later injected by Spring.
102          */
103         @Autowired
104         @Qualifier("publicationService")
105         private transient PublicationService _publicationService;
106
107         /**
108          * The StepService. Later injected by Spring.
109          */
110         @Autowired
111         @Qualifier("stepService")
112         private transient StepService _stepService;
113
114         /**
115          * The SimulationContextService. Later injected by Spring.
116          */
117         @Autowired
118         @Qualifier("simulationContextService")
119         private transient SimulationContextService _simulationContextService;
120
121         /**
122          * The ProjectSettingsService. Later injected by Spring.
123          */
124         @Autowired
125         @Qualifier("projectSettings")
126         private transient ProjectSettingsService _projectSettings;
127
128         /**
129          * The DocumentTypeService. Later injected by Spring.
130          */
131         @Autowired
132         @Qualifier("documentTypeService")
133         private transient DocumentTypeService _documentTypeService;
134
135         /**
136          * The KnowledgeElementTypeService. Later injected by Spring.
137          */
138         @Autowired
139         @Qualifier("knowledgeElementTypeService")
140         private transient KnowledgeElementTypeService _knowledgeElementTypeService;
141
142         /**
143          * Test of getting a scenario content for building siman-salome.conf.<BR>
144          * <B>Description :</B> <BR>
145          * <i>Create a scenario and try to get an info for it.</i><BR>
146          * <B>Action : </B><BR>
147          * <i>1. call the method for an existing scenario id.</i><BR>
148          * <i>2. call the method for a not existing scenario id.</i><BR>
149          * <B>Test data : </B><BR>
150          * <i>no input parameters</i><BR>
151          * <i>no input parameters</i><BR>
152          * 
153          * <B>Outcome results:</B><BR>
154          * <i>
155          * <ul>
156          * <li>result DTO must contain list of all documents and files<BR>
157          * </li>
158          * <li>Exception is thrown<BR>
159          * </li>
160          * </ul>
161          * </i>
162          * 
163          * @throws InvalidPropertyException
164          *             if an invalid property is used when creating objects
165          * @throws MultiplyDefinedException
166          *             when trying to create an object with already existing id
167          * @throws MissedPropertyException
168          *             if a mandatory property is not defined for an object to be created
169          * @throws IOException
170          *             if scenario creation is failed
171          * @throws SQLException
172          *             if scenario creation is failed
173          */
174         @Test(groups = { "checkout", "sevice", "functional", "business" })
175         public void testGetScenarioInfo() throws InvalidPropertyException,
176                         MissedPropertyException, MultiplyDefinedException, IOException,
177                         SQLException {
178                 LOG.debug(">>>>> BEGIN testGetScenarioInfo()");
179                 startNestedTransaction();
180
181                 long scenarioId = createScenario();
182                 // Call DAO's create method for a good transient knowledge element.
183                 List<StepDTO> steps = _scenarioService.getScenarioInfo(scenarioId);
184                 Assert.assertNotNull(steps, "List of steps must not be null.");
185                 Assert.assertTrue(steps.size() > 0, "No steps are read.");
186
187                 List<Step> projSteps = _projectSettings.getStepsOf(Scenario.class);
188                 Assert.assertEquals(steps.size(), projSteps.size(),
189                                 "Not all steps are listed.");
190                 int docIndex = 0;
191                 for (StepDTO step : steps) {
192                         LOG.debug("check the step " + step.getNumber() + ":\n" + step);
193                         Assert.assertNotNull(step, "Step DTO must not be null.");
194                         Assert.assertNotNull(step.getKey(), "Step name must not be null.");
195                         Assert.assertFalse(step.getKey().isEmpty(),
196                                         "Step name must not empty.");
197                         Assert.assertTrue(step.getNumber() > 0,
198                                         "Step number must be positive integer.");
199                         Assert.assertNotNull(step.getDocs(),
200                                         "Step documents list must not be null.");
201
202                         Step aProjStep = null;
203                         for (Step projStep : projSteps) {
204                                 if (projStep.getNumber() == step.getNumber()) {
205                                         aProjStep = projStep;
206                                         break;
207                                 }
208                         }
209
210                         List<DocumentType> dtypes = _documentTypeService
211                                         .selectTypesOf(aProjStep);
212                         for (DocumentType dtype : dtypes) {
213                                 Assert.assertTrue(step.getDocs().size() > 0,
214                                                 "Step documents list must not be empty.");
215                                 String docName = "document" + docIndex;
216                                 for (DocumentDTO doc : step.getDocs()) {
217                                         if (docName.equals(doc.getTitle())) {
218                                                 Assert.assertTrue(doc.getId() > 0,
219                                                                 "Document id must be positive integer.");
220                                                 Assert.assertEquals(doc.getTitle(), docName);
221                                                 Assert.assertNotNull(doc.getFiles(),
222                                                                 "Document files list must not be null.");
223                                                 Assert
224                                                                 .assertTrue(doc.getFiles().size() > 1,
225                                                                                 "Document must have more then 1 attached file.");
226
227                                                 for (FileDTO file : doc.getFiles()) {
228                                                         Assert.assertNotNull(file.getPath(),
229                                                                         "File path must not be null.");
230                                                         Assert.assertFalse(file.getPath().isEmpty(),
231                                                                         "File path must not be empty.");
232                                                         /*
233                                                          * <mappings> <document type="geometry"> <import format="brep"/> <!-- Result Shape --> </document> <document
234                                                          * type="model"> <import format="med"/> <!-- Result mesh without input parameters --> </document> <document
235                                                          * type="loads"> <import format="c3m"/> <!-- Input data created interactively --> </document> <document
236                                                          * type="results"> <import format="med"/> <!-- Calculation results source file --> </document> </mappings>
237                                                          */
238                                                         // Check state and processing instruction
239                                                         String fileFormat = file.getPath().substring(
240                                                                         file.getPath().lastIndexOf('.') + 1);
241                                                         /*
242                                                          * if (_projectSettings.doImport(dtype.getName(), fileFormat)) { Assert.assertTrue(file.isResult(), "The file
243                                                          * must be a result file."); } else { Assert.assertFalse(file.isResult(), "The file must be a source file."); }
244                                                          */if ((docIndex % 2) == 0) { // New
245                                                                 Assert.assertEquals(file.getState(), 'Y',
246                                                                                 "File state must be actual ('Y').");
247                                                                 if (_projectSettings.doImport(dtype.getName(),
248                                                                                 fileFormat)) {
249                                                                         Assert.assertEquals(file.getProcessing(),
250                                                                                         "file-import",
251                                                                                         "File must be imported.");
252                                                                 } else {
253                                                                         Assert.assertEquals(file.getProcessing(),
254                                                                                         "file-download",
255                                                                                         "File must be downloaded.");
256                                                                 }
257                                                         } else { // Outdated
258                                                                 Assert.assertEquals(file.getState(), 'O',
259                                                                                 "File state must be outdated ('O').");
260                                                                 Assert
261                                                                                 .assertEquals(file.getProcessing(),
262                                                                                                 "file-download",
263                                                                                                 "Outdated document should not be imported but downloaded.");
264                                                         }
265                                                 }
266                                         }
267                                 }
268                                 docIndex++;
269                         }
270                 }
271
272                 // Call DAO's get method for a not existing id.
273                 try {
274                         steps = _scenarioService.getScenarioInfo(-1L);
275                         // getHibernateTemplate().flush();
276                         Assert
277                                         .fail("Getting an object with not existing id must be failed.");
278                 } catch (Exception e) {
279                         LOG.debug("Expected exception is thrown: "
280                                         + e.getClass().getSimpleName() + ": " + e.getMessage());
281                 }
282                 rollbackNestedTransaction();
283                 LOG.debug(">>>>> END testGetScenarioInfo()");
284         }
285
286         /**
287          * Test check-in scenario operation to be performed after SALOME session.<BR>
288          * <B>Description :</B> <BR>
289          * <i>Create a scenario and try to check-in it with some simulated SALOME results data.<BR>
290          * After check-in verify following points:
291          * <ul>
292          * <li>scenario is no more marked as checked out</li>
293          * <li>new document versions are created for checked in documents</li>
294          * <li>presentation of the previous version is removed</li>
295          * <li>uses relations are copied correctly</li>
296          * <li>files are moved correctly</li>
297          * <li>formats of files are new if they are according to the document's type on the study step</li>
298          * <li>new documents are created for new data</li>
299          * <li>new documents have correctly generated names</li>
300          * <li>uses relations are created correctly</li>
301          * <li>files are moved correctly</li>
302          * </ul>
303          * </i><BR>
304          * <B>Action : </B><BR>
305          * <i>1. call the method for an existing scenario id.</i><BR>
306          * <i>2. call the method for a not existing scenario id.</i><BR>
307          * <B>Test data : </B><BR>
308          * <i>no input parameters</i><BR>
309          * <i>no input parameters</i><BR>
310          * 
311          * <B>Outcome results:</B><BR>
312          * <i>
313          * <ul>
314          * <li>New version of existing documents must be created and new documents must be imported for documents with zero id. Correct
315          * relations must be created.<BR>
316          * </li>
317          * <li>Exception is thrown<BR>
318          * </li>
319          * </ul>
320          * </i>
321          * 
322          * @throws InvalidPropertyException
323          *             if an invalid property is used when creating objects
324          * @throws MultiplyDefinedException
325          *             when trying to create an object with already existing id
326          * @throws MissedPropertyException
327          *             if a mandatory property is not defined for an object to be created
328          * @throws IOException
329          *             if scenario creation is failed
330          * @throws SQLException
331          *             if scenario creation is failed
332          * @throws NotApplicableException
333          *             if checkin failed
334          * @throws MismatchException
335          *             if checkin failed
336          */
337         @Test(groups = { "checkin", "sevice", "functional", "business" })
338         public void testCheckin() throws InvalidPropertyException,
339                         MissedPropertyException, MultiplyDefinedException, IOException,
340                         SQLException, MismatchException, NotApplicableException {
341                 LOG.debug(">>>>> BEGIN testCheckin()");
342                 startNestedTransaction();
343
344                 _projectSettings.getAllSteps().clear(); // Clear config to be able to load it again
345                 _projectSettings.configure(ClassLoader
346                                 .getSystemResource("test/som.xml").getPath());
347                 getHibernateTemplate().flush();
348                 long scenarioId = createScenario();
349                 Scenario aScen = _scenarioDAO.get(scenarioId);
350                 User user = aScen.getAuthor();
351                 long userId = user.getIndex();
352
353                 
354                 // ////////////////////////////////////////////////////////
355                 // Call checkin method for empty list of modules.
356
357                 // Simulate checkout
358                 List<StepDTO> steps = _scenarioService.getScenarioInfo(scenarioId);
359                 _scenarioService.checkout(aScen, user);
360                 _scenarioDAO.flush();
361                 // Check that scenario is no more marked as checked out
362                 aScen = _scenarioDAO.get(scenarioId);
363                 Assert.assertTrue(aScen.isCheckedout(),
364                                 "Scenario is not marked as checked out after checkout.");
365
366                 // Prepare test data for checkin
367                 // Checkin only two first steps (geom and mesh)
368                 List<StepDTO> stepsToCheckin = new ArrayList<StepDTO>();
369                 // Do test checkin
370                 _scenarioService.checkin(scenarioId, userId, stepsToCheckin);
371
372                 _scenarioDAO.flush();
373                 // Check that scenario is no more marked as checked out
374                 aScen = _scenarioDAO.get(scenarioId);
375                 Assert.assertFalse(aScen.isCheckedout(),
376                                 "Scenario is still marked as checked out after checkin.");
377                 
378                 
379                 
380                 // ////////////////////////////////////////////////////////
381                 // Call checkin method for good prepared transient data.
382
383                 // Simulate checkout
384                 steps = _scenarioService.getScenarioInfo(scenarioId);
385                 _scenarioService.checkout(aScen, user);
386
387                 // Prepare test data for checkin
388                 // Checkin only two first steps (geom and mesh)
389                 for (StepDTO step : steps) {
390                         // Prepare GEOM: checkin actual brep
391                         StepDTO stepToCheckin = createDocDTOForModule(null, "GEOM", "brep",
392                                         userId, step, stepsToCheckin);
393                         createDocDTOForModule(stepToCheckin, "SMESH", "med", userId, step,
394                                         stepsToCheckin);
395                 }
396                 // Do test checkin
397                 _scenarioService.checkin(scenarioId, userId, stepsToCheckin);
398
399                 _scenarioDAO.flush();
400                 // Check that scenario is no more marked as checked out
401                 aScen = _scenarioDAO.get(scenarioId);
402                 Assert.assertFalse(aScen.isCheckedout(),
403                                 "Scenario is still marked as checked out after checkin.");
404                 // Check that new document versions are created for checked in documents
405                 for (StepDTO step : stepsToCheckin) {
406                         for (DocumentDTO docDTO : step.getDocs()) {
407                                 if ((docDTO.getId() != 0) && (docDTO.getId() != null)) {
408                                         boolean found = false;
409                                         Document prevDoc = null;
410                                         Document curDoc = null;
411                                         Publication newPub = null;
412                                         for (Publication pub : aScen.getDocums()) {
413                                                 prevDoc = pub.value().getPreviousVersion();
414                                                 if (prevDoc != null) {
415                                                         found = (prevDoc.getIndex() == docDTO.getId());
416                                                         if (found) { // Found next published version of the checked in document
417                                                                 newPub = pub;
418                                                                 break;
419                                                         }
420                                                 }
421                                                 if (pub.value().getIndex() == docDTO.getId()) {
422                                                         // Document version was not changed, old document is still published
423                                                         curDoc = pub.value();
424                                                         break;
425                                                 }
426                                         }
427                                         Assert.assertTrue(found || (curDoc != null),
428                                                         "New version or new attached file of the existing checked in document \""
429                                                                         + docDTO.getTitle() + "\" (id="
430                                                                         + docDTO.getId()
431                                                                         + ") is not found in the scenario.");
432                                         // If previous version is found then the format must be the same
433                                         String newFormat = docDTO.getFiles().get(0).getPath()
434                                                         .substring(
435                                                                         docDTO.getFiles().get(0).getPath()
436                                                                                         .lastIndexOf('.') + 1);
437                                         if (found) {
438                                                 Assert.assertEquals(prevDoc.getFormat(), newFormat,
439                                                                 "Formats of versions must be same");
440                                                 Assert.assertFalse(aScen.publishes(prevDoc));
441                                                 // Check that presentation of the previous version is removed
442                                                 checkFiles(docDTO, newPub);
443                                                 
444                                                 // Formats of files are new if they are according to the document's type on the study step
445                                                 if ("py".equals(prevDoc.getFormat())
446                                                                 && "geometry".equals(prevDoc.getType().getName())) {
447                                                         Assert.assertEquals(newPub.value().getFormat(), "brep");
448                                                         Assert.assertEquals(newPub.getSourceFile().getFormat(),
449                                                                         "brep");
450                                                         Assert.assertEquals(newPub.getSourceFile()
451                                                                         .getRelativePath().substring(
452                                                                                         newPub.getSourceFile()
453                                                                                                         .getRelativePath().lastIndexOf(
454                                                                                                                         '.') + 1), "brep");
455                                                 }
456
457                                                 // Check that uses relations are copied correctly
458
459                                                 // 1. Get all uses relations of the previous document version
460                                                 for (Relation rel : prevDoc
461                                                                 .getRelations(UsesRelation.class)) {
462                                                         Document used = ((UsesRelation) rel).getTo();
463                                                         // 2.1. Get the latest version of the document published in this scenario
464                                                         Publication toBeUsed = aScen.getPublication(used);
465                                                         if (toBeUsed == null) {
466                                                                 // Find the latest published version
467                                                                 for (Publication lastPub : aScen.getDocums()) {
468                                                                         if ((lastPub.value().getPreviousVersion() != null)
469                                                                                         && (lastPub.value()
470                                                                                                         .getPreviousVersion()
471                                                                                                         .getIndex() == used.getIndex())) {
472                                                                                 toBeUsed = lastPub;
473                                                                                 break;
474                                                                         }
475                                                                 }
476                                                         }
477                                                         if ((toBeUsed != null) && (!toBeUsed.isOutdated())) {
478                                                                 // 2.2. For each used document check that its latest not outdated version
479                                                                 // is used by the new checked in document version.
480                                                                 checkUsesRelation(newPub, toBeUsed);
481                                                         }
482                                                 }
483                                                 // 1. Get all usedBy relations of the previous document version
484                                                 for (Relation rel : prevDoc
485                                                                 .getRelations(UsedByRelation.class)) {
486                                                         Document using = ((UsedByRelation) rel).getTo();
487                                                         // Check that not checked in dependent documents became outdated
488                                                         Publication usingPub = aScen.getPublication(using);
489                                                         if (usingPub != null) { // if the document using the old version is still published
490                                                                 Assert.assertTrue(usingPub.isOutdated(),
491                                                                                 "Not checked in dependent document "
492                                                                                                 + using.getTitle() + " ("
493                                                                                                 + using.getType().getName()
494                                                                                                 + ") must become outdated.");
495                                                         }
496                                                 }
497                                         } else {
498                                                 // Otherwise the new file format must differ from the previous one
499                                                 // and the new file must be attached to the same document
500                                                 org.splat.dal.bo.som.File attFile = curDoc
501                                                                 .getAttachedFile(newFormat);
502                                                 Assert.assertNotNull(attFile, "File "
503                                                                 + docDTO.getFiles().get(0).getPath()
504                                                                 + " must be attached to the document "
505                                                                 + docDTO.getTitle() + "#" + docDTO.getId());
506                                                 Assert.assertTrue(attFile.asFile().exists(), "File "
507                                                                 + docDTO.getFiles().get(0).getPath()
508                                                                 + " attached to the document "
509                                                                 + docDTO.getTitle() + "#" + docDTO.getId() + " doesn't exist");
510                                                 LOG.debug("Source format: " + curDoc.getFormat() + ", new format: " + newFormat);
511                                         }
512
513
514                                 } else {
515                                         // Check that new documents are created for new data
516                                         boolean found = false;
517                                         Publication newPub = null;
518                                         for (Publication pub : aScen.getDocums()) {
519                                                 if (pub.value().getPreviousVersion() == null) {
520                                                         found = (pub.value().getTitle().startsWith(pub
521                                                                         .value().getType().getName()));
522                                                         if (found) { // Found next published version of the checked in document
523                                                                 String fcontent = Files.readFile(pub
524                                                                                 .getSourceFile().asFile());
525                                                                 found = fcontent.contains(docDTO.getTitle());
526                                                                 if (found) {
527                                                                         LOG
528                                                                                         .debug("Found new document with generated title: "
529                                                                                                         + pub.value().getTitle());
530                                                                         newPub = pub;
531                                                                         break;
532                                                                 }
533                                                         }
534                                                 }
535                                         }
536                                         Assert.assertTrue(found,
537                                                         "New document is not created for checked in document \""
538                                                                         + docDTO.getTitle() + "\".");
539
540                                         // Check that uses relations are created correctly
541                                         Assert.assertTrue(newPub.value().getTitle().startsWith(
542                                                         newPub.value().getType().getName() + "_"),
543                                                         "Document title newPub.value().getTitle() must start with "
544                                                                         + newPub.value().getType().getName() + "_");
545
546                                         // 1. Find the document type used by this document type
547                                         Set<DocumentType> usedTypes = newPub.value().getType()
548                                                         .getDefaultUses();
549                                         // 2. Find documents of used types in the current study step and previous study steps
550                                         for (Publication pub : aScen.getDocums()) {
551                                                 if ((pub.getStep().getNumber() <= step.getNumber())
552                                                                 && (!pub.isOutdated())
553                                                                 && usedTypes.contains(pub.value().getType())) {
554                                                         // 3. Check that there is uses relation to the found document
555                                                         // if it is not outdated.
556                                                         checkUsesRelation(newPub, pub);
557                                                 }
558                                         }
559
560                                         // Check that files are moved correctly
561                                         checkFiles(docDTO, newPub);
562                                 }
563                         }
564                 }
565
566                 // ///////////////////////////////////////////////////////////
567                 // Call checkin method for a not existing id.
568                 try {
569                         _scenarioService.checkin(-1, userId, stepsToCheckin);
570                         Assert
571                                         .fail("Check in for scenario with not existing id must be failed.");
572                 } catch (Exception e) {
573                         LOG.debug("Expected exception is thrown: "
574                                         + e.getClass().getSimpleName() + ": " + e.getMessage());
575                 }
576
577                 // Test checkin with empty list of steps
578                 stepsToCheckin.clear();
579                 _scenarioService.checkin(scenarioId, userId, stepsToCheckin);
580
581                 rollbackNestedTransaction();
582                 LOG.debug(">>>>> END testCheckin()");
583         }
584
585         /**
586          * Check if there is uses relation from the newPub to pub.
587          * 
588          * @param newPub
589          *            the new publication
590          * @param pub
591          *            the publication to be used
592          */
593         private void checkUsesRelation(final Publication newPub,
594                         final Publication pub) {
595                 boolean uses = false;
596                 boolean usesExist = false;
597                 for (Publication usesPub : newPub.getRelations(UsesRelation.class)) {
598                         usesExist = true;
599                         uses = (usesPub.equals(pub));
600                         if (uses) {
601                                 break;
602                         }
603                 }
604                 Assert.assertTrue(usesExist && uses, "The created document "
605                                 + newPub.value().getTitle() + "("
606                                 + newPub.value().getType().getName() + ")"
607                                 + " has no uses relation to the document "
608                                 + pub.value().getTitle() + "("
609                                 + pub.value().getType().getName() + ")");
610         }
611
612         /**
613          * Check that files are moved correctly.
614          * 
615          * @param docDTO
616          *            checked in document DTO
617          * @param newPub
618          *            the created document publication
619          */
620         private void checkFiles(final DocumentDTO docDTO, final Publication newPub) {
621                 // Check that original files are deleted
622                 for (int j = 0; j < docDTO.getFiles().size(); j++) {
623                         FileDTO fileDTO = docDTO.getFiles().get(j);
624                         Assert.assertFalse(new File(fileDTO.getPath()).exists(), "File"
625                                         + fileDTO.getPath()
626                                         + " was not removed from downloads directory.");
627                         String format = fileDTO.getPath().substring(
628                                         fileDTO.getPath().lastIndexOf('.') + 1);
629                 }
630                 // TODO: Check file by its internal content
631                 Assert.assertTrue(newPub.getSourceFile().exists(), "File "
632                                 + newPub.getSourceFile().asFile().getAbsolutePath()
633                                 + " for the document " + docDTO.getTitle()
634                                 + " was not created.");
635         }
636
637         /**
638          * Prepare a document with a file for check-in.
639          * 
640          * @param stepTo
641          *            step DTO with data for check-in
642          * @param module
643          *            SALOME module name
644          * @param format
645          *            file extension
646          * @param userId
647          *            download directory
648          * @param stepFrom
649          *            checked out stepDTO
650          * @param stepsToCheckin
651          *            DTO for check-in
652          * @throws IOException
653          *             if file creation failed
654          * @return step DTO with data prepared for check-in (stepTo or new if stepTo is null)
655          */
656         private StepDTO createDocDTOForModule(final StepDTO stepTo,
657                         final String module, final String format, final long userId,
658                         final StepDTO stepFrom, final List<StepDTO> stepsToCheckin)
659                         throws IOException {
660                 StepDTO stepToCheckin = stepTo;
661                 if (stepToCheckin == null) {
662                         stepToCheckin = new StepDTO();
663                 }
664                 if (module.equals(stepFrom.getModule())) {
665                         stepsToCheckin.add(stepToCheckin);
666                         stepToCheckin.setNumber(stepFrom.getNumber());
667                         for (DocumentDTO doc : stepFrom.getDocs()) {
668                                 if (doc.getFiles().get(0).getState() != 'O') {
669                                         DocumentDTO docToCheckin = stepToCheckin.addDoc(
670                                                         doc.getId(), doc.getTitle());
671                                         for (FileDTO file : doc.getFiles()) {
672                                                 if (file.getPath().endsWith(format)
673                                                                 || (file.getPath().endsWith("py") && (format
674                                                                                 .equals("brep") || format
675                                                                                 .equals("med")))) {
676                                                         // Create a file in the download directory
677                                                         docToCheckin.addFile(createDownloadedFile(userId,
678                                                                         doc.getTitle() + "_result", format));
679                                                 }
680                                         }
681                                 }
682                         }
683                         // Prepare new data
684                         stepToCheckin.addDoc(0, "newdoc" + stepFrom.getNumber()).addFile(
685                                         createDownloadedFile(userId, "newdoc"
686                                                         + stepFrom.getNumber(), "brep"));
687                 }
688                 return stepToCheckin;
689         }
690
691         /**
692          * Create a file in the user's repository downloads directory.
693          * 
694          * @param userId
695          *            user id
696          * @param name
697          *            file name
698          * @param format
699          *            file extension
700          * @return created file DTO
701          * @throws IOException
702          *             if file creation failed
703          */
704         private FileDTO createDownloadedFile(final long userId, final String name,
705                         final String format) throws IOException {
706                 // Create a file in the download directory
707                 return createDownloadedFile(userId, name + "." + format);
708         }
709
710         /**
711          * Create a file in the user's repository downloads directory.
712          * 
713          * @param userId
714          *            user id
715          * @param fname
716          *            file name
717          * @return created file DTO
718          * @throws IOException
719          *             if file creation failed
720          */
721         private FileDTO createDownloadedFile(final long userId, final String fname)
722                         throws IOException {
723                 // Create a file in the download directory
724                 String filePath = getDownloadPath(userId) + fname;
725                 FileWriter fw = new FileWriter(filePath);
726                 fw.write("Simulation of " + fname + " file for checkin at "
727                                 + new Date());
728                 fw.close();
729                 return new FileDTO(filePath);
730         }
731
732         /**
733          * Get path to the user's downloads directory. The directory is created if it is not exist yet.
734          * 
735          * @param userId
736          *            user id
737          * @return absolute path to downloads directory followed by slash
738          */
739         private String getDownloadPath(final long userId) {
740                 // Prepare download directory
741                 File tmpDir = _repositoryService.getDownloadDirectory(userId);
742                 if (!tmpDir.exists()) {
743                         Assert.assertTrue(tmpDir.mkdir(),
744                                         "Can't create temporary directory: "
745                                                         + tmpDir.getAbsolutePath());
746                 }
747
748                 return tmpDir.getAbsolutePath() + "/";
749         }
750
751         /**
752          * Create a persistent scenario for tests.
753          * 
754          * @return a persistent scenario
755          * @throws InvalidPropertyException
756          *             if an invalid property is used when creating objects
757          * @throws MultiplyDefinedException
758          *             when trying to create an object with already existing id
759          * @throws MissedPropertyException
760          *             if a mandatory property is not defined for an object to be created
761          * @throws IOException
762          *             if document creation is failed
763          * @throws SQLException
764          *             if project settings loading is failed
765          */
766         private long createScenario() throws InvalidPropertyException,
767                         MissedPropertyException, MultiplyDefinedException, IOException,
768                         SQLException {
769                 // Create a scenario for tests
770                 HibernateTemplate ht = getHibernateTemplate();
771
772                 Database.getInstance().reset();
773                 _projectSettings.getAllSteps().clear(); // Clear config to be able to load it again
774                 // Load workflow customization
775                 try {
776                         _projectSettings.configure(ClassLoader.getSystemResource(
777                                         "test/som.xml").getPath());
778                 } catch (FileNotFoundException e) {
779                         Assert.fail("Can't find som.xml: ", e);
780                 }
781                 List<Step> steps = _projectSettings.getStepsOf(Scenario.class);
782                 Assert.assertTrue(steps.size() > 0, "No steps are created.");
783
784                 // Create a test user
785                 User.Properties uprop = new User.Properties();
786                 uprop.setUsername("TST_Username").setName("TST_SimanUnitTestsUser")
787                                 .setFirstName("TST_FirstName").setDisplayName("TST_test.user")
788                                 .addRole("TST_user").setMailAddress(
789                                                 "noreply@salome-platform.org");
790                 uprop.disableCheck();
791                 User anAuthor = new User(uprop);
792                 ht.saveOrUpdate(anAuthor);
793
794                 // Create a test study
795                 Study.Properties stprops = new Study.Properties().setReference(
796                                 "TST_SID_01").setTitle("TST_Study").setManager(anAuthor);
797                 Study aStudy = new Study(stprops);
798                 ht.saveOrUpdate(aStudy);
799
800                 // Create a test scenario
801                 Scenario.Properties sprops = new Scenario.Properties().setTitle(
802                                 "TST_Scenario").setManager(anAuthor).setOwnerStudy(aStudy);
803                 Scenario aScenario = new Scenario(sprops);
804                 aStudy.getScenariiList().add(aScenario);
805                 ht.saveOrUpdate(anAuthor);
806                 ht.saveOrUpdate(aStudy);
807                 ht.saveOrUpdate(aScenario);
808
809                 // Create documents for each scenario step
810                 Document.Properties dprop = new Document.Properties().setAuthor(
811                                 anAuthor).setDate(new Date());
812                 int i = 0;
813                 Publication usedPub = null;
814                 Map<Long, Long> usedMap = new HashMap<Long, Long>();
815                 for (Step step : steps) {
816                         LOG.debug("Create scenario step: " + i);
817
818                         org.splat.som.Step aScStep = new org.splat.som.Step(step, aScenario);
819                         List<DocumentType> dtypes = _documentTypeService
820                                         .selectTypesOf(step);
821                         for (DocumentType dtype : dtypes) {
822                                 // Create a document published in the scenario
823                                 // document<i>: document type[0] - first type used on the step
824                                 // <source-file>.brep
825                                 // <attached-file>.med
826                                 dprop.setName("document" + i++).setType(dtype);
827 /*                              if (step.getNumber() > 3) {
828                                         dprop.setFormat("med");
829                                 } else {
830 */                                      dprop.setFormat("py");
831 //                              }
832                                 dprop.setLocalPath(dprop.getName() + "." + dprop.getFormat());
833                                 Publication pub = createDoc(aScenario, aScStep, dprop, "med",
834                                                 false);
835                                 if (usedPub != null) {
836                                         pub.addDependency(usedPub);
837                                         ht.saveOrUpdate(pub.value());
838
839                                         usedMap.put(pub.getIndex(), usedPub.getIndex());
840                                 }
841                                 usedPub = pub;
842
843                                 // Create another document with outdated publication
844                                 dprop.setName("document" + i++).setType(dtype).setFormat("py");
845                                 dprop.setLocalPath(dprop.getName() + "." + dprop.getFormat());
846                                 createDoc(aScenario, aScStep, dprop, "med", true);
847
848                         }
849                         if (dtypes.size() <= 0) {
850                                 LOG.debug("No document types are found for scenario step " + i);
851                         }
852                 }
853
854                 // Check that the scenario and its documents have been created correctly.
855
856                 Assert.assertNotNull(ht.find("from Document"),
857                                 "No documents in the database.");
858                 Assert.assertTrue(ht.find("from Document").size() > 0,
859                                 "No documents in the database.");
860
861                 Assert.assertNotNull(ht.find("from Publication where owner="
862                                 + aScenario.getIndex()), "No publications in the database.");
863                 Assert.assertTrue(
864                                 ht.find("from Publication where owner=" + aScenario.getIndex())
865                                                 .size() > 0, "No publications in the database.");
866
867                 for (Publication p : (List<Publication>) ht
868                                 .find("from Publication where owner=" + aScenario.getIndex())) {
869                         LOG.debug("Publication found: [id=" + p.getIndex() + ", owner="
870                                         + p.getOwner().getIndex() + ", doc=" + p.value().getIndex()
871                                         + "]");
872                         Assert.assertEquals(p.getOwner().getIndex(), aScenario.getIndex(),
873                                         "The publication was not attached to the scenario.");
874                 }
875
876                 // Remove the scenario from the current hibernate session.
877                 ht.evict(aScenario);
878                 // Check that the scenario is created in the database.
879                 Scenario aScen = ht.load(Scenario.class, aScenario.getIndex());
880                 Assert.assertNotNull(aScen, "Scenario was not saved in the database.");
881                 Assert.assertTrue(aScen.getDocums().size() > 0,
882                                 "No publications in the scenario.");
883
884                 Assert.assertTrue(i > 0,
885                                 "More then one document must be in the database");
886
887                 // Check created uses relations
888                 Assert
889                                 .assertTrue(usedMap.size() > 0,
890                                                 "Uses relations must be created.");
891                 boolean foundAny = false;
892                 for (Long usingId : usedMap.keySet()) {
893                         for (Publication pub : aScen.getDocums()) {
894                                 if (pub.getIndex() == usingId) {
895                                         boolean found = false;
896                                         for (Publication used : aScen.getDocums()) {
897                                                 found = (used.getIndex() == usedMap.get(usingId));
898                                                 if (found) {
899                                                         break;
900                                                 }
901                                         }
902                                         Assert.assertTrue(found,
903                                                         "Uses relation was not created in the database.");
904                                         foundAny = foundAny || found;
905                                 }
906                         }
907                 }
908                 Assert.assertTrue(foundAny,
909                                 "No Uses relation was created in the database.");
910
911                 return aScenario.getIndex();
912         }
913
914         /**
915          * Create a document published in the scenario. <BR>
916          * document:<BR>
917          * document type[0] - first type used on the step <BR>
918          * &lt;source-file&gt;.brep <BR>
919          * &lt;attached-file&gt;.med
920          * 
921          * @param aScenario
922          *            the scenario to add the document to
923          * @param aScStep
924          *            scenario step where the document to be published
925          * @param dprop
926          *            document properties
927          * @param attachedFileExt
928          *            extension of the secon attached (exported) file
929          * @param isOutdated
930          *            outdated document flag
931          * @return the publication of the created document
932          * @throws IOException
933          * @throws MultiplyDefinedException
934          * @throws InvalidPropertyException
935          * @throws MissedPropertyException
936          */
937         private Publication createDoc(final Scenario aScenario,
938                         final org.splat.som.Step aScStep, final Properties dprop,
939                         final String attachedFileExt, final boolean isOutdated)
940                         throws MissedPropertyException, InvalidPropertyException,
941                         MultiplyDefinedException, IOException {
942                 // Create a document published in the scenario
943                 // document<i>: document type[0] - first type used on the step
944                 // <source-file>.brep
945                 // <attached-file>.med
946                 createDownloadedFile(aScenario.getAuthor().getIndex(), dprop
947                                 .getLocalPath());
948                 Publication pub = _stepService.createDocument(aScStep, dprop);
949                 Assert.assertNotNull(pub.getOwner(),
950                                 "The publication must be attached to the scenario.");
951                 Assert.assertEquals(pub.getOwner().getIndex(), aScenario.getIndex(),
952                                 "The publication was not attached to the scenario.");
953
954                 if (isOutdated) {
955                         pub.setIsnew('O');
956                 }
957                 aScenario.add(pub);
958                 HibernateTemplate ht = getHibernateTemplate();
959                 ht.saveOrUpdate(pub);
960
961                 // Attach a file
962                 createDownloadedFile(aScenario.getAuthor().getIndex(), dprop
963                                 .getLocalPath().substring(0,
964                                                 dprop.getLocalPath().lastIndexOf(".") - 1),
965                                 attachedFileExt);
966                 ht.save(pub.value());
967                 ht.saveOrUpdate(_publicationService.attach(pub, attachedFileExt));
968
969                 return pub;
970         }
971
972         /**
973          * Test check-in scenario operation to be performed after SALOME session.<BR>
974          * <B>Description :</B> <BR>
975          * <i>Create a scenario and try to check-in it with some simulated SALOME results data.<BR>
976          * After check-in verify following points:
977          * <ul>
978          * <li>scenario is no more marked as checked out</li>
979          * <li>new document versions are created for checked in documents</li>
980          * <li>presentation of the previous version is removed</li>
981          * <li>uses relations are copied correctly</li>
982          * <li>files are moved correctly</li>
983          * <li>new documents are created for new data</li>
984          * <li>uses relations are created correctly</li>
985          * <li>files are moved correctly</li>
986          * </ul>
987          * </i><BR>
988          * <B>Action : </B><BR>
989          * <i>1. call the method for an existing scenario id.</i><BR>
990          * <i>2. call the method for a not existing scenario id.</i><BR>
991          * <B>Test data : </B><BR>
992          * <i>no input parameters</i><BR>
993          * <i>no input parameters</i><BR>
994          * 
995          * <B>Outcome results:</B><BR>
996          * <i>
997          * <ul>
998          * <li>New version of existing documents must be created and new documents must be imported for documents with zero id. Correct
999          * relations must be created.<BR>
1000          * </li>
1001          * <li>Exception is thrown<BR>
1002          * </li>
1003          * </ul>
1004          * </i>
1005          * 
1006          * @throws InvalidPropertyException
1007          *             if an invalid property is used when creating objects
1008          * @throws MultiplyDefinedException
1009          *             when trying to create an object with already existing id
1010          * @throws MissedPropertyException
1011          *             if a mandatory property is not defined for an object to be created
1012          * @throws IOException
1013          *             if scenario creation is failed
1014          * @throws SQLException
1015          *             if scenario creation is failed
1016          * @throws NotApplicableException
1017          *             if checkin failed
1018          * @throws MismatchException
1019          *             if checkin failed
1020          */
1021         @Test(groups = { "study", "sevice", "functional", "business" })
1022         public void testCreateStudy() throws InvalidPropertyException,
1023                         MissedPropertyException, MultiplyDefinedException, IOException,
1024                         SQLException, MismatchException, NotApplicableException {
1025                 LOG.debug(">>>>> BEGIN testCreateStudy()");
1026                 startNestedTransaction();
1027
1028                 Database.getInstance().reset();
1029                 _projectSettings.getAllSteps().clear(); // Clear config to be able to load it again
1030                 _projectSettings.configure(ClassLoader
1031                                 .getSystemResource("test/som.xml").getPath());
1032
1033                 // Create a test user
1034                 User.Properties uprop = new User.Properties();
1035                 uprop.setUsername("TST_Username").setName("TST_SimanUnitTestsUser")
1036                                 .setFirstName("TST_FirstName").setDisplayName("TST_test.user")
1037                                 .addRole("TST_user").setMailAddress(
1038                                                 "noreply@salome-platform.org");
1039                 uprop.disableCheck();
1040                 User anAuthor = new User(uprop);
1041
1042                 getHibernateTemplate().saveOrUpdate(anAuthor);
1043                 KnowledgeElementType ucase = _knowledgeElementTypeService
1044                                 .selectType("usecase");
1045                 Assert.assertNotNull(ucase,
1046                                 "Knowledge type 'usecase' must be created in the database.");
1047                 SimulationContextType prodtype = _simulationContextService
1048                                 .selectType("product");
1049                 Assert
1050                                 .assertNotNull(prodtype,
1051                                                 "Simulation context type 'product' must be created in the database.");
1052
1053                 // Create admin
1054                 uprop.clear();
1055                 uprop.setUsername("TST_Admin").setName("TST_SimanUnitTestsAdmin")
1056                                 .setFirstName("TST_AdminFirstName").setDisplayName(
1057                                                 "TST_test.admin").addRole("TST_user,sysadmin")
1058                                 .setMailAddress("noreply@salome-platform.org");
1059                 uprop.disableCheck();
1060
1061                 getHibernateTemplate().saveOrUpdate(new User(uprop));
1062                 getHibernateTemplate().flush();
1063
1064                 Study.Properties sprop = new Study.Properties();
1065                 sprop.setTitle("Test study creation").setManager(anAuthor);
1066                 Scenario.Properties oprop = new Scenario.Properties();
1067                 oprop.setTitle("Test scenario for the created study");
1068
1069                 // Addition of the entered project context
1070                 SimulationContext.Properties cprop = new SimulationContext.Properties();
1071                 // Input of new project context
1072                 cprop.setType(_simulationContextService.selectType("product"))
1073                                 .setValue("Test Simulation Context: Product");
1074                 Study study = _scenarioService.createStudy(sprop, oprop, cprop);
1075
1076                 rollbackNestedTransaction();
1077                 LOG.debug(">>>>> END testCreateStudy()");
1078         }
1079 }