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