package org.splat.service;
+import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.ParseException;
final List<Long> docuses) throws MissedPropertyException,
InvalidPropertyException, MultiplyDefinedException, IOException,
NotApplicableException, InterruptedException, ParseException;
-
+
/**
* Create a new version of the document.
*
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.
*
* @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;
}
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;
+ }
}
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;
* 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.
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() + "/";
+ }
}
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;
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
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
.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(
*****************************************************************************/
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;
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;
import org.testng.annotations.Test;
import test.splat.common.BaseTest;
+import test.splat.util.TestEntitiesGenerator;
/**
* Test class for PublicationService.
@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.
*
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();
+ }
}
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;
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.
*
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>
package test.splat.service;
import java.io.FileNotFoundException;
-import java.io.FileWriter;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
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.
*
*****************************************************************************/
package test.splat.service;
-import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
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;
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;
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
* @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;
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.
*
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;
*/
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.
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);
_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();
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;
}
/**
// 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;
/**
* Get the index.
+ *
* @return the index
*/
@Override
public String getIndex() {
return _index;
}
-
+
/**
* Get the publicationService.
*
<result name="version" type="redirectAction">
version-document?index=%{index}&fileName=%{canceledFileName}
</result>
- <result name="attach" type="redirectAction">
- attach-document?index=%{index}&fileName=%{canceledFileName}
- </result>
+ <result name="attach" type="redirectAction">
+ attach-document?index=%{index}&fileName=%{canceledFileName}
+ </result>
+ <result name="replace" type="redirectAction">
+ replace-document?index=%{index}&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">