]> SALOME platform Git repositories - tools/siman.git/blob - Workspace/Siman-Common/src/test/splat/service/TestPublicationService.java
Salome HOME
04f2b076e6f63386ba7e8d258ddc706facc6deb2
[tools/siman.git] / Workspace / Siman-Common / src / test / splat / service / TestPublicationService.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.BufferedReader;
12 import java.io.DataInputStream;
13 import java.io.File;
14 import java.io.FileInputStream;
15 import java.io.FileNotFoundException;
16 import java.io.FileWriter;
17 import java.io.IOException;
18 import java.io.InputStreamReader;
19 import java.sql.SQLException;
20 import java.text.DecimalFormat;
21 import java.text.ParseException;
22 import java.util.ArrayList;
23 import java.util.Arrays;
24 import java.util.Calendar;
25 import java.util.Date;
26 import java.util.HashMap;
27 import java.util.List;
28 import java.util.Map;
29
30 import org.splat.dal.bo.kernel.User;
31 import org.splat.dal.bo.som.ConvertsRelation;
32 import org.splat.dal.bo.som.Document;
33 import org.splat.dal.bo.som.DocumentType;
34 import org.splat.dal.bo.som.ProgressState;
35 import org.splat.dal.bo.som.ProjectElement;
36 import org.splat.dal.bo.som.Publication;
37 import org.splat.dal.bo.som.Scenario;
38 import org.splat.dal.bo.som.Study;
39 import org.splat.dal.bo.som.Document.Properties;
40 import org.splat.dal.dao.kernel.UserDAO;
41 import org.splat.dal.dao.som.Database;
42 import org.splat.dal.dao.som.ScenarioDAO;
43 import org.splat.dal.dao.som.StudyDAO;
44 import org.splat.exception.BusinessException;
45 import org.splat.exception.IncompatibleDataException;
46 import org.splat.kernel.InvalidPropertyException;
47 import org.splat.kernel.MissedPropertyException;
48 import org.splat.kernel.MultiplyDefinedException;
49 import org.splat.kernel.NotApplicableException;
50 import org.splat.log.AppLogger;
51 import org.splat.service.DocumentTypeService;
52 import org.splat.service.ProjectElementService;
53 import org.splat.service.PublicationService;
54 import org.splat.service.StepService;
55 import org.splat.service.StudyService;
56 import org.splat.service.technical.ProjectSettingsService;
57 import org.splat.service.technical.RepositoryService;
58 import org.splat.service.technical.ProjectSettingsService.Step;
59 import org.springframework.beans.factory.annotation.Autowired;
60 import org.springframework.beans.factory.annotation.Qualifier;
61 import org.springframework.orm.hibernate3.HibernateTemplate;
62 import org.testng.Assert;
63 import org.testng.annotations.Test;
64
65 import test.splat.common.BaseTest;
66 import test.splat.util.TestEntitiesGenerator;
67
68 /**
69  * Test class for PublicationService.
70  * 
71  * @author <a href="mailto:roman.kozlov@opencascade.com">Roman Kozlov (RKV)</a>
72  * 
73  */
74 public class TestPublicationService extends BaseTest {
75
76         /**
77          * Logger for the class.
78          */
79         private static final AppLogger LOG = AppLogger
80                         .getLogger(TestPublicationService.class);
81
82         /**
83          * The StudyDAO. Later injected by Spring.
84          */
85         @Autowired
86         @Qualifier("studyDAO")
87         private transient StudyDAO _studyDAO;
88
89         /**
90          * The PublicationService. Later injected by Spring.
91          */
92         @Autowired
93         @Qualifier("publicationService")
94         private transient PublicationService _publicationService;
95
96         /**
97          * The ProjectElementService. Later injected by Spring.
98          */
99         @Autowired
100         @Qualifier("projectElementService")
101         private transient ProjectElementService _projectElementService;
102
103         /**
104          * The StepService. Later injected by Spring.
105          */
106         @Autowired
107         @Qualifier("stepService")
108         private transient StepService _stepService;
109
110         /**
111          * The ProjectSettingsService. Later injected by Spring.
112          */
113         @Autowired
114         @Qualifier("projectSettings")
115         private transient ProjectSettingsService _projectSettings;
116
117         /**
118          * The DocumentTypeService. Later injected by Spring.
119          */
120         @Autowired
121         @Qualifier("documentTypeService")
122         private transient DocumentTypeService _documentTypeService;
123
124         /**
125          * The StudyService. Later injected by Spring.
126          */
127         @Autowired
128         @Qualifier("studyService")
129         private transient StudyService _studyService;
130
131         /**
132          * The RepositoryService. Later injected by Spring.
133          */
134         @Autowired
135         @Qualifier("repositoryService")
136         private transient RepositoryService _repositoryService;
137
138         /**
139          * The UserDAO. Later injected by Spring.
140          */
141         @Autowired
142         @Qualifier("userDAO")
143         private transient UserDAO _userDAO;
144
145         /**
146          * The Scenario DAO. Later injected by Spring.
147          */
148         @Autowired
149         @Qualifier("scenarioDAO")
150         private transient ScenarioDAO _scenarioDAO;
151
152         /**
153          * Create a persistent scenario for tests.
154          * 
155          * @return a persistent scenario
156          * @throws InvalidPropertyException
157          *             if an invalid property is used when creating objects
158          * @throws MultiplyDefinedException
159          *             when trying to create an object with already existing id
160          * @throws MissedPropertyException
161          *             if a mandatory property is not defined for an object to be created
162          * @throws IOException
163          *             if document creation is failed
164          * @throws SQLException
165          *             if project settings loading is failed
166          */
167         private Study createStudy() throws InvalidPropertyException,
168                         MissedPropertyException, MultiplyDefinedException, IOException,
169                         SQLException {
170                 // Create a scenario for tests
171                 HibernateTemplate ht = getHibernateTemplate();
172
173                 Database.getInstance().reset();
174                 _projectSettings.getAllSteps().clear(); // Clear config to be able to load it again
175                 // Load workflow customization
176                 try {
177                         _projectSettings.configure("classpath:test/som.xml");
178                 } catch (FileNotFoundException e) {
179                         Assert.fail("Can't find som.xml: ", e);
180                 }
181                 List<Step> steps = _projectSettings.getAllSteps();
182                 Assert.assertTrue(steps.size() > 0, "No steps are created.");
183
184                 // Create a test user
185                 User.Properties uprop = new User.Properties();
186                 uprop.setUsername("TST_Username").setName("TST_SimanUnitTestsUser")
187                                 .setFirstName("TST_FirstName").setDisplayName("TST_test.user")
188                                 .addRole("TST_user").setMailAddress(
189                                                 "noreply@salome-platform.org");
190                 uprop.disableCheck();
191                 User anAuthor = new User(uprop);
192                 ht.saveOrUpdate(anAuthor);
193
194                 // Create a test study
195                 Study.Properties stprops = new Study.Properties().setReference(
196                                 "TST_SID_01").setTitle("TST_Study").setManager(anAuthor);
197                 Study aStudy = new Study(stprops);
198                 ht.saveOrUpdate(aStudy);
199
200                 // Create a test scenario
201                 Scenario.Properties sprops = new Scenario.Properties().setTitle(
202                                 "TST_Scenario").setManager(anAuthor).setOwnerStudy(aStudy);
203                 Scenario aScenario = new Scenario(sprops);
204                 aStudy.getScenariiList().add(aScenario);
205                 ht.saveOrUpdate(anAuthor);
206                 ht.saveOrUpdate(aStudy);
207                 ht.saveOrUpdate(aScenario);
208
209                 // Create documents for each scenario step
210                 Document.Properties dprop = new Document.Properties().setAuthor(
211                                 anAuthor).setDate(new Date());
212                 int i = 0;
213                 Publication usedPub = null;
214                 Map<Long, Long> usedMap = new HashMap<Long, Long>();
215                 for (int stepNum = 1; stepNum <= steps.size(); stepNum++) {
216                         Step step = _projectSettings.getStep(stepNum);
217                         LOG.debug("Create scenario step: " + stepNum);
218                         ProjectElement projElem;
219
220                         if (step.appliesTo(Study.class)) {
221                                 projElem = aStudy;
222                         } else {
223                                 projElem = aScenario;
224                         }
225                         org.splat.som.Step aScStep = new org.splat.som.Step(step, projElem);
226                         List<DocumentType> dtypes = _documentTypeService
227                                         .selectTypesOf(step);
228                         if (dtypes.size() > 0) {
229                                 DocumentType dtype = dtypes.get(0);
230                                 // Create a document published in the scenario
231                                 // document<i>: document type[0] - first type used on the step
232                                 // <source-file>.brep
233                                 // <attached-file>.med
234                                 i++;
235                                 dprop.setName("document" + stepNum).setType(dtype);
236                                 if (step.getNumber() > 3) {
237                                         dprop.setFormat("med");
238                                 } else {
239                                         dprop.setFormat("py");
240                                 }
241                                 Publication pub = createDoc(projElem, aScStep, dprop, "med",
242                                                 false);
243                                 if (usedPub != null) {
244                                         pub.addDependency(usedPub);
245                                         LOG.debug("Add dependency: " + pub.value().getTitle()
246                                                         + " from " + usedPub.value().getTitle());
247                                         ht.saveOrUpdate(pub.value());
248                                         ht.flush();
249
250                                         usedMap.put(pub.getIndex(), usedPub.getIndex());
251                                 }
252                                 usedPub = pub;
253                         }
254                         if (dtypes.size() <= 0) {
255                                 LOG.debug("No document types are found for scenario step " + i);
256                         }
257                 }
258
259                 // Check that the scenario and its documents have been created correctly.
260
261                 Assert.assertNotNull(ht.find("from Document"),
262                                 "No documents in the database.");
263                 Assert.assertTrue(ht.find("from Document").size() > 0,
264                                 "No documents in the database.");
265
266                 Assert.assertNotNull(ht.find("from Publication where owner="
267                                 + aScenario.getIndex()), "No publications in the database.");
268                 Assert.assertTrue(
269                                 ht.find("from Publication where owner=" + aScenario.getIndex())
270                                                 .size() > 0, "No publications in the database.");
271
272                 for (Publication p : (List<Publication>) ht
273                                 .find("from Publication where owner=" + aScenario.getIndex())) {
274                         LOG.debug("Publication found: [id=" + p.getIndex() + ", owner="
275                                         + p.getOwner().getIndex() + ", doc=" + p.value().getIndex()
276                                         + "]");
277                         Assert.assertEquals(p.getOwner().getIndex(), aScenario.getIndex(),
278                                         "The publication was not attached to the scenario.");
279                 }
280
281                 // Remove the scenario from the current hibernate session.
282                 ht.evict(aScenario);
283                 // Check that the scenario is created in the database.
284                 Scenario aScen = ht.load(Scenario.class, aScenario.getIndex());
285                 Assert.assertNotNull(aScen, "Scenario was not saved in the database.");
286                 Assert.assertTrue(aScen.getDocums().size() > 0,
287                                 "No publications in the scenario.");
288
289                 Assert.assertTrue(i > 0,
290                                 "More then one document must be in the database");
291
292                 // Check created uses relations
293                 Assert
294                                 .assertTrue(usedMap.size() > 0,
295                                                 "Uses relations must be created.");
296                 boolean foundAny = false;
297                 for (Long usingId : usedMap.keySet()) {
298                         for (Publication pub : aScen.getDocums()) {
299                                 if (pub.getIndex() == usingId) {
300                                         boolean found = false;
301                                         for (Publication used : aScen.getDocums()) {
302                                                 found = (used.getIndex() == usedMap.get(usingId));
303                                                 if (found) {
304                                                         break;
305                                                 }
306                                         }
307                                         if (!found) {
308                                                 for (Publication used : aStudy.getDocums()) {
309                                                         found = (used.getIndex() == usedMap.get(usingId));
310                                                         if (found) {
311                                                                 break;
312                                                         }
313                                                 }
314                                         }
315                                         Assert.assertTrue(found,
316                                                         "Uses relation was not created in the database.");
317                                         foundAny = foundAny || found;
318                                 }
319                         }
320                 }
321                 Assert.assertTrue(foundAny,
322                                 "No Uses relation was created in the database.");
323
324                 return aScenario.getOwnerStudy();
325         }
326
327         /**
328          * Create a document published in the scenario. <BR>
329          * document:<BR>
330          * document type - type used on the step <BR>
331          * &lt;source-file&gt;.brep <BR>
332          * &lt;attached-file&gt;.med
333          * 
334          * @param aScenario
335          *            the scenario to add the document to
336          * @param aScStep
337          *            scenario step where the document to be published
338          * @param dprop
339          *            document properties
340          * @param attachedFileExt
341          *            extension of the secon attached (exported) file
342          * @param isOutdated
343          *            outdated document flag
344          * @return the publication of the created document
345          * @throws IOException
346          * @throws MultiplyDefinedException
347          * @throws InvalidPropertyException
348          * @throws MissedPropertyException
349          */
350         private Publication createDoc(final ProjectElement aScenario,
351                         final org.splat.som.Step aScStep, final Properties dprop,
352                         final String attachedFileExt, final boolean isOutdated)
353                         throws MissedPropertyException, InvalidPropertyException,
354                         MultiplyDefinedException, IOException {
355                 // Create a document published in the scenario
356                 // document<i>: document type - type used on the step
357                 // <source-file>.brep
358                 // <attached-file>.med
359                 Publication pub = _stepService.createDocument(aScStep, dprop);
360                 Assert.assertNotNull(pub.getOwner(),
361                                 "The publication must be attached to the scenario.");
362                 Assert.assertEquals(pub.getOwner().getIndex(), aScenario.getIndex(),
363                                 "The publication was not attached to the scenario.");
364
365                 if (isOutdated) {
366                         pub.setIsnew('O');
367                 }
368                 aScenario.add(pub);
369                 HibernateTemplate ht = getHibernateTemplate();
370                 ht.saveOrUpdate(pub);
371
372                 // Attach a file
373                 ht.save(pub.value());
374                 ht.flush();
375                 ht.saveOrUpdate(_publicationService.attach(pub, attachedFileExt));
376
377                 return pub;
378         }
379
380         /**
381          * Test of generating a study document index.<BR>
382          * <B>Description :</B> <BR>
383          * <i>Create a study and try to generate the next document index.</i><BR>
384          * <B>Action : </B><BR>
385          * <i>1. call DAO's read method for an existing id.</i><BR>
386          * <B>Test data : </B><BR>
387          * <i>no input parameters</i><BR>
388          * 
389          * <B>Outcome results:</B><BR>
390          * <i>
391          * <ul>
392          * <li>The new index must be equal to the incremented old one and saved into the database<BR>
393          * </li>
394          * </ul>
395          * </i>
396          * 
397          * @throws InvalidPropertyException
398          *             if an invalid property is used when creating objects
399          * @throws MultiplyDefinedException
400          *             when trying to create an object with already existing id
401          * @throws MissedPropertyException
402          *             if a mandatory property is not defined for an object to be created
403          * @throws SQLException
404          *             if test study creation is failed
405          * @throws IOException
406          *             if test study creation is failed
407          * @throws ParseException
408          * @throws InterruptedException
409          * @throws NotApplicableException
410          * 
411          */
412         @Test
413         public void testCreateDoc() throws InvalidPropertyException,
414                         MissedPropertyException, MultiplyDefinedException, IOException,
415                         SQLException, NotApplicableException, InterruptedException,
416                         ParseException {
417                 LOG.debug(">>>>> BEGIN testCreateDoc()");
418                 startNestedTransaction();
419
420                 HibernateTemplate ht = getHibernateTemplate();
421                 Study aStudy = createStudy();
422                 // Call DAO's create method for a good transient study.
423                 Long id = aStudy.getIndex();
424                 Assert.assertNotNull(id,
425                                 "Create method returns null instead of a new id.");
426                 Assert.assertTrue(id > 0, "The new id is not a positive number.");
427
428                 // Call DAO's get method for an existing id.
429                 _studyDAO.flush();
430                 getHibernateTemplate().evict(aStudy);
431                 getHibernateTemplate().clear();
432                 Study aStudyFound = _studyDAO.get(id);
433                 ht.evict(aStudyFound);
434
435                 long userId = aStudyFound.getAuthor().getIndex();
436                 org.splat.som.Step[] studySteps = _projectElementService
437                                 .getSteps(aStudyFound);
438                 org.splat.som.Step[] scSteps = _projectElementService
439                                 .getSteps(aStudyFound.getScenarii()[0]);
440
441                 List<org.splat.som.Step> steps = new ArrayList<org.splat.som.Step>();
442                 steps.addAll(Arrays.asList(studySteps));
443                 steps.addAll(Arrays.asList(scSteps));
444                 steps.addAll(Arrays.asList(studySteps));
445                 DecimalFormat tostring = new DecimalFormat(Document.suformat);
446                 for (org.splat.som.Step step : steps) {
447                         LOG.debug("Create a document for the step " + step.getNumber());
448
449                         List<DocumentType> dtypes = _documentTypeService.selectTypesOf(step
450                                         .getStep());
451                         if (dtypes.size() > 0) {
452                                 DocumentType dtype = dtypes.get(0);
453                                 int oldInd = ht.get(Study.class, aStudyFound.getIndex())
454                                                 .getLastLocalIndex();
455
456                                 // Create a file in the download directory
457                                 String fname = "filename" + step.getNumber() + ".py";
458                                 String filePath = getDownloadPath(aStudyFound.getAuthor())
459                                                 + fname;
460                                 LOG.debug(step.getStep().getKey() + ": "
461                                                 + step.getOwner().getClass().getSimpleName()
462                                                 + ": Create test file: " + filePath);
463                                 FileWriter fw = new FileWriter(filePath);
464                                 fw
465                                                 .write("Simulation of filename.py file for creating a new document at "
466                                                                 + new Date());
467                                 fw.close();
468
469                                 Publication addoc = _publicationService.createDoc(aStudyFound
470                                                 .getIndex(), step, dtype.getIndex(), userId, fname,
471                                                 "tstdoc", ProgressState.inWORK, "", "", new Date(),
472                                                 null);
473
474                                 _studyDAO.flush();
475                                 ht.flush();
476
477                                 int ind = ht.get(Study.class, aStudyFound.getIndex())
478                                                 .getLastLocalIndex();
479
480                                 LOG.debug("Previous index: " + oldInd + ", new index: " + ind);
481                                 Assert.assertEquals(ht.get(Study.class, aStudyFound.getIndex())
482                                                 .getLastLocalIndex(), oldInd + 1,
483                                                 "Incremented index must be saved in the database.");
484                                 aStudy = (Study) ht.find(
485                                                 "from Study where rid = " + aStudyFound.getIndex())
486                                                 .get(0);
487                                 Assert.assertEquals(aStudy.getLastLocalIndex(), oldInd + 1,
488                                                 "Incremented index must be saved in the database.");
489                                 Assert.assertEquals(addoc.getSourceFile().getName(), tostring
490                                                 .format(aStudy.getLastLocalIndex())
491                                                 + "_" + fname, "The generated file name is incorrect.");
492                         }
493                 }
494
495                 rollbackNestedTransaction();
496                 LOG.debug(">>>>> END testCreateDoc()");
497         }
498
499         /**
500          * Test of file attaching to a study document.<BR>
501          * <B>Description :</B> <BR>
502          * <i>Create a study and try to attach a new file to its each document.</i><BR>
503          * <B>Action : </B><BR>
504          * <i>1. call attach method for each document publication of the study.</i><BR>
505          * <B>Test data : </B><BR>
506          * <i>no input parameters</i><BR>
507          * 
508          * <B>Outcome results:</B><BR>
509          * <i>
510          * <ul>
511          * <li>The new ConvertsRelation and the new File object must be created in the database.<BR>
512          * </li>
513          * </ul>
514          * </i>
515          * 
516          * @throws InvalidPropertyException
517          *             if an invalid property is used when creating objects
518          * @throws MultiplyDefinedException
519          *             when trying to create an object with already existing id
520          * @throws MissedPropertyException
521          *             if a mandatory property is not defined for an object to be created
522          * @throws SQLException
523          *             if test study creation is failed
524          * @throws IOException
525          *             if test study creation is failed
526          * @throws ParseException
527          * @throws InterruptedException
528          * @throws NotApplicableException
529          * 
530          */
531         @Test
532         public void testAttach() throws InvalidPropertyException,
533                         MissedPropertyException, MultiplyDefinedException, IOException,
534                         SQLException, NotApplicableException, InterruptedException,
535                         ParseException {
536                 LOG.debug(">>>>> BEGIN testAttach()");
537                 startNestedTransaction();
538
539                 HibernateTemplate ht = getHibernateTemplate();
540                 Study aStudy = createStudy();
541                 // Call DAO's create method for a good transient study.
542                 Long id = aStudy.getIndex();
543                 Assert.assertNotNull(id,
544                                 "Create method returns null instead of a new id.");
545                 Assert.assertTrue(id > 0, "The new id is not a positive number.");
546
547                 // Call DAO's get method for an existing id.
548                 _studyDAO.flush();
549                 getHibernateTemplate().evict(aStudy);
550                 getHibernateTemplate().clear();
551                 Study aStudyFound = _studyDAO.get(id);
552                 ht.clear();
553                 ht.evict(aStudyFound);
554
555                 long userId = aStudyFound.getAuthor().getIndex();
556                 org.splat.som.Step[] studySteps = _projectElementService
557                                 .getSteps(aStudyFound);
558                 org.splat.som.Step[] scSteps = _projectElementService
559                                 .getSteps(aStudyFound.getScenarii()[0]);
560
561                 List<org.splat.som.Step> steps = new ArrayList<org.splat.som.Step>();
562                 steps.addAll(Arrays.asList(studySteps));
563                 steps.addAll(Arrays.asList(scSteps));
564                 steps.addAll(Arrays.asList(studySteps));
565                 for (org.splat.som.Step step : steps) {
566                         LOG.debug("Attach a new .py file to documents of the step "
567                                         + step.getNumber() + ": " + step.getStep().getKey() + ": "
568                                         + step.getOwner().getClass().getSimpleName());
569
570                         for (Publication pub : step.getAllDocuments()) {
571
572                                 ht.evict(step.getOwner());
573                                 ht.evict(pub);
574                                 ht.evict(pub.value());
575                                 int nbConverts = ht.find("from ConvertsRelation").size();
576                                 int nbDocConverts = ht.find(
577                                                 "from ConvertsRelation where owner="
578                                                                 + pub.value().getIndex()).size();
579                                 int nbFiles = ht.find("from File").size();
580
581                                 ConvertsRelation rel = _publicationService.attach(pub, "py");
582
583                                 _studyDAO.flush();
584                                 ht.flush();
585                                 Assert.assertNotNull(rel,
586                                                 "Returned ConvertsRelation must not be null.");
587                                 Assert
588                                                 .assertTrue(rel.isSaved(),
589                                                                 "Returned ConvertsRelation must be saved in the database.");
590                                 Assert.assertEquals(ht.find(
591                                                 "from ConvertsRelation where owner="
592                                                                 + pub.value().getIndex()).size(),
593                                                 nbDocConverts + 1,
594                                                 "Number of created ConvertsRelations must be 1.");
595                                 Assert.assertEquals(ht.find("from ConvertsRelation").size(),
596                                                 nbConverts + 1,
597                                                 "Number of created ConvertsRelations must be 1.");
598                                 Assert.assertNotNull(rel.getTo(),
599                                                 "Attached File must not be null.");
600                                 Assert.assertTrue(rel.isSaved(),
601                                                 "Attached File must be saved in the database.");
602                                 Assert
603                                                 .assertEquals(ht
604                                                                 .find(
605                                                                                 "from File where rid="
606                                                                                                 + rel.getTo().getIndex())
607                                                                 .size(), 1, "Number of created File must be 1.");
608                                 Assert.assertEquals(ht.find("from File").size(), nbFiles + 1,
609                                                 "Number of created Files must be 1.");
610                         }
611                 }
612
613                 rollbackNestedTransaction();
614                 LOG.debug(">>>>> END testAttach()");
615         }
616
617         /**
618          * Get path to the user's downloads directory. The directory is created if it is not exist yet.
619          * 
620          * @param user
621          *            user
622          * @return absolute path to downloads directory followed by slash
623          */
624         private String getDownloadPath(final User user) {
625                 // Prepare download directory
626                 File tmpDir = _repositoryService.getDownloadDirectory(user);
627                 if (!tmpDir.exists()) {
628                         Assert.assertTrue(tmpDir.mkdir(),
629                                         "Can't create temporary directory: "
630                                                         + tmpDir.getAbsolutePath());
631                 }
632
633                 return tmpDir.getAbsolutePath() + "/";
634         }
635
636         /**
637          * Test testReplace method for a published document.<BR>
638          * <B>Description :</B> <BR>
639          * <i>Create a study and a scenario with documents and try to replace source files.<BR>
640          * </i><BR>
641          * <B>Action : </B><BR>
642          * <i>1. call the method for a document in the status inDRAFT.</i><BR>
643          * <i>2. call the method for a document in the status inCHECK.</i><BR>
644          * <i>3. call the method for a document in the status APPROVED.</i><BR>
645          * <i>4. call the method for an Extern document published in the study step.</i><BR>
646          * <i>5. call the method for an inWork document published in the scenario step.</i><BR>
647          * <B>Test data : </B><BR>
648          * <i>no input parameters</i><BR>
649          * 
650          * <B>Outcome results:</B><BR>
651          * <i>
652          * <ul>
653          * <li>1-3: Exception must be thrown. The document source file content must not be replaced.<BR>
654          * </li>
655          * <li>4: The document source file content in the study must be replaced.<BR>
656          * </li>
657          * <li>5: The document source file content in the scenario must be replaced.<BR>
658          * </li>
659          * </ul>
660          * </i>
661          * 
662          * @throws BusinessException
663          *             if test data creation is failed
664          * @throws IOException
665          *             if application configuration loading or test data creation is failed
666          * @throws SQLException
667          *             if application configuration loading or test data creation is failed
668          */
669         @Test
670         public void testReplace() throws BusinessException, IOException,
671                         SQLException {
672                 LOG.debug(">>>>> BEGIN testReplace()");
673                 startNestedTransaction();
674
675                 HibernateTemplate ht = getHibernateTemplate();
676
677                 Database.getInstance().reset();
678                 _projectSettings.getAllSteps().clear(); // Clear config to be able to load it again
679                 _projectSettings.configure("classpath:test/som.xml");
680
681                 User goodUser = TestEntitiesGenerator.getTestUser("GoodUser");
682                 _userDAO.create(goodUser);
683
684                 // Create private study
685                 Study aStudy = TestEntitiesGenerator.getTestStudy(goodUser);
686                 aStudy.setTitle("0.This is private study");
687                 Long studyId = _studyDAO.create(aStudy);
688
689                 // Add a scenario to the study
690                 Scenario scen = TestEntitiesGenerator.getTestScenario(aStudy);
691                 Long scenId = _scenarioDAO.create(scen);
692                 ht.flush();
693
694                 DocumentType dtype = _documentTypeService.selectType("minutes");
695
696                 // Add documents to the first study activity
697                 // Add a converts relations
698                 Map<Integer, org.splat.som.Step> stSteps = _projectElementService
699                                 .getStepsMap(aStudy);
700                 org.splat.som.Step aStep = stSteps.get(1);
701                 Publication pub0inDraft = addDoc(aStudy, aStep, "document0indraft",
702                                 dtype);
703                 pub0inDraft.value().setProgressState(ProgressState.inDRAFT);
704                 Publication pub0inCheck = addDoc(aStudy, aStep, "document0incheck",
705                                 dtype);
706                 pub0inCheck.value().setProgressState(ProgressState.inCHECK);
707                 Publication pub0approved = addDoc(aStudy, aStep, "document0approved",
708                                 dtype);
709                 pub0approved.value().setProgressState(ProgressState.APPROVED);
710                 Publication pub1 = addDoc(aStudy, aStep, "document1", dtype);
711                 String format1 = pub1.value().getFormat();
712                 ht.flush();
713                 ht.update(aStudy);
714                 ht.flush();
715
716                 // Add documents to the first scenario activity
717                 scen = aStudy.getScenariiList().get(0);
718                 Map<Integer, org.splat.som.Step> scSteps = _projectElementService
719                                 .getStepsMap(scen);
720                 aStep = scSteps.get(2);
721                 Publication spub1 = addDoc(scen, aStep, "sdocument1", dtype);
722                 String format2 = spub1.value().getFormat();
723                 ht.flush();
724
725                 // Remember documents ids
726                 Long id0inDraft = pub0inDraft.value().getIndex(), id0inCheck = pub0inCheck
727                                 .value().getIndex(), id0approved = pub0approved.value()
728                                 .getIndex(), id1 = pub1.value().getIndex(), id2 = spub1.value()
729                                 .getIndex();
730
731                 ht.evict(scen);
732                 ht.evict(scen.getOwnerStudy());
733                 ht.clear();
734
735                 Assert.assertTrue(ht.find("from File").size() >= 3,
736                                 "Files were not created in the database.");
737
738                 Date modifTime = Calendar.getInstance().getTime();
739
740                 aStudy = _studyService.selectStudy(studyId);
741                 File newFile = new File(getDownloadPath(goodUser) + "replaced0.ddd");
742                 createFile(newFile.getAbsolutePath());
743
744                 // TEST CALL: Try to replace a file for inDraft document
745                 Publication pub = getPublicationByDocId(aStudy, id0inDraft);
746                 try {
747                         _publicationService.replace(pub, newFile, modifTime);
748                         Assert
749                                         .fail("IncompatibleDataException is expected for a doucment in the status "
750                                                         + pub.getProgressState().name());
751                 } catch (IncompatibleDataException e) {
752                         LOG.debug("Expected exception: ", e);
753                 }
754                 ht.flush();
755                 // TEST CALL: Try to replace a file for inCheck document
756                 pub = getPublicationByDocId(aStudy, id0inCheck);
757                 try {
758                         _publicationService.replace(pub, newFile, modifTime);
759                         Assert
760                                         .fail("IncompatibleDataException is expected for a doucment in the status "
761                                                         + pub.getProgressState().name());
762                 } catch (IncompatibleDataException e) {
763                         LOG.debug("Expected exception: ", e);
764                 }
765                 ht.flush();
766                 // TEST CALL: Try to replace a file for Approved document
767                 pub = getPublicationByDocId(aStudy, id0approved);
768                 try {
769                         _publicationService.replace(pub, newFile, modifTime);
770                         Assert
771                                         .fail("IncompatibleDataException is expected for a doucment in the status "
772                                                         + pub.getProgressState().name());
773                 } catch (IncompatibleDataException e) {
774                         LOG.debug("Expected exception: ", e);
775                 }
776                 ht.flush();
777                 newFile.delete();
778
779                 // TEST CALL: Replace a file in the study step
780                 pub = getPublicationByDocId(aStudy, id1);
781                 newFile = new File(getDownloadPath(goodUser) + "replaced1.ddd");
782                 createFile(newFile.getAbsolutePath());
783                 Assert.assertTrue(_publicationService.replace(pub, newFile, modifTime));
784                 ht.flush();
785
786                 // TEST CALL: Replace a file in the scenario step
787                 scen = aStudy.getScenariiList().get(0);
788                 pub = getPublicationByDocId(scen, id2);
789                 newFile = new File(getDownloadPath(goodUser) + "replaced2.ddd");
790                 createFile(newFile.getAbsolutePath());
791                 Assert.assertTrue(_publicationService.replace(pub, newFile, modifTime));
792                 ht.flush();
793
794                 ht.clear();
795                 // Remove milliseconds because they are lost after saving in the database
796                 modifTime.setTime((modifTime.getTime() / 1000) * 1000);
797
798                 Document doc = ht.get(Document.class, id1);
799                 String txt = readFile(doc.getFile().asFile());
800                 Assert.assertTrue(doc.getFile().getName().contains("_document1"));
801                 Assert.assertEquals(doc.getFile().getFormat(), format1);
802                 Assert.assertTrue(txt.contains("replaced1.ddd"));
803                 Assert.assertEquals(doc.getLastModificationDate(), modifTime);
804
805                 doc = ht.get(Document.class, id2);
806                 txt = readFile(doc.getFile().asFile());
807                 Assert.assertTrue(doc.getFile().getName().contains("_sdocument1"));
808                 Assert.assertEquals(doc.getFile().getFormat(), format2);
809                 Assert.assertTrue(txt.contains("replaced2.ddd"));
810                 Assert.assertEquals(doc.getLastModificationDate(), modifTime);
811
812                 rollbackNestedTransaction();
813                 LOG.debug(">>>>> END testReplace()");
814         }
815
816         /**
817          * Find a document publication in the project element.
818          * 
819          * @param projElem
820          *            the project element to scan
821          * @param docId
822          *            the document id
823          * @return the document publication if found, otherwise return null
824          */
825         private Publication getPublicationByDocId(final ProjectElement projElem,
826                         final Long docId) {
827                 Publication res = null;
828                 for (Publication pub : projElem.getDocums()) {
829                         if (docId.equals(pub.value().getIndex())) {
830                                 res = pub;
831                                 break;
832                         }
833                 }
834                 return res;
835         }
836
837         /**
838          * Get file content as a string.
839          * 
840          * @param f
841          *            the file to read
842          * @return the file content
843          * @throws IOException
844          *             if reading is failed
845          */
846         private String readFile(final File f) throws IOException {
847                 FileInputStream fstream = new FileInputStream(f);
848                 // Get the object of DataInputStream
849                 DataInputStream in = new DataInputStream(fstream);
850                 BufferedReader br = new BufferedReader(new InputStreamReader(in));
851                 StringBuffer res = new StringBuffer();
852                 String str;
853                 // Read File Line By Line
854                 while ((str = br.readLine()) != null) {
855                         res.append(str);
856                 }
857                 // Close the input stream
858                 in.close();
859                 return res.toString();
860         }
861 }