Salome HOME
Fix for checkin: attach a new file to the same version if format differs from the...
[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                 // Call checkin method for good prepared transient data.
355
356                 // Simulate checkout
357                 List<StepDTO> steps = _scenarioService.getScenarioInfo(scenarioId);
358                 _scenarioService.checkout(aScen, user);
359
360                 // Prepare test data for checkin
361                 // Checkin only two first steps (geom and mesh)
362                 List<StepDTO> stepsToCheckin = new ArrayList<StepDTO>();
363                 for (StepDTO step : steps) {
364                         // Prepare GEOM: checkin actual brep
365                         StepDTO stepToCheckin = createDocDTOForModule(null, "GEOM", "brep",
366                                         userId, step, stepsToCheckin);
367                         createDocDTOForModule(stepToCheckin, "SMESH", "med", userId, step,
368                                         stepsToCheckin);
369                 }
370                 // Do test checkin
371                 _scenarioService.checkin(scenarioId, userId, stepsToCheckin);
372
373                 _scenarioDAO.flush();
374                 // Check that scenario is no more marked as checked out
375                 aScen = _scenarioDAO.get(scenarioId);
376                 Assert.assertFalse(aScen.isCheckedout(),
377                                 "Scenario is still marked as checked out after checkin.");
378                 // Check that new document versions are created for checked in documents
379                 boolean caseFound = false;
380                 for (StepDTO step : stepsToCheckin) {
381                         for (DocumentDTO docDTO : step.getDocs()) {
382                                 if ((docDTO.getId() != 0) && (docDTO.getId() != null)) {
383                                         boolean found = false;
384                                         Document prevDoc = null;
385                                         Document curDoc = null;
386                                         Publication newPub = null;
387                                         for (Publication pub : aScen.getDocums()) {
388                                                 prevDoc = pub.value().getPreviousVersion();
389                                                 if (prevDoc != null) {
390                                                         found = (prevDoc.getIndex() == docDTO.getId());
391                                                         if (found) { // Found next published version of the checked in document
392                                                                 newPub = pub;
393                                                                 break;
394                                                         }
395                                                 }
396                                                 if (pub.value().getIndex() == docDTO.getId()) {
397                                                         // Document version was not changed, old document is still published
398                                                         curDoc = pub.value();
399                                                         break;
400                                                 }
401                                         }
402                                         Assert.assertTrue(found || (curDoc != null),
403                                                         "New version or new attached file of the existing checked in document \""
404                                                                         + docDTO.getTitle() + "\" (id="
405                                                                         + docDTO.getId()
406                                                                         + ") is not found in the scenario.");
407                                         // If previous version is found then the format must be the same
408                                         String newFormat = docDTO.getFiles().get(0).getPath()
409                                                         .substring(
410                                                                         docDTO.getFiles().get(0).getPath()
411                                                                                         .lastIndexOf('.') + 1);
412                                         if (found) {
413                                                 Assert.assertEquals(prevDoc.getFormat(), newFormat,
414                                                                 "Formats of versions must be same");
415                                                 Assert.assertFalse(aScen.publishes(prevDoc));
416                                                 // Check that presentation of the previous version is removed
417                                                 checkFiles(docDTO, newPub);
418                                                 
419                                                 // Formats of files are new if they are according to the document's type on the study step
420                                                 if ("py".equals(prevDoc.getFormat())
421                                                                 && "geometry".equals(prevDoc.getType().getName())) {
422                                                         Assert.assertEquals(newPub.value().getFormat(), "brep");
423                                                         Assert.assertEquals(newPub.getSourceFile().getFormat(),
424                                                                         "brep");
425                                                         Assert.assertEquals(newPub.getSourceFile()
426                                                                         .getRelativePath().substring(
427                                                                                         newPub.getSourceFile()
428                                                                                                         .getRelativePath().lastIndexOf(
429                                                                                                                         '.') + 1), "brep");
430                                                 }
431
432                                                 // Check that uses relations are copied correctly
433
434                                                 // 1. Get all uses relations of the previous document version
435                                                 for (Relation rel : prevDoc
436                                                                 .getRelations(UsesRelation.class)) {
437                                                         Document used = ((UsesRelation) rel).getTo();
438                                                         // 2.1. Get the latest version of the document published in this scenario
439                                                         Publication toBeUsed = aScen.getPublication(used);
440                                                         if (toBeUsed == null) {
441                                                                 // Find the latest published version
442                                                                 for (Publication lastPub : aScen.getDocums()) {
443                                                                         if ((lastPub.value().getPreviousVersion() != null)
444                                                                                         && (lastPub.value()
445                                                                                                         .getPreviousVersion()
446                                                                                                         .getIndex() == used.getIndex())) {
447                                                                                 toBeUsed = lastPub;
448                                                                                 break;
449                                                                         }
450                                                                 }
451                                                         }
452                                                         if ((toBeUsed != null) && (!toBeUsed.isOutdated())) {
453                                                                 // 2.2. For each used document check that its latest not outdated version
454                                                                 // is used by the new checked in document version.
455                                                                 checkUsesRelation(newPub, toBeUsed);
456                                                         }
457                                                 }
458                                                 // 1. Get all usedBy relations of the previous document version
459                                                 for (Relation rel : prevDoc
460                                                                 .getRelations(UsedByRelation.class)) {
461                                                         Document using = ((UsedByRelation) rel).getTo();
462                                                         // Check that not checked in dependent documents became outdated
463                                                         Publication usingPub = aScen.getPublication(using);
464                                                         if (usingPub != null) { // if the document using the old version is still published
465                                                                 Assert.assertTrue(usingPub.isOutdated(),
466                                                                                 "Not checked in dependent document "
467                                                                                                 + using.getTitle() + " ("
468                                                                                                 + using.getType().getName()
469                                                                                                 + ") must become outdated.");
470                                                                 caseFound = true;
471                                                         }
472                                                 }
473                                         } else {
474                                                 // Otherwise the new file format must differ from the previous one
475                                                 // and the new file must be attached to the same document
476                                                 org.splat.dal.bo.som.File attFile = curDoc
477                                                                 .getAttachedFile(newFormat);
478                                                 Assert.assertNotNull(attFile, "File "
479                                                                 + docDTO.getFiles().get(0).getPath()
480                                                                 + " must be attached to the document "
481                                                                 + docDTO.getTitle() + "#" + docDTO.getId());
482                                                 Assert.assertTrue(attFile.asFile().exists(), "File "
483                                                                 + docDTO.getFiles().get(0).getPath()
484                                                                 + " attached to the document "
485                                                                 + docDTO.getTitle() + "#" + docDTO.getId() + " doesn't exist");
486                                         }
487
488
489                                 } else {
490                                         // Check that new documents are created for new data
491                                         boolean found = false;
492                                         Publication newPub = null;
493                                         for (Publication pub : aScen.getDocums()) {
494                                                 if (pub.value().getPreviousVersion() == null) {
495                                                         found = (pub.value().getTitle().startsWith(pub
496                                                                         .value().getType().getName()));
497                                                         if (found) { // Found next published version of the checked in document
498                                                                 String fcontent = Files.readFile(pub
499                                                                                 .getSourceFile().asFile());
500                                                                 found = fcontent.contains(docDTO.getTitle());
501                                                                 if (found) {
502                                                                         LOG
503                                                                                         .debug("Found new document with generated title: "
504                                                                                                         + pub.value().getTitle());
505                                                                         newPub = pub;
506                                                                         break;
507                                                                 }
508                                                         }
509                                                 }
510                                         }
511                                         Assert.assertTrue(found,
512                                                         "New document is not created for checked in document \""
513                                                                         + docDTO.getTitle() + "\".");
514
515                                         // Check that uses relations are created correctly
516                                         Assert.assertTrue(newPub.value().getTitle().startsWith(
517                                                         newPub.value().getType().getName() + "_"),
518                                                         "Document title newPub.value().getTitle() must start with "
519                                                                         + newPub.value().getType().getName() + "_");
520
521                                         // 1. Find the document type used by this document type
522                                         Set<DocumentType> usedTypes = newPub.value().getType()
523                                                         .getDefaultUses();
524                                         // 2. Find documents of used types in the current study step and previous study steps
525                                         for (Publication pub : aScen.getDocums()) {
526                                                 if ((pub.getStep().getNumber() <= step.getNumber())
527                                                                 && (!pub.isOutdated())
528                                                                 && usedTypes.contains(pub.value().getType())) {
529                                                         // 3. Check that there is uses relation to the found document
530                                                         // if it is not outdated.
531                                                         checkUsesRelation(newPub, pub);
532                                                 }
533                                         }
534
535                                         // Check that files are moved correctly
536                                         checkFiles(docDTO, newPub);
537                                 }
538                         }
539                 }
540                 Assert.assertTrue(caseFound,
541                                 "Not checked in dependent documents must become outdated.");
542
543                 // ///////////////////////////////////////////////////////////
544                 // Call checkin method for a not existing id.
545                 try {
546                         _scenarioService.checkin(-1, userId, stepsToCheckin);
547                         Assert
548                                         .fail("Check in for scenario with not existing id must be failed.");
549                 } catch (Exception e) {
550                         LOG.debug("Expected exception is thrown: "
551                                         + e.getClass().getSimpleName() + ": " + e.getMessage());
552                 }
553
554                 // Test checkin with empty list of steps
555                 stepsToCheckin.clear();
556                 _scenarioService.checkin(scenarioId, userId, stepsToCheckin);
557
558                 rollbackNestedTransaction();
559                 LOG.debug(">>>>> END testCheckin()");
560         }
561
562         /**
563          * Check if there is uses relation from the newPub to pub.
564          * 
565          * @param newPub
566          *            the new publication
567          * @param pub
568          *            the publication to be used
569          */
570         private void checkUsesRelation(final Publication newPub,
571                         final Publication pub) {
572                 boolean uses = false;
573                 boolean usesExist = false;
574                 for (Publication usesPub : newPub.getRelations(UsesRelation.class)) {
575                         usesExist = true;
576                         uses = (usesPub.equals(pub));
577                         if (uses) {
578                                 break;
579                         }
580                 }
581                 Assert.assertTrue(usesExist && uses, "The created document "
582                                 + newPub.value().getTitle() + "("
583                                 + newPub.value().getType().getName() + ")"
584                                 + " has no uses relation to the document "
585                                 + pub.value().getTitle() + "("
586                                 + pub.value().getType().getName() + ")");
587         }
588
589         /**
590          * Check that files are moved correctly.
591          * 
592          * @param docDTO
593          *            checked in document DTO
594          * @param newPub
595          *            the created document publication
596          */
597         private void checkFiles(final DocumentDTO docDTO, final Publication newPub) {
598                 // Check that original files are deleted
599                 for (int j = 0; j < docDTO.getFiles().size(); j++) {
600                         FileDTO fileDTO = docDTO.getFiles().get(j);
601                         Assert.assertFalse(new File(fileDTO.getPath()).exists(), "File"
602                                         + fileDTO.getPath()
603                                         + " was not removed from downloads directory.");
604                         String format = fileDTO.getPath().substring(
605                                         fileDTO.getPath().lastIndexOf('.') + 1);
606                 }
607                 // TODO: Check file by its internal content
608                 Assert.assertTrue(newPub.getSourceFile().exists(), "File "
609                                 + newPub.getSourceFile().asFile().getAbsolutePath()
610                                 + " for the document " + docDTO.getTitle()
611                                 + " was not created.");
612         }
613
614         /**
615          * Prepare a document with a file for check-in.
616          * 
617          * @param stepTo
618          *            step DTO with data for check-in
619          * @param module
620          *            SALOME module name
621          * @param format
622          *            file extension
623          * @param userId
624          *            download directory
625          * @param stepFrom
626          *            checked out stepDTO
627          * @param stepsToCheckin
628          *            DTO for check-in
629          * @throws IOException
630          *             if file creation failed
631          * @return step DTO with data prepared for check-in (stepTo or new if stepTo is null)
632          */
633         private StepDTO createDocDTOForModule(final StepDTO stepTo,
634                         final String module, final String format, final long userId,
635                         final StepDTO stepFrom, final List<StepDTO> stepsToCheckin)
636                         throws IOException {
637                 StepDTO stepToCheckin = stepTo;
638                 if (stepToCheckin == null) {
639                         stepToCheckin = new StepDTO();
640                 }
641                 if (module.equals(stepFrom.getModule())) {
642                         stepsToCheckin.add(stepToCheckin);
643                         stepToCheckin.setNumber(stepFrom.getNumber());
644                         for (DocumentDTO doc : stepFrom.getDocs()) {
645                                 if (doc.getFiles().get(0).getState() != 'O') {
646                                         DocumentDTO docToCheckin = stepToCheckin.addDoc(
647                                                         doc.getId(), doc.getTitle());
648                                         for (FileDTO file : doc.getFiles()) {
649                                                 if (file.getPath().endsWith(format)
650                                                                 || (file.getPath().endsWith("py") && format
651                                                                                 .equals("brep"))) {
652                                                         // Create a file in the download directory
653                                                         docToCheckin.addFile(createDownloadedFile(userId,
654                                                                         doc.getTitle() + "_result", format));
655                                                 }
656                                         }
657                                 }
658                         }
659                         // Prepare new data
660                         stepToCheckin.addDoc(0, "newdoc" + stepFrom.getNumber()).addFile(
661                                         createDownloadedFile(userId, "newdoc"
662                                                         + stepFrom.getNumber(), "brep"));
663                 }
664                 return stepToCheckin;
665         }
666
667         /**
668          * Create a file in the user's repository downloads directory.
669          * 
670          * @param userId
671          *            user id
672          * @param name
673          *            file name
674          * @param format
675          *            file extension
676          * @return created file DTO
677          * @throws IOException
678          *             if file creation failed
679          */
680         private FileDTO createDownloadedFile(final long userId, final String name,
681                         final String format) throws IOException {
682                 // Create a file in the download directory
683                 return createDownloadedFile(userId, name + "." + format);
684         }
685
686         /**
687          * Create a file in the user's repository downloads directory.
688          * 
689          * @param userId
690          *            user id
691          * @param fname
692          *            file name
693          * @return created file DTO
694          * @throws IOException
695          *             if file creation failed
696          */
697         private FileDTO createDownloadedFile(final long userId, final String fname)
698                         throws IOException {
699                 // Create a file in the download directory
700                 String filePath = getDownloadPath(userId) + fname;
701                 FileWriter fw = new FileWriter(filePath);
702                 fw.write("Simulation of " + fname + " file for checkin at "
703                                 + new Date());
704                 fw.close();
705                 return new FileDTO(filePath);
706         }
707
708         /**
709          * Get path to the user's downloads directory. The directory is created if it is not exist yet.
710          * 
711          * @param userId
712          *            user id
713          * @return absolute path to downloads directory followed by slash
714          */
715         private String getDownloadPath(final long userId) {
716                 // Prepare download directory
717                 File tmpDir = _repositoryService.getDownloadDirectory(userId);
718                 if (!tmpDir.exists()) {
719                         Assert.assertTrue(tmpDir.mkdir(),
720                                         "Can't create temporary directory: "
721                                                         + tmpDir.getAbsolutePath());
722                 }
723
724                 return tmpDir.getAbsolutePath() + "/";
725         }
726
727         /**
728          * Create a persistent scenario for tests.
729          * 
730          * @return a persistent scenario
731          * @throws InvalidPropertyException
732          *             if an invalid property is used when creating objects
733          * @throws MultiplyDefinedException
734          *             when trying to create an object with already existing id
735          * @throws MissedPropertyException
736          *             if a mandatory property is not defined for an object to be created
737          * @throws IOException
738          *             if document creation is failed
739          * @throws SQLException
740          *             if project settings loading is failed
741          */
742         private long createScenario() throws InvalidPropertyException,
743                         MissedPropertyException, MultiplyDefinedException, IOException,
744                         SQLException {
745                 // Create a scenario for tests
746                 HibernateTemplate ht = getHibernateTemplate();
747
748                 Database.getInstance().reset();
749                 _projectSettings.getAllSteps().clear(); // Clear config to be able to load it again
750                 // Load workflow customization
751                 try {
752                         _projectSettings.configure(ClassLoader.getSystemResource(
753                                         "test/som.xml").getPath());
754                 } catch (FileNotFoundException e) {
755                         Assert.fail("Can't find som.xml: ", e);
756                 }
757                 List<Step> steps = _projectSettings.getStepsOf(Scenario.class);
758                 Assert.assertTrue(steps.size() > 0, "No steps are created.");
759
760                 // Create a test user
761                 User.Properties uprop = new User.Properties();
762                 uprop.setUsername("TST_Username").setName("TST_SimanUnitTestsUser")
763                                 .setFirstName("TST_FirstName").setDisplayName("TST_test.user")
764                                 .addRole("TST_user").setMailAddress(
765                                                 "noreply@salome-platform.org");
766                 uprop.disableCheck();
767                 User anAuthor = new User(uprop);
768                 ht.saveOrUpdate(anAuthor);
769
770                 // Create a test study
771                 Study.Properties stprops = new Study.Properties().setReference(
772                                 "TST_SID_01").setTitle("TST_Study").setManager(anAuthor);
773                 Study aStudy = new Study(stprops);
774                 ht.saveOrUpdate(aStudy);
775
776                 // Create a test scenario
777                 Scenario.Properties sprops = new Scenario.Properties().setTitle(
778                                 "TST_Scenario").setManager(anAuthor).setOwnerStudy(aStudy);
779                 Scenario aScenario = new Scenario(sprops);
780                 aStudy.getScenariiList().add(aScenario);
781                 ht.saveOrUpdate(anAuthor);
782                 ht.saveOrUpdate(aStudy);
783                 ht.saveOrUpdate(aScenario);
784
785                 // Create documents for each scenario step
786                 Document.Properties dprop = new Document.Properties().setAuthor(
787                                 anAuthor).setDate(new Date());
788                 int i = 0;
789                 Publication usedPub = null;
790                 Map<Long, Long> usedMap = new HashMap<Long, Long>();
791                 for (Step step : steps) {
792                         LOG.debug("Create scenario step: " + i);
793
794                         org.splat.som.Step aScStep = new org.splat.som.Step(step, aScenario);
795                         List<DocumentType> dtypes = _documentTypeService
796                                         .selectTypesOf(step);
797                         for (DocumentType dtype : dtypes) {
798                                 // Create a document published in the scenario
799                                 // document<i>: document type[0] - first type used on the step
800                                 // <source-file>.brep
801                                 // <attached-file>.med
802                                 dprop.setName("document" + i++).setType(dtype);
803                                 if (step.getNumber() > 3) {
804                                         dprop.setFormat("med");
805                                 } else {
806                                         dprop.setFormat("py");
807                                 }
808                                 dprop.setLocalPath(dprop.getName() + "." + dprop.getFormat());
809                                 Publication pub = createDoc(aScenario, aScStep, dprop, "med",
810                                                 false);
811                                 if (usedPub != null) {
812                                         pub.addDependency(usedPub);
813                                         ht.saveOrUpdate(pub.value());
814
815                                         usedMap.put(pub.getIndex(), usedPub.getIndex());
816                                 }
817                                 usedPub = pub;
818
819                                 // Create another document with outdated publication
820                                 dprop.setName("document" + i++).setType(dtype).setFormat("py");
821                                 dprop.setLocalPath(dprop.getName() + "." + dprop.getFormat());
822                                 createDoc(aScenario, aScStep, dprop, "med", true);
823
824                         }
825                         if (dtypes.size() <= 0) {
826                                 LOG.debug("No document types are found for scenario step " + i);
827                         }
828                 }
829
830                 // Check that the scenario and its documents have been created correctly.
831
832                 Assert.assertNotNull(ht.find("from Document"),
833                                 "No documents in the database.");
834                 Assert.assertTrue(ht.find("from Document").size() > 0,
835                                 "No documents in the database.");
836
837                 Assert.assertNotNull(ht.find("from Publication where owner="
838                                 + aScenario.getIndex()), "No publications in the database.");
839                 Assert.assertTrue(
840                                 ht.find("from Publication where owner=" + aScenario.getIndex())
841                                                 .size() > 0, "No publications in the database.");
842
843                 for (Publication p : (List<Publication>) ht
844                                 .find("from Publication where owner=" + aScenario.getIndex())) {
845                         LOG.debug("Publication found: [id=" + p.getIndex() + ", owner="
846                                         + p.getOwner().getIndex() + ", doc=" + p.value().getIndex()
847                                         + "]");
848                         Assert.assertEquals(p.getOwner().getIndex(), aScenario.getIndex(),
849                                         "The publication was not attached to the scenario.");
850                 }
851
852                 // Remove the scenario from the current hibernate session.
853                 ht.evict(aScenario);
854                 // Check that the scenario is created in the database.
855                 Scenario aScen = ht.load(Scenario.class, aScenario.getIndex());
856                 Assert.assertNotNull(aScen, "Scenario was not saved in the database.");
857                 Assert.assertTrue(aScen.getDocums().size() > 0,
858                                 "No publications in the scenario.");
859
860                 Assert.assertTrue(i > 0,
861                                 "More then one document must be in the database");
862
863                 // Check created uses relations
864                 Assert
865                                 .assertTrue(usedMap.size() > 0,
866                                                 "Uses relations must be created.");
867                 boolean foundAny = false;
868                 for (Long usingId : usedMap.keySet()) {
869                         for (Publication pub : aScen.getDocums()) {
870                                 if (pub.getIndex() == usingId) {
871                                         boolean found = false;
872                                         for (Publication used : aScen.getDocums()) {
873                                                 found = (used.getIndex() == usedMap.get(usingId));
874                                                 if (found) {
875                                                         break;
876                                                 }
877                                         }
878                                         Assert.assertTrue(found,
879                                                         "Uses relation was not created in the database.");
880                                         foundAny = foundAny || found;
881                                 }
882                         }
883                 }
884                 Assert.assertTrue(foundAny,
885                                 "No Uses relation was created in the database.");
886
887                 return aScenario.getIndex();
888         }
889
890         /**
891          * Create a document published in the scenario. <BR>
892          * document:<BR>
893          * document type[0] - first type used on the step <BR>
894          * &lt;source-file&gt;.brep <BR>
895          * &lt;attached-file&gt;.med
896          * 
897          * @param aScenario
898          *            the scenario to add the document to
899          * @param aScStep
900          *            scenario step where the document to be published
901          * @param dprop
902          *            document properties
903          * @param attachedFileExt
904          *            extension of the secon attached (exported) file
905          * @param isOutdated
906          *            outdated document flag
907          * @return the publication of the created document
908          * @throws IOException
909          * @throws MultiplyDefinedException
910          * @throws InvalidPropertyException
911          * @throws MissedPropertyException
912          */
913         private Publication createDoc(final Scenario aScenario,
914                         final org.splat.som.Step aScStep, final Properties dprop,
915                         final String attachedFileExt, final boolean isOutdated)
916                         throws MissedPropertyException, InvalidPropertyException,
917                         MultiplyDefinedException, IOException {
918                 // Create a document published in the scenario
919                 // document<i>: document type[0] - first type used on the step
920                 // <source-file>.brep
921                 // <attached-file>.med
922                 createDownloadedFile(aScenario.getAuthor().getIndex(), dprop
923                                 .getLocalPath());
924                 Publication pub = _stepService.createDocument(aScStep, dprop);
925                 Assert.assertNotNull(pub.getOwner(),
926                                 "The publication must be attached to the scenario.");
927                 Assert.assertEquals(pub.getOwner().getIndex(), aScenario.getIndex(),
928                                 "The publication was not attached to the scenario.");
929
930                 if (isOutdated) {
931                         pub.setIsnew('O');
932                 }
933                 aScenario.add(pub);
934                 HibernateTemplate ht = getHibernateTemplate();
935                 ht.saveOrUpdate(pub);
936
937                 // Attach a file
938                 createDownloadedFile(aScenario.getAuthor().getIndex(), dprop
939                                 .getLocalPath().substring(0,
940                                                 dprop.getLocalPath().lastIndexOf(".") - 1),
941                                 attachedFileExt);
942                 ht.save(pub.value());
943                 ht.saveOrUpdate(_publicationService.attach(pub, attachedFileExt));
944
945                 return pub;
946         }
947
948         /**
949          * Test check-in scenario operation to be performed after SALOME session.<BR>
950          * <B>Description :</B> <BR>
951          * <i>Create a scenario and try to check-in it with some simulated SALOME results data.<BR>
952          * After check-in verify following points:
953          * <ul>
954          * <li>scenario is no more marked as checked out</li>
955          * <li>new document versions are created for checked in documents</li>
956          * <li>presentation of the previous version is removed</li>
957          * <li>uses relations are copied correctly</li>
958          * <li>files are moved correctly</li>
959          * <li>new documents are created for new data</li>
960          * <li>uses relations are created correctly</li>
961          * <li>files are moved correctly</li>
962          * </ul>
963          * </i><BR>
964          * <B>Action : </B><BR>
965          * <i>1. call the method for an existing scenario id.</i><BR>
966          * <i>2. call the method for a not existing scenario id.</i><BR>
967          * <B>Test data : </B><BR>
968          * <i>no input parameters</i><BR>
969          * <i>no input parameters</i><BR>
970          * 
971          * <B>Outcome results:</B><BR>
972          * <i>
973          * <ul>
974          * <li>New version of existing documents must be created and new documents must be imported for documents with zero id. Correct
975          * relations must be created.<BR>
976          * </li>
977          * <li>Exception is thrown<BR>
978          * </li>
979          * </ul>
980          * </i>
981          * 
982          * @throws InvalidPropertyException
983          *             if an invalid property is used when creating objects
984          * @throws MultiplyDefinedException
985          *             when trying to create an object with already existing id
986          * @throws MissedPropertyException
987          *             if a mandatory property is not defined for an object to be created
988          * @throws IOException
989          *             if scenario creation is failed
990          * @throws SQLException
991          *             if scenario creation is failed
992          * @throws NotApplicableException
993          *             if checkin failed
994          * @throws MismatchException
995          *             if checkin failed
996          */
997         @Test(groups = { "study", "sevice", "functional", "business" })
998         public void testCreateStudy() throws InvalidPropertyException,
999                         MissedPropertyException, MultiplyDefinedException, IOException,
1000                         SQLException, MismatchException, NotApplicableException {
1001                 LOG.debug(">>>>> BEGIN testCreateStudy()");
1002                 startNestedTransaction();
1003
1004                 Database.getInstance().reset();
1005                 _projectSettings.getAllSteps().clear(); // Clear config to be able to load it again
1006                 _projectSettings.configure(ClassLoader
1007                                 .getSystemResource("test/som.xml").getPath());
1008
1009                 // Create a test user
1010                 User.Properties uprop = new User.Properties();
1011                 uprop.setUsername("TST_Username").setName("TST_SimanUnitTestsUser")
1012                                 .setFirstName("TST_FirstName").setDisplayName("TST_test.user")
1013                                 .addRole("TST_user").setMailAddress(
1014                                                 "noreply@salome-platform.org");
1015                 uprop.disableCheck();
1016                 User anAuthor = new User(uprop);
1017
1018                 getHibernateTemplate().saveOrUpdate(anAuthor);
1019                 KnowledgeElementType ucase = _knowledgeElementTypeService
1020                                 .selectType("usecase");
1021                 Assert.assertNotNull(ucase,
1022                                 "Knowledge type 'usecase' must be created in the database.");
1023                 SimulationContextType prodtype = _simulationContextService
1024                                 .selectType("product");
1025                 Assert
1026                                 .assertNotNull(prodtype,
1027                                                 "Simulation context type 'product' must be created in the database.");
1028
1029                 // Create admin
1030                 uprop.clear();
1031                 uprop.setUsername("TST_Admin").setName("TST_SimanUnitTestsAdmin")
1032                                 .setFirstName("TST_AdminFirstName").setDisplayName(
1033                                                 "TST_test.admin").addRole("TST_user,sysadmin")
1034                                 .setMailAddress("noreply@salome-platform.org");
1035                 uprop.disableCheck();
1036
1037                 getHibernateTemplate().saveOrUpdate(new User(uprop));
1038                 getHibernateTemplate().flush();
1039
1040                 Study.Properties sprop = new Study.Properties();
1041                 sprop.setTitle("Test study creation").setManager(anAuthor);
1042                 Scenario.Properties oprop = new Scenario.Properties();
1043                 oprop.setTitle("Test scenario for the created study");
1044
1045                 // Addition of the entered project context
1046                 SimulationContext.Properties cprop = new SimulationContext.Properties();
1047                 // Input of new project context
1048                 cprop.setType(_simulationContextService.selectType("product"))
1049                                 .setValue("Test Simulation Context: Product");
1050                 Study study = _scenarioService.createStudy(sprop, oprop, cprop);
1051
1052                 rollbackNestedTransaction();
1053                 LOG.debug(">>>>> END testCreateStudy()");
1054         }
1055 }