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