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