]> SALOME platform Git repositories - tools/siman.git/commitdiff
Salome HOME
Replace document functionality is implemented.
authorrkv <rkv@opencascade.com>
Wed, 10 Apr 2013 12:45:51 +0000 (12:45 +0000)
committerrkv <rkv@opencascade.com>
Wed, 10 Apr 2013 12:45:51 +0000 (12:45 +0000)
Workspace/Siman-Common/src/org/splat/service/PublicationService.java
Workspace/Siman-Common/src/org/splat/service/PublicationServiceImpl.java
Workspace/Siman-Common/src/test/splat/common/BaseTest.java
Workspace/Siman-Common/src/test/splat/service/TestProjectSettingsService.java
Workspace/Siman-Common/src/test/splat/service/TestPublicationService.java
Workspace/Siman-Common/src/test/splat/service/TestScenarioService.java
Workspace/Siman-Common/src/test/splat/service/TestStepService.java
Workspace/Siman-Common/src/test/splat/service/TestStudyService.java
Workspace/Siman/src/org/splat/simer/EditDocumentAction.java
Workspace/Siman/src/struts.xml

index 6279f2db814907cb550432fd85104bc40c1c376f..0c9d36803262fe461c16e00bbb41c8ef94fc0a11 100644 (file)
@@ -9,6 +9,7 @@
 
 package org.splat.service;
 
+import java.io.File;
 import java.io.FileNotFoundException;
 import java.io.IOException;
 import java.text.ParseException;
@@ -59,7 +60,7 @@ public interface PublicationService {
                        final List<Long> docuses) throws MissedPropertyException,
                        InvalidPropertyException, MultiplyDefinedException, IOException,
                        NotApplicableException, InterruptedException, ParseException;
-       
+
        /**
         * Create a new version of the document.
         * 
@@ -250,6 +251,20 @@ public interface PublicationService {
        void rename(Publication aPublication, String title)
                        throws InvalidPropertyException;
 
+       /**
+        * Replace the document source file.
+        * 
+        * @param pub
+        *            document publication
+        * @param newFile
+        *            the new file
+        * @param modifTime
+        *            modification time
+        * @return true if succeeded otherwise return false
+        */
+       boolean replace(final Publication pub, final File newFile,
+                       final Date modifTime);
+
        /**
         * Create "Converts" relation for the given document publication and format.
         * 
@@ -297,13 +312,16 @@ public interface PublicationService {
         * @see #actualize()
         */
        void outdate(Publication aPublication);
-       
 
        /**
         * Get DocToCompareDTO by publication id.
-        * @param publicationId publication id
+        * 
+        * @param publicationId
+        *            publication id
         * @return DocToCompareDTO
-        * @throws InvalidParameterException if there is no document with such id.
+        * @throws InvalidParameterException
+        *             if there is no document with such id.
         */
-       DocToCompareDTO getDocToCompareDTO(long publicationId) throws InvalidParameterException;
+       DocToCompareDTO getDocToCompareDTO(long publicationId)
+                       throws InvalidParameterException;
 }
index 2c13f06ff1e40e4352604846eddbd1f46f4c8c25..3e0ffac8ca4a213c6841ca7dc5ab5bfb00c155fe 100644 (file)
@@ -975,4 +975,39 @@ public class PublicationServiceImpl implements PublicationService {
        public void setUserService(final UserService userService) {
                _userService = userService;
        }
+
+       /** 
+        * {@inheritDoc}
+        * @see org.splat.service.PublicationService#replace(long, java.io.File)
+        */
+       @Override
+       @Transactional
+       public boolean replace(final Publication pub, final File newFile,
+                       final Date modifTime) {
+               Document doc = getDocumentService().selectDocument(pub.value().getIndex());
+               if (LOG.isInfoEnabled()) {
+                       LOG.info("Moving \"" + newFile.getName() + "\" to \""
+                                       + doc.getSourceFile().asFile().getAbsolutePath()
+                                       + "\".");
+               }
+               // Save a temporary copy of the original file as <old file name>.backup
+               String oldFilePath = doc.getSourceFile().asFile().getAbsolutePath();
+               File oldFile = new File(oldFilePath);
+               File backupFile = new File(oldFilePath + ".backup");
+               oldFile.renameTo(backupFile);
+               boolean res = newFile.renameTo(oldFile);
+               if (res) {
+                       // Delete the temporary copy of the old file 
+                       // if the new one is moved into the repository.
+                       backupFile.delete();
+                       // Update the document modification date.
+                       doc.setLastModificationDate(modifTime);
+                       // Update presentation data
+                       pub.value().setLastModificationDate(modifTime);
+               } else {
+                       // Restore the original file if replacing is failed
+                       backupFile.renameTo(oldFile);
+               }
+               return res;
+       }
 }
index 2282a863d8a9c61488196e06c9f802ef8781f9cc..99ff65a9c24f7c217e048f71d20241c5e18c8e05 100644 (file)
@@ -9,13 +9,25 @@
 
 package test.splat.common;
 
+import java.io.File;
+import java.io.FileWriter;
+import java.io.IOException;
+import java.util.Date;
 import java.util.List;
 import java.util.Map;
 
 import javax.sql.DataSource;
 
 import org.hibernate.SessionFactory;
+import org.splat.dal.bo.som.Document;
+import org.splat.dal.bo.som.DocumentType;
+import org.splat.dal.bo.som.ProjectElement;
+import org.splat.dal.bo.som.Publication;
+import org.splat.exception.BusinessException;
 import org.splat.log.AppLogger;
+import org.splat.service.PublicationService;
+import org.splat.service.StepService;
+import org.splat.service.technical.RepositoryService;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.beans.factory.annotation.Qualifier;
 import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;
@@ -187,6 +199,27 @@ public class BaseTest extends TestListingAndOrder {
         * Used for nested transactions management.
         */
        private transient TransactionStatus _nestedTxStatus;
+
+       /**
+        * The StepService. Later injected by Spring.
+        */
+       @Autowired
+       @Qualifier("stepService")
+       private transient StepService _stepService;
+
+       /**
+        * The PublicationService. Later injected by Spring.
+        */
+       @Autowired
+       @Qualifier("publicationService")
+       private transient PublicationService _publicationService;
+
+       /**
+        * The RepositoryService. Later injected by Spring.
+        */
+       @Autowired
+       @Qualifier("repositoryService")
+       private transient RepositoryService _repositoryService;
        
        /**
         * Use this method to start a new transaction within an existing one. 
@@ -249,4 +282,109 @@ public class BaseTest extends TestListingAndOrder {
                rollbackNestedTransaction();
                startNestedTransaction();
        }
+
+       /**
+        * Create a file.
+        * 
+        * @param fname
+        *            file name
+        * @throws IOException
+        *             if file creation failed
+        */
+       protected void createFile(final String fname) throws IOException {
+               // Create a file in the download directory
+               LOG.debug("Create file: " + fname);
+               String filePath = fname;
+               FileWriter fw = new FileWriter(filePath);
+               fw.write("Simulation of " + fname + " data file at " + new Date());
+               fw.close();
+       }
+
+       /**
+        * Create a new version of the document.
+        * 
+        * @param pub
+        *            the current document publication
+        * @return the new document version publication
+        * @throws IOException
+        *             if versioning is failed
+        * @throws BusinessException
+        *             if versioning is failed
+        */
+       protected Publication version(final Publication pub)
+                       throws BusinessException, IOException {
+               Document.Properties dprop = new Document.Properties();
+               dprop.setDocument(pub.value(), pub.getStep().getStep());
+               dprop.setLocalPath(pub.value().getTitle() + "_v1");
+               Publication newpub = _stepService.versionDocument(pub.getStep(), pub,
+                               dprop);
+               pub.getOwner().getDocums().remove(pub);
+               pub.getStep().getDocuments().remove(pub);
+               pub.getOwner().add(newpub);
+               pub.getStep().getDocuments().add(newpub);
+               String filepath = newpub.getSourceFile().asFile().getAbsolutePath();
+               createFile(filepath);
+               return newpub;
+       }
+
+       /**
+        * Create a document and publish it in the project element.
+        * 
+        * @param aProjElem
+        *            the project element
+        * @param aStep
+        *            the project element step
+        * @param docname
+        *            document name
+        * @param dtype
+        *            document type
+        * @return publication of the created document
+        * @throws BusinessException
+        *             if document creation is failed
+        * @throws IOException
+        *             if file creation is failed
+        */
+       protected Publication addDoc(final ProjectElement aProjElem,
+                       final org.splat.som.Step aStep, final String docname,
+                       final DocumentType dtype) throws BusinessException, IOException {
+               HibernateTemplate ht = getHibernateTemplate();
+               // Add documents to the study activity
+               Document.Properties dprop = new Document.Properties().setAuthor(
+                               aProjElem.getAuthor()).setDate(new Date()).setName(docname)
+                               .setType(dtype).setFormat("py");
+               dprop.setLocalPath(dprop.getName() + "." + dprop.getFormat());
+               dprop.setStep(aStep.getStep());
+               Publication pub = _stepService.createDocument(aStep, dprop);
+               pub.setStep(aStep);
+               aProjElem.add(pub);
+               aStep.getDocuments().add(pub);
+               ht.saveOrUpdate(pub);
+               ht.save(pub.value());
+               // Add a converts relation
+               // Attach a med file
+               ht.saveOrUpdate(_publicationService.attach(pub, "med"));
+               String filepath = pub.getSourceFile().asFile().getAbsolutePath();
+               createFile(filepath);
+               createFile(filepath.substring(0, filepath.lastIndexOf(".")) + ".med");
+               return pub;
+       }
+
+       /**
+        * Get path to the user's downloads directory. The directory is created if it is not exist yet.
+        * 
+        * @param userId
+        *            user id
+        * @return absolute path to downloads directory followed by slash
+        */
+       protected String getDownloadPath(final long userId) {
+               // Prepare download directory
+               File tmpDir = _repositoryService.getDownloadDirectory(userId);
+               if (!tmpDir.exists()) {
+                       Assert.assertTrue(tmpDir.mkdir(),
+                                       "Can't create temporary directory: "
+                                                       + tmpDir.getAbsolutePath());
+               }
+       
+               return tmpDir.getAbsolutePath() + "/";
+       }
 }
index 74ae7836aaff4282ffdecd4cd6d143a8dcbbc107..486902509acf69ad7162dbff1dc9df90d1390bd0 100644 (file)
@@ -22,8 +22,8 @@ import org.splat.service.DocumentTypeService;
 import org.splat.service.KnowledgeElementTypeService;
 import org.splat.service.SimulationContextService;
 import org.splat.service.technical.ProjectSettingsService;
-import org.splat.service.technical.ProjectSettingsService.Step;
 import org.splat.service.technical.StepsConfigService;
+import org.splat.service.technical.ProjectSettingsService.Step;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.beans.factory.annotation.Qualifier;
 import org.springframework.dao.DuplicateKeyException;
@@ -129,7 +129,7 @@ public class TestProjectSettingsService extends BaseTest {
                Assert.assertTrue(steps.size() > 0, "No steps are created.");
                Assert.assertTrue(_projectSettings.doImport("geometry", "brep"));
                Assert.assertTrue(_projectSettings.doImport("model", "med"));
-               Assert.assertTrue(_projectSettings.doImport("loads", "c3m"));
+               Assert.assertTrue(_projectSettings.doImport("loads", "model"));
                Assert.assertTrue(_projectSettings.doImport("results", "med"));
 
                // ////// Load workflow customization with empty mappings
@@ -143,7 +143,7 @@ public class TestProjectSettingsService extends BaseTest {
                Assert.assertTrue(steps.size() > 0, "No steps are created.");
                Assert.assertFalse(_projectSettings.doImport("geometry", "brep"));
                Assert.assertFalse(_projectSettings.doImport("model", "med"));
-               Assert.assertFalse(_projectSettings.doImport("loads", "c3m"));
+               Assert.assertFalse(_projectSettings.doImport("loads", "model"));
                Assert.assertFalse(_projectSettings.doImport("results", "med"));
 
                // ////// Load workflow customization from not existing file
@@ -378,6 +378,23 @@ public class TestProjectSettingsService extends BaseTest {
                                                        .getDefaultDocumentType(step, "xml").getName(),
                                                        "memorandum");
                                        break;
+                               case 5:
+                                       Assert.assertEquals(defTypes.size(), 2);
+                                       Assert.assertNull(_projectSettings.getDefaultDocumentType(
+                                                       step, "pdf"));
+                                       Assert.assertNull(_projectSettings
+                                                       .getDefaultDocumentType(step, "py"));
+                                       Assert.assertNotNull(_projectSettings
+                                                       .getDefaultDocumentType(step, "med"));
+                                       Assert.assertEquals(_projectSettings
+                                                       .getDefaultDocumentType(step, "med").getName(),
+                                                       "model");
+                                       Assert.assertNotNull(_projectSettings
+                                                       .getDefaultDocumentType(step, "model"));
+                                       Assert.assertEquals(_projectSettings
+                                                       .getDefaultDocumentType(step, "model").getName(),
+                                                       "loads");
+                                       break;
                                case 6:
                                        Assert.assertEquals(defTypes.size(), 2);
                                        Assert.assertNull(_projectSettings.getDefaultDocumentType(
index 6fb04e4fd28542b0074f6e46095052f16f26321c..ccd85661676a6577f13b3bf9c498cb3e0c1e428b 100644 (file)
@@ -8,10 +8,14 @@
  *****************************************************************************/
 package test.splat.service;
 
+import java.io.BufferedReader;
+import java.io.DataInputStream;
 import java.io.File;
+import java.io.FileInputStream;
 import java.io.FileNotFoundException;
 import java.io.FileWriter;
 import java.io.IOException;
+import java.io.InputStreamReader;
 import java.sql.SQLException;
 import java.text.DecimalFormat;
 import java.text.ParseException;
@@ -32,8 +36,11 @@ import org.splat.dal.bo.som.Publication;
 import org.splat.dal.bo.som.Scenario;
 import org.splat.dal.bo.som.Study;
 import org.splat.dal.bo.som.Document.Properties;
+import org.splat.dal.dao.kernel.UserDAO;
 import org.splat.dal.dao.som.Database;
+import org.splat.dal.dao.som.ScenarioDAO;
 import org.splat.dal.dao.som.StudyDAO;
+import org.splat.exception.BusinessException;
 import org.splat.kernel.InvalidPropertyException;
 import org.splat.kernel.MissedPropertyException;
 import org.splat.kernel.MultiplyDefinedException;
@@ -54,6 +61,7 @@ import org.testng.Assert;
 import org.testng.annotations.Test;
 
 import test.splat.common.BaseTest;
+import test.splat.util.TestEntitiesGenerator;
 
 /**
  * Test class for PublicationService.
@@ -125,6 +133,20 @@ public class TestPublicationService extends BaseTest {
        @Qualifier("repositoryService")
        private transient RepositoryService _repositoryService;
 
+       /**
+        * The UserDAO. Later injected by Spring.
+        */
+       @Autowired
+       @Qualifier("userDAO")
+       private transient UserDAO _userDAO;
+
+       /**
+        * The Scenario DAO. Later injected by Spring.
+        */
+       @Autowired
+       @Qualifier("scenarioDAO")
+       private transient ScenarioDAO _scenarioDAO;
+
        /**
         * Create a persistent scenario for tests.
         * 
@@ -609,4 +631,149 @@ public class TestPublicationService extends BaseTest {
                return tmpDir.getAbsolutePath() + "/";
        }
 
+       /**
+        * Test testReplace method for a published document.<BR>
+        * <B>Description :</B> <BR>
+        * <i>Create a study and a scenario with documents and try to replace source files.<BR>
+        * </i><BR>
+        * <B>Action : </B><BR>
+        * <i>1. call the method for a document published in the study step.</i><BR>
+        * <i>2. call the method for a document published in the scenario step.</i><BR>
+        * <B>Test data : </B><BR>
+        * <i>no input parameters</i><BR>
+        * <i>no input parameters</i><BR>
+        * 
+        * <B>Outcome results:</B><BR>
+        * <i>
+        * <ul>
+        * <li>The document source file content in the study must be replaced.<BR>
+        * </li>
+        * <li>The document source file content in the scenario must be replaced.<BR>
+        * </li>
+        * </ul>
+        * </i>
+        * 
+        * @throws BusinessException
+        *             if test data creation is failed
+        * @throws IOException
+        *             if application configuration loading or test data creation is failed
+        * @throws SQLException
+        *             if application configuration loading or test data creation is failed
+        */
+       @Test
+       public void testReplace() throws BusinessException, IOException,
+                       SQLException {
+               LOG.debug(">>>>> BEGIN testReplace()");
+               startNestedTransaction();
+
+               HibernateTemplate ht = getHibernateTemplate();
+
+               Database.getInstance().reset();
+               _projectSettings.getAllSteps().clear(); // Clear config to be able to load it again
+               _projectSettings.configure("classpath:test/som.xml");
+
+               User goodUser = TestEntitiesGenerator.getTestUser("GoodUser");
+               _userDAO.create(goodUser);
+
+               // Create private study
+               Study aStudy = TestEntitiesGenerator.getTestStudy(goodUser);
+               aStudy.setTitle("0.This is private study");
+               Long studyId = _studyDAO.create(aStudy);
+
+               // Add a scenario to the study
+               Scenario scen = TestEntitiesGenerator.getTestScenario(aStudy);
+               Long scenId = _scenarioDAO.create(scen);
+               ht.flush();
+
+               DocumentType dtype = _documentTypeService.selectType("minutes");
+
+               // Add documents to the first study activity
+               // Add a converts relations
+               Map<Integer, org.splat.som.Step> stSteps = _projectElementService
+                               .getStepsMap(aStudy);
+               org.splat.som.Step aStep = stSteps.get(1);
+               Publication pub1 = addDoc(aStudy, aStep, "document1", dtype);
+               String format1 = pub1.value().getFormat();
+               ht.flush();
+               ht.update(aStudy);
+               ht.flush();
+
+               // Add documents to the first scenario activity
+               scen = aStudy.getScenariiList().get(0);
+               Map<Integer, org.splat.som.Step> scSteps = _projectElementService
+                               .getStepsMap(scen);
+               aStep = scSteps.get(2);
+               Publication spub1 = addDoc(scen, aStep, "sdocument1", dtype);
+               String format2 = spub1.value().getFormat();
+               ht.flush();
+
+               Long id1 = pub1.value().getIndex(), id2 = spub1.value().getIndex();
+
+               ht.evict(scen);
+               ht.evict(scen.getOwnerStudy());
+               ht.clear();
+
+               Assert.assertTrue(ht.find("from File").size() >= 2,
+                               "Files were not created in the database.");
+
+               Date modifTime = new Date();
+
+               // TEST CALL: Replace a file in the study step
+               aStudy = _studyService.selectStudy(studyId);
+               Publication pub = aStudy.getDocums().toArray(new Publication[] {})[0];
+               File newFile = new File(getDownloadPath(goodUser) + "replaced1.ddd");
+               createFile(newFile.getAbsolutePath());
+               Assert.assertTrue(_publicationService.replace(pub, newFile, modifTime));
+               ht.flush();
+
+               // TEST CALL: Replace a file in the scenario step
+               scen = aStudy.getScenariiList().get(0);
+               pub = scen.getDocums().toArray(new Publication[] {})[0];
+               newFile = new File(getDownloadPath(goodUser) + "replaced2.ddd");
+               createFile(newFile.getAbsolutePath());
+               Assert.assertTrue(_publicationService.replace(pub, newFile, modifTime));
+               ht.flush();
+
+               ht.clear();
+
+               Document doc = ht.get(Document.class, id1);
+               String txt = readFile(doc.getFile().asFile());
+               Assert.assertTrue(doc.getFile().getName().contains("_document1"));
+               Assert.assertEquals(doc.getFile().getFormat(), format1);
+               Assert.assertTrue(txt.contains("replaced1.ddd"));
+
+               doc = ht.get(Document.class, id2);
+               txt = readFile(doc.getFile().asFile());
+               Assert.assertTrue(doc.getFile().getName().contains("_sdocument1"));
+               Assert.assertEquals(doc.getFile().getFormat(), format1);
+               Assert.assertTrue(txt.contains("replaced2.ddd"));
+               
+               rollbackNestedTransaction();
+               LOG.debug(">>>>> END testReplace()");
+       }
+
+       /**
+        * Get file content as a string.
+        * 
+        * @param f
+        *            the file to read
+        * @return the file content
+        * @throws IOException
+        *             if reading is failed
+        */
+       private String readFile(final File f) throws IOException {
+               FileInputStream fstream = new FileInputStream(f);
+               // Get the object of DataInputStream
+               DataInputStream in = new DataInputStream(fstream);
+               BufferedReader br = new BufferedReader(new InputStreamReader(in));
+               StringBuffer res = new StringBuffer();
+               String str;
+               // Read File Line By Line
+               while ((str = br.readLine()) != null) {
+                       res.append(str);
+               }
+               // Close the input stream
+               in.close();
+               return res.toString();
+       }
 }
index 2cf593124dadde1c7112ef80730f9ce792114d97..5cf66d462b10e284686f611aa3590759aac6e6d8 100644 (file)
@@ -27,7 +27,6 @@ import org.splat.dal.bo.som.ConvertsRelation;
 import org.splat.dal.bo.som.Document;
 import org.splat.dal.bo.som.DocumentType;
 import org.splat.dal.bo.som.KnowledgeElementType;
-import org.splat.dal.bo.som.ProjectElement;
 import org.splat.dal.bo.som.Publication;
 import org.splat.dal.bo.som.Scenario;
 import org.splat.dal.bo.som.SimulationContext;
@@ -825,42 +824,6 @@ public class TestScenarioService extends BaseTest {
                return new FileDTO(filePath);
        }
 
-       /**
-        * Create a file.
-        * 
-        * @param fname
-        *            file name
-        * @throws IOException
-        *             if file creation failed
-        */
-       private void createFile(final String fname) throws IOException {
-               // Create a file in the download directory
-               LOG.debug("Create file: " + fname);
-               String filePath = fname;
-               FileWriter fw = new FileWriter(filePath);
-               fw.write("Simulation of " + fname + " data file at " + new Date());
-               fw.close();
-       }
-
-       /**
-        * Get path to the user's downloads directory. The directory is created if it is not exist yet.
-        * 
-        * @param userId
-        *            user id
-        * @return absolute path to downloads directory followed by slash
-        */
-       private String getDownloadPath(final long userId) {
-               // Prepare download directory
-               File tmpDir = _repositoryService.getDownloadDirectory(userId);
-               if (!tmpDir.exists()) {
-                       Assert.assertTrue(tmpDir.mkdir(),
-                                       "Can't create temporary directory: "
-                                                       + tmpDir.getAbsolutePath());
-               }
-
-               return tmpDir.getAbsolutePath() + "/";
-       }
-
        /**
         * Create a persistent scenario for tests.
         * 
@@ -1496,75 +1459,6 @@ public class TestScenarioService extends BaseTest {
                LOG.debug(">>>>> END testCopyStudyContent()");
        }
 
-       /**
-        * Create a document and publish it in the project element.
-        * 
-        * @param aProjElem
-        *            the project element
-        * @param aStep
-        *            the project element step
-        * @param docname
-        *            document name
-        * @param dtype
-        *            document type
-        * @return publication of the created document
-        * @throws BusinessException
-        *             if document creation is failed
-        * @throws IOException
-        *             if file creation is failed
-        */
-       private Publication addDoc(final ProjectElement aProjElem,
-                       final org.splat.som.Step aStep, final String docname,
-                       final DocumentType dtype) throws BusinessException, IOException {
-               HibernateTemplate ht = getHibernateTemplate();
-               // Add documents to the study activity
-               Document.Properties dprop = new Document.Properties().setAuthor(
-                               aProjElem.getAuthor()).setDate(new Date()).setName(docname)
-                               .setType(dtype).setFormat("py");
-               dprop.setLocalPath(dprop.getName() + "." + dprop.getFormat());
-               dprop.setStep(aStep.getStep());
-               Publication pub = _stepService.createDocument(aStep, dprop);
-               pub.setStep(aStep);
-               aProjElem.add(pub);
-               aStep.getDocuments().add(pub);
-               ht.saveOrUpdate(pub);
-               ht.save(pub.value());
-               // Add a converts relation
-               // Attach a med file
-               ht.saveOrUpdate(_publicationService.attach(pub, "med"));
-               String filepath = pub.getSourceFile().asFile().getAbsolutePath();
-               createFile(filepath);
-               createFile(filepath.substring(0, filepath.lastIndexOf(".")) + ".med");
-               return pub;
-       }
-
-       /**
-        * Create a new version of the document.
-        * 
-        * @param pub
-        *            the current document publication
-        * @return the new document version publication
-        * @throws IOException
-        *             if versioning is failed
-        * @throws BusinessException
-        *             if versioning is failed
-        */
-       private Publication version(final Publication pub)
-                       throws BusinessException, IOException {
-               Document.Properties dprop = new Document.Properties();
-               dprop.setDocument(pub.value(), pub.getStep().getStep());
-               dprop.setLocalPath(pub.value().getTitle() + "_v1");
-               Publication newpub = _stepService.versionDocument(pub.getStep(), pub,
-                               dprop);
-               pub.getOwner().getDocums().remove(pub);
-               pub.getStep().getDocuments().remove(pub);
-               pub.getOwner().add(newpub);
-               pub.getStep().getDocuments().add(newpub);
-               String filepath = newpub.getSourceFile().asFile().getAbsolutePath();
-               createFile(filepath);
-               return newpub;
-       }
-
        /**
         * Test assigning a simulation context to a study.<BR>
         * <B>Description :</B> <BR>
index a50c23bad9a4669fedccf45e2df9e62b8439e0c1..0908b242b85989fc8e37d9687cefa8f135f8166b 100644 (file)
@@ -9,7 +9,6 @@
 package test.splat.service;
 
 import java.io.FileNotFoundException;
-import java.io.FileWriter;
 import java.io.IOException;
 import java.sql.SQLException;
 import java.util.ArrayList;
@@ -594,92 +593,6 @@ public class TestStepService extends BaseTest {
                LOG.debug(">>>>> END testRemoveDocumentVersion()");
        }
 
-       /**
-        * Create a document and publish it in the project element.
-        * 
-        * @param aProjElem
-        *            the project element
-        * @param aStep
-        *            the project element step
-        * @param docname
-        *            document name
-        * @param dtype
-        *            document type
-        * @return publication of the created document
-        * @throws BusinessException
-        *             if document creation is failed
-        * @throws IOException
-        *             if file creation is failed
-        */
-       private Publication addDoc(final ProjectElement aProjElem,
-                       final org.splat.som.Step aStep, final String docname,
-                       final DocumentType dtype) throws BusinessException, IOException {
-               HibernateTemplate ht = getHibernateTemplate();
-               // Add documents to the study activity
-               Document.Properties dprop = new Document.Properties().setAuthor(
-                               aProjElem.getAuthor()).setDate(new Date()).setName(docname)
-                               .setType(dtype).setFormat("py");
-               dprop.setLocalPath(dprop.getName() + "." + dprop.getFormat());
-               dprop.setStep(aStep.getStep());
-               Publication pub = _stepService.createDocument(aStep, dprop);
-               pub.setStep(aStep);
-               aProjElem.add(pub);
-               aStep.getDocuments().add(pub);
-               ht.saveOrUpdate(pub);
-               ht.save(pub.value());
-               // Add a converts relation
-               // Attach a med file
-               ht.saveOrUpdate(_publicationService.attach(pub, "med"));
-               String filepath = pub.getSourceFile().asFile().getAbsolutePath();
-               createFile(filepath);
-               createFile(filepath.substring(0, filepath.lastIndexOf(".")) + ".med");
-               return pub;
-       }
-
-       /**
-        * Create a file.
-        * 
-        * @param fname
-        *            file name
-        * @throws IOException
-        *             if file creation failed
-        */
-       private void createFile(final String fname) throws IOException {
-               // Create a file in the download directory
-               LOG.debug("Create file: " + fname);
-               String filePath = fname;
-               FileWriter fw = new FileWriter(filePath);
-               fw.write("Simulation of " + fname + " data file at " + new Date());
-               fw.close();
-       }
-
-       /**
-        * Create a new version of the document.
-        * 
-        * @param pub
-        *            the current document publication
-        * @return the new document version publication
-        * @throws IOException
-        *             if versioning is failed
-        * @throws BusinessException
-        *             if versioning is failed
-        */
-       private Publication version(final Publication pub)
-                       throws BusinessException, IOException {
-               Document.Properties dprop = new Document.Properties();
-               dprop.setDocument(pub.value(), pub.getStep().getStep());
-               dprop.setLocalPath(pub.value().getTitle() + "_v1");
-               Publication newpub = _stepService.versionDocument(pub.getStep(), pub,
-                               dprop);
-               pub.getOwner().getDocums().remove(pub);
-               pub.getStep().getDocuments().remove(pub);
-               pub.getOwner().add(newpub);
-               pub.getStep().getDocuments().add(newpub);
-               String filepath = newpub.getSourceFile().asFile().getAbsolutePath();
-               createFile(filepath);
-               return newpub;
-       }
-
        /**
         * Create a persistent scenario for tests.
         * 
index 7cfb8aaf232a79e4c7e604deb64cfdf3b4c6fa84..5b68c34fdb2f1c05942f48a234ea3a096855220e 100644 (file)
@@ -8,7 +8,6 @@
  *****************************************************************************/
 package test.splat.service;
 
-import java.io.File;
 import java.io.FileNotFoundException;
 import java.io.FileWriter;
 import java.io.IOException;
@@ -18,7 +17,6 @@ import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
 
-import org.splat.dal.bo.som.ReaderRelation;
 import org.splat.dal.bo.kernel.Relation;
 import org.splat.dal.bo.kernel.User;
 import org.splat.dal.bo.som.ContributorRelation;
@@ -30,6 +28,7 @@ import org.splat.dal.bo.som.KnowledgeElementType;
 import org.splat.dal.bo.som.ProgressState;
 import org.splat.dal.bo.som.ProjectElement;
 import org.splat.dal.bo.som.Publication;
+import org.splat.dal.bo.som.ReaderRelation;
 import org.splat.dal.bo.som.Scenario;
 import org.splat.dal.bo.som.SimulationContext;
 import org.splat.dal.bo.som.Study;
@@ -891,34 +890,10 @@ public class TestStudyService extends BaseTest {
                LOG.debug(">>>>> END testRemoveStudy()");
        }
 
-       /**
-        * Create a new version of the document.
-        * 
-        * @param pub
-        *            the current document publication
-        * @return the new document version publication
-        * @throws IOException
-        *             if versioning is failed
-        * @throws BusinessException
-        *             if versioning is failed
-        */
-       private Publication version(final Publication pub)
-                       throws BusinessException, IOException {
-               Document.Properties dprop = new Document.Properties();
-               dprop.setDocument(pub.value(), pub.getStep().getStep());
-               Publication newpub = _stepService.versionDocument(pub.getStep(), pub,
-                               dprop);
-               pub.getOwner().getDocums().remove(pub);
-               pub.getStep().getDocuments().remove(pub);
-               pub.getOwner().add(newpub);
-               pub.getStep().getDocuments().add(newpub);
-               return newpub;
-       }
-
        /**
         * Create a document and publish it in the project element.
         * 
-        * @param aStudy
+        * @param aProjElem
         *            the project element
         * @param stStep
         * @param docname
@@ -931,29 +906,29 @@ public class TestStudyService extends BaseTest {
         * @throws IOException
         *             if file creation is failed
         */
-       private Publication addDoc(final ProjectElement aStudy,
+       private Publication addDoc(final ProjectElement aProjElem,
                        final String docname, final DocumentType dtype)
                        throws BusinessException, IOException {
                HibernateTemplate ht = getHibernateTemplate();
                // Add documents to the first study activity
-               org.splat.som.Step aStep = _projectElementService.getFirstStep(aStudy);
+               org.splat.som.Step aStep = _projectElementService.getFirstStep(aProjElem);
                Document.Properties dprop = new Document.Properties().setAuthor(
-                               aStudy.getAuthor()).setDate(new Date()).setName(docname)
+                               aProjElem.getAuthor()).setDate(new Date()).setName(docname)
                                .setType(dtype).setFormat("py");
                dprop.setLocalPath(dprop.getName() + "." + dprop.getFormat());
                dprop.setStep(aStep.getStep());
                Publication pub = _stepService.createDocument(aStep, dprop);
                pub.setStep(aStep);
-               aStudy.add(pub);
+               aProjElem.add(pub);
                aStep.getDocuments().add(pub);
                ht.saveOrUpdate(pub);
                ht.save(pub.value());
                // Add a converts relation
                // Attach a med file
                ht.saveOrUpdate(_publicationService.attach(pub, "med"));
-               createDownloadedFile(aStudy.getAuthor().getIndex(), dprop
+               createDownloadedFile(aProjElem.getAuthor().getIndex(), dprop
                                .getLocalPath());
-               createDownloadedFile(aStudy.getAuthor().getIndex(), dprop
+               createDownloadedFile(aProjElem.getAuthor().getIndex(), dprop
                                .getLocalPath().substring(0,
                                                dprop.getLocalPath().lastIndexOf(".") - 1), "med");
                return pub;
@@ -978,25 +953,6 @@ public class TestStudyService extends BaseTest {
                return createDownloadedFile(userId, name + "." + format);
        }
 
-       /**
-        * Get path to the user's downloads directory. The directory is created if it is not exist yet.
-        * 
-        * @param userId
-        *            user id
-        * @return absolute path to downloads directory followed by slash
-        */
-       private String getDownloadPath(final long userId) {
-               // Prepare download directory
-               File tmpDir = _repositoryService.getDownloadDirectory(userId);
-               if (!tmpDir.exists()) {
-                       Assert.assertTrue(tmpDir.mkdir(),
-                                       "Can't create temporary directory: "
-                                                       + tmpDir.getAbsolutePath());
-               }
-
-               return tmpDir.getAbsolutePath() + "/";
-       }
-
        /**
         * Create a file in the user's repository downloads directory.
         * 
index d6727231d824d2b6a61fe991ce22ceb9ee7875e1..66689767a7936babbcbe23fb5c0edbc7c17fa88e 100644 (file)
@@ -2,6 +2,7 @@ package org.splat.simer;
 
 import java.io.File;
 import java.util.Calendar;
+import java.util.Date;
 
 import org.splat.dal.bo.kernel.User;
 import org.splat.dal.bo.som.ConvertsRelation;
@@ -23,8 +24,17 @@ public class EditDocumentAction extends DisplayStudyStepAction {
         */
        private static final long serialVersionUID = 4573036736137033679L;
 
+       /**
+        * The selected document id.
+        */
        private transient String _index = null;
+       /**
+        * Document title.
+        */
        private transient String _title = null;
+       /**
+        * Uploaded filename.
+        */
        private transient String _filename = null;
        /**
         * Injected publication service.
@@ -61,16 +71,20 @@ public class EditDocumentAction extends DisplayStudyStepAction {
                return SUCCESS;
        }
 
+       /**
+        * Perform the selected operation on the document.
+        * 
+        * @return SUCCESS if succeeded, INPUT if input data are invalid, ERROR if failed
+        */
        public String doSetDocument() {
-
                setMenu();
-
+               String res = ERROR;
                try {
                        _openStudy = getOpenStudy();
 
                        Execute todo = Execute.valueOf(_action);
                        Step step = _openStudy.getSelectedStep();
-                       Publication doc = step.getDocument(Integer.valueOf(_index));
+                       Publication doc = step.getDocument(Long.valueOf(_index));
 
                        if (todo == Execute.renameDocument) {
                                getPublicationService().rename(doc, _title);
@@ -99,19 +113,23 @@ public class EditDocumentAction extends DisplayStudyStepAction {
                                _openStudy.update(doc);
                                _openStudy.getMenu().refreshSelectedItem(); // Updates the menu icon, in case of other documents in approved state
                        }
-                       return SUCCESS;
+                       res = SUCCESS;
                } catch (RuntimeException saverror) {
                        LOG.error("Reason:", saverror);
-                       return ERROR;
                } catch (InvalidPropertyException error) {
-                       return INPUT;
+                       res = INPUT;
                }
+               return res;
        }
 
+       /**
+        * Attach an uploaded result file to the selected document.
+        * 
+        * @return SUCCESS if succeeded, otherwise return ERROR
+        */
        public String doAttach() {
-
                setMenu();
-
+               String res = ERROR;
                try {
                        // Getting user inputs
                        _openStudy = getOpenStudy();
@@ -121,22 +139,52 @@ public class EditDocumentAction extends DisplayStudyStepAction {
                        File upfile = new File(updir.getPath() + "/" + _filename);
                        String[] parse = _filename.split("\\x2E");
 
-                       Publication edited = step.getDocument(Integer.valueOf(_index));
+                       Publication edited = step.getDocument(Long.valueOf(_index));
                        ConvertsRelation export = getPublicationService().attach(edited,
                                        parse[parse.length - 1]);
 
                        if (LOG.isInfoEnabled()) {
                                LOG.info("Moving \"" + upfile.getName() + "\" to \""
-                                               + updir.getPath() + "\".");
+                                               + export.getTo().asFile().getAbsolutePath() + "\".");
                        }
                        upfile.renameTo(export.getTo().asFile());
 
                        _openStudy.update(edited);
-                       return SUCCESS;
+                       res = SUCCESS;
                } catch (Exception error) {
                        LOG.error("Reason:", error);
-                       return ERROR;
                }
+               return res;
+       }
+
+       /**
+        * Replace the selected document source file by the uploaded file.
+        * 
+        * @return SUCCESS if succeeded, otherwise return ERROR
+        */
+       public String doReplace() {
+               setMenu();
+               String res = ERROR;
+               try {
+                       // Getting user inputs
+                       User user = getConnectedUser();
+                       File updir = getRepositoryService().getDownloadDirectory(user);
+                       File upfile = new File(updir.getPath() + "/" + _filename);
+
+                       _openStudy = getOpenStudy();
+                       Step step = _openStudy.getSelectedStep();
+                       Publication edited = step.getDocument(Long.valueOf(_index));
+                       Date modifTime = Calendar.getInstance().getTime();
+                       
+                       // Replace the document source file
+                       getPublicationService().replace(edited, upfile, modifTime);
+                       
+                       _openStudy.update(edited);
+                       res = SUCCESS;
+               } catch (Exception error) {
+                       LOG.error("Reason:", error);
+               }
+               return res;
        }
 
        /**
@@ -174,14 +222,31 @@ public class EditDocumentAction extends DisplayStudyStepAction {
        // Getters and setters
        // ==============================================================================================================================
 
+       /**
+        * Set the document title.
+        * 
+        * @param title
+        *            the document title to set
+        */
        public void setDocumentTitle(final String title) {
                this._title = title;
        }
 
+       /**
+        * Set the uploaded file name.
+        * 
+        * @param filename
+        *            the file name to set
+        */
        public void setFileName(final String filename) {
                this._filename = filename;
        }
 
+       /**
+        * {@inheritDoc}
+        * 
+        * @see org.splat.simer.AbstractDisplayAction#setIndex(java.lang.String)
+        */
        @Override
        public void setIndex(final String index) {
                this._index = index;
@@ -189,13 +254,14 @@ public class EditDocumentAction extends DisplayStudyStepAction {
 
        /**
         * Get the index.
+        * 
         * @return the index
         */
        @Override
        public String getIndex() {
                return _index;
        }
-       
+
        /**
         * Get the publicationService.
         * 
index 8d6c00dd151daa5ebe72b6ba8ee10d9e8ef73ba8..12a20f32886521e2e478081675805245df5ea651 100644 (file)
                        <result name="version" type="redirectAction">
                                version-document?index=%{index}&amp;fileName=%{canceledFileName}
                        </result>
-                       <result name="attach" type="redirectAction">
-                               attach-document?index=%{index}&amp;fileName=%{canceledFileName}
-                       </result>
+            <result name="attach" type="redirectAction">
+                attach-document?index=%{index}&amp;fileName=%{canceledFileName}
+            </result>
+            <result name="replace" type="redirectAction">
+                replace-document?index=%{index}&amp;fileName=%{canceledFileName}
+            </result>
                        <result name="outofmemory" type="tiles">
                                page.error.study
                        </result>
                        </result>
                        <result name="error" type="tiles">page.importerror</result>
                </action>
-               <action name="attach-document" class="editDocumentAction"
-                       method="attach">
-                       <result name="success" type="tiles">
-                               page.displaystudy
-                       </result>
-               </action>
+        <action name="attach-document" class="editDocumentAction"
+            method="attach">
+            <result name="success" type="tiles">
+                page.displaystudy
+            </result>
+        </action>
+        <action name="replace-document" class="editDocumentAction"
+            method="replace">
+            <result name="success" type="tiles">
+                page.displaystudy
+            </result>
+        </action>
                <action name="edit-document" class="editDocumentAction"
                        method="initialize">
                        <result name="success" type="tiles">