1 /*****************************************************************************
5 * Creation date 12 Oct 2012
8 *****************************************************************************/
9 package test.splat.service;
11 import java.io.BufferedReader;
12 import java.io.DataInputStream;
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;
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;
65 import test.splat.common.BaseTest;
66 import test.splat.util.TestEntitiesGenerator;
69 * Test class for PublicationService.
71 * @author <a href="mailto:roman.kozlov@opencascade.com">Roman Kozlov (RKV)</a>
74 public class TestPublicationService extends BaseTest {
77 * Logger for the class.
79 private static final AppLogger LOG = AppLogger
80 .getLogger(TestPublicationService.class);
83 * The StudyDAO. Later injected by Spring.
86 @Qualifier("studyDAO")
87 private transient StudyDAO _studyDAO;
90 * The PublicationService. Later injected by Spring.
93 @Qualifier("publicationService")
94 private transient PublicationService _publicationService;
97 * The ProjectElementService. Later injected by Spring.
100 @Qualifier("projectElementService")
101 private transient ProjectElementService _projectElementService;
104 * The StepService. Later injected by Spring.
107 @Qualifier("stepService")
108 private transient StepService _stepService;
111 * The ProjectSettingsService. Later injected by Spring.
114 @Qualifier("projectSettings")
115 private transient ProjectSettingsService _projectSettings;
118 * The DocumentTypeService. Later injected by Spring.
121 @Qualifier("documentTypeService")
122 private transient DocumentTypeService _documentTypeService;
125 * The StudyService. Later injected by Spring.
128 @Qualifier("studyService")
129 private transient StudyService _studyService;
132 * The RepositoryService. Later injected by Spring.
135 @Qualifier("repositoryService")
136 private transient RepositoryService _repositoryService;
139 * The UserDAO. Later injected by Spring.
142 @Qualifier("userDAO")
143 private transient UserDAO _userDAO;
146 * The Scenario DAO. Later injected by Spring.
149 @Qualifier("scenarioDAO")
150 private transient ScenarioDAO _scenarioDAO;
153 * Create a persistent scenario for tests.
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
167 private Study createStudy() throws InvalidPropertyException,
168 MissedPropertyException, MultiplyDefinedException, IOException,
170 // Create a scenario for tests
171 HibernateTemplate ht = getHibernateTemplate();
173 Database.getInstance().reset();
174 _projectSettings.getAllSteps().clear(); // Clear config to be able to load it again
175 // Load workflow customization
177 _projectSettings.configure("classpath:test/som.xml");
178 } catch (FileNotFoundException e) {
179 Assert.fail("Can't find som.xml: ", e);
181 List<Step> steps = _projectSettings.getAllSteps();
182 Assert.assertTrue(steps.size() > 0, "No steps are created.");
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);
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);
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);
209 // Create documents for each scenario step
210 Document.Properties dprop = new Document.Properties().setAuthor(
211 anAuthor).setDate(new Date());
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;
220 if (step.appliesTo(Study.class)) {
223 projElem = aScenario;
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
235 dprop.setName("document" + stepNum).setType(dtype);
236 if (step.getNumber() > 3) {
237 dprop.setFormat("med");
239 dprop.setFormat("py");
241 Publication pub = createDoc(projElem, aScStep, dprop, "med",
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());
250 usedMap.put(pub.getIndex(), usedPub.getIndex());
254 if (dtypes.size() <= 0) {
255 LOG.debug("No document types are found for scenario step " + i);
259 // Check that the scenario and its documents have been created correctly.
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.");
266 Assert.assertNotNull(ht.find("from Publication where owner="
267 + aScenario.getIndex()), "No publications in the database.");
269 ht.find("from Publication where owner=" + aScenario.getIndex())
270 .size() > 0, "No publications in the database.");
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()
277 Assert.assertEquals(p.getOwner().getIndex(), aScenario.getIndex(),
278 "The publication was not attached to the scenario.");
281 // Remove the scenario from the current hibernate session.
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.");
289 Assert.assertTrue(i > 0,
290 "More then one document must be in the database");
292 // Check created uses relations
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));
308 for (Publication used : aStudy.getDocums()) {
309 found = (used.getIndex() == usedMap.get(usingId));
315 Assert.assertTrue(found,
316 "Uses relation was not created in the database.");
317 foundAny = foundAny || found;
321 Assert.assertTrue(foundAny,
322 "No Uses relation was created in the database.");
324 return aScenario.getOwnerStudy();
328 * Create a document published in the scenario. <BR>
330 * document type - type used on the step <BR>
331 * <source-file>.brep <BR>
332 * <attached-file>.med
335 * the scenario to add the document to
337 * scenario step where the document to be published
339 * document properties
340 * @param attachedFileExt
341 * extension of the secon attached (exported) file
343 * outdated document flag
344 * @return the publication of the created document
345 * @throws IOException
346 * @throws MultiplyDefinedException
347 * @throws InvalidPropertyException
348 * @throws MissedPropertyException
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.");
369 HibernateTemplate ht = getHibernateTemplate();
370 ht.saveOrUpdate(pub);
373 ht.save(pub.value());
375 ht.saveOrUpdate(_publicationService.attach(pub, attachedFileExt));
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>
389 * <B>Outcome results:</B><BR>
392 * <li>The new index must be equal to the incremented old one and saved into the database<BR>
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
413 public void testCreateDoc() throws InvalidPropertyException,
414 MissedPropertyException, MultiplyDefinedException, IOException,
415 SQLException, NotApplicableException, InterruptedException,
417 LOG.debug(">>>>> BEGIN testCreateDoc()");
418 startNestedTransaction();
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.");
428 // Call DAO's get method for an existing id.
430 getHibernateTemplate().evict(aStudy);
431 getHibernateTemplate().clear();
432 Study aStudyFound = _studyDAO.get(id);
433 ht.evict(aStudyFound);
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]);
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());
449 List<DocumentType> dtypes = _documentTypeService.selectTypesOf(step
451 if (dtypes.size() > 0) {
452 DocumentType dtype = dtypes.get(0);
453 int oldInd = ht.get(Study.class, aStudyFound.getIndex())
454 .getLastLocalIndex();
456 // Create a file in the download directory
457 String fname = "filename" + step.getNumber() + ".py";
458 String filePath = getDownloadPath(aStudyFound.getAuthor())
460 LOG.debug(step.getStep().getKey() + ": "
461 + step.getOwner().getClass().getSimpleName()
462 + ": Create test file: " + filePath);
463 FileWriter fw = new FileWriter(filePath);
465 .write("Simulation of filename.py file for creating a new document at "
469 Publication addoc = _publicationService.createDoc(aStudyFound
470 .getIndex(), step, dtype.getIndex(), userId, fname,
471 "tstdoc", ProgressState.inWORK, "", "", new Date(),
477 int ind = ht.get(Study.class, aStudyFound.getIndex())
478 .getLastLocalIndex();
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())
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.");
495 rollbackNestedTransaction();
496 LOG.debug(">>>>> END testCreateDoc()");
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>
508 * <B>Outcome results:</B><BR>
511 * <li>The new ConvertsRelation and the new File object must be created in the database.<BR>
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
532 public void testAttach() throws InvalidPropertyException,
533 MissedPropertyException, MultiplyDefinedException, IOException,
534 SQLException, NotApplicableException, InterruptedException,
536 LOG.debug(">>>>> BEGIN testAttach()");
537 startNestedTransaction();
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.");
547 // Call DAO's get method for an existing id.
549 getHibernateTemplate().evict(aStudy);
550 getHibernateTemplate().clear();
551 Study aStudyFound = _studyDAO.get(id);
553 ht.evict(aStudyFound);
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]);
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());
570 for (Publication pub : step.getAllDocuments()) {
572 ht.evict(step.getOwner());
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();
581 ConvertsRelation rel = _publicationService.attach(pub, "py");
585 Assert.assertNotNull(rel,
586 "Returned ConvertsRelation must not be null.");
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(),
594 "Number of created ConvertsRelations must be 1.");
595 Assert.assertEquals(ht.find("from ConvertsRelation").size(),
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.");
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.");
613 rollbackNestedTransaction();
614 LOG.debug(">>>>> END testAttach()");
618 * Get path to the user's downloads directory. The directory is created if it is not exist yet.
622 * @return absolute path to downloads directory followed by slash
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());
633 return tmpDir.getAbsolutePath() + "/";
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>
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>
650 * <B>Outcome results:</B><BR>
653 * <li>1-3: Exception must be thrown. The document source file content must not be replaced.<BR>
655 * <li>4: The document source file content in the study must be replaced.<BR>
657 * <li>5: The document source file content in the scenario must be replaced.<BR>
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
670 public void testReplace() throws BusinessException, IOException,
672 LOG.debug(">>>>> BEGIN testReplace()");
673 startNestedTransaction();
675 HibernateTemplate ht = getHibernateTemplate();
677 Database.getInstance().reset();
678 _projectSettings.getAllSteps().clear(); // Clear config to be able to load it again
679 _projectSettings.configure("classpath:test/som.xml");
681 User goodUser = TestEntitiesGenerator.getTestUser("GoodUser");
682 _userDAO.create(goodUser);
684 // Create private study
685 Study aStudy = TestEntitiesGenerator.getTestStudy(goodUser);
686 aStudy.setTitle("0.This is private study");
687 Long studyId = _studyDAO.create(aStudy);
689 // Add a scenario to the study
690 Scenario scen = TestEntitiesGenerator.getTestScenario(aStudy);
691 Long scenId = _scenarioDAO.create(scen);
694 DocumentType dtype = _documentTypeService.selectType("minutes");
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",
703 pub0inDraft.value().setProgressState(ProgressState.inDRAFT);
704 Publication pub0inCheck = addDoc(aStudy, aStep, "document0incheck",
706 pub0inCheck.value().setProgressState(ProgressState.inCHECK);
707 Publication pub0approved = addDoc(aStudy, aStep, "document0approved",
709 pub0approved.value().setProgressState(ProgressState.APPROVED);
710 Publication pub1 = addDoc(aStudy, aStep, "document1", dtype);
711 String format1 = pub1.value().getFormat();
716 // Add documents to the first scenario activity
717 scen = aStudy.getScenariiList().get(0);
718 Map<Integer, org.splat.som.Step> scSteps = _projectElementService
720 aStep = scSteps.get(2);
721 Publication spub1 = addDoc(scen, aStep, "sdocument1", dtype);
722 String format2 = spub1.value().getFormat();
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()
732 ht.evict(scen.getOwnerStudy());
735 Assert.assertTrue(ht.find("from File").size() >= 3,
736 "Files were not created in the database.");
738 Date modifTime = Calendar.getInstance().getTime();
740 aStudy = _studyService.selectStudy(studyId);
741 File newFile = new File(getDownloadPath(goodUser) + "replaced0.ddd");
742 createFile(newFile.getAbsolutePath());
744 // TEST CALL: Try to replace a file for inDraft document
745 Publication pub = getPublicationByDocId(aStudy, id0inDraft);
747 _publicationService.replace(pub, newFile, modifTime);
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);
755 // TEST CALL: Try to replace a file for inCheck document
756 pub = getPublicationByDocId(aStudy, id0inCheck);
758 _publicationService.replace(pub, newFile, modifTime);
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);
766 // TEST CALL: Try to replace a file for Approved document
767 pub = getPublicationByDocId(aStudy, id0approved);
769 _publicationService.replace(pub, newFile, modifTime);
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);
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));
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));
795 // Remove milliseconds because they are lost after saving in the database
796 modifTime.setTime((modifTime.getTime() / 1000) * 1000);
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);
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);
812 rollbackNestedTransaction();
813 LOG.debug(">>>>> END testReplace()");
817 * Find a document publication in the project element.
820 * the project element to scan
823 * @return the document publication if found, otherwise return null
825 private Publication getPublicationByDocId(final ProjectElement projElem,
827 Publication res = null;
828 for (Publication pub : projElem.getDocums()) {
829 if (docId.equals(pub.value().getIndex())) {
838 * Get file content as a string.
842 * @return the file content
843 * @throws IOException
844 * if reading is failed
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();
853 // Read File Line By Line
854 while ((str = br.readLine()) != null) {
857 // Close the input stream
859 return res.toString();