Fix for attaching a file to a document: the file and ConvertsRelation was not created.
Fix for removing of a document from scenario: new attached file and ConvertsRelation are replicated and not deleted.
}
}
if (res != null) {
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("Contains: "
+ + this.getAllRelations().contains(res));
+ LOG.debug("Nb relations of this before: "
+ + this.getAllRelations().size());
+ }
+ res.owner = null;
this.getAllRelations().remove(res);
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("Nb relations of this after: "
+ + this.getAllRelations().size());
+ }
if (res.isBidirectional()) {
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("Nb relations of reverse before: "
+ + ((Entity)res.getTo()).getAllRelations().size());
+ }
((Entity)res.getTo()).getAllRelations().remove(res.getReverse());
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("Nb relations of reverse after: "
+ + ((Entity)res.getTo()).getAllRelations().size());
+ }
}
}
return res;
--- /dev/null
+/*****************************************************************************
+ * Company OPEN CASCADE
+ * Application SIMAN
+ * File $Id$
+ * Creation date 27.12.2012
+ * @author $Author$
+ * @version $Revision$
+ * @copyright OPEN CASCADE 2012
+ *****************************************************************************/
+
+package org.splat.dal.bo.kernel;
+
+import java.util.UUID;
+
+/**
+ * ID Generator. It is supposed to use UUID for identifying persistent objects<BR>
+ * in the same way before and after saving in the database, i.e. before and<BR>
+ * after persistent id generation. The object UID is used for identification in <BR>
+ * equals() and in hashCode().
+ *
+ * @author <a href="mailto:roman.kozlov@opencascade.com">Roman Kozlov (RKV)</a>
+ */
+public class IdGenerator {
+ public static String createId() {
+ UUID uuid = java.util.UUID.randomUUID();
+ return uuid.toString();
+ }
+}
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
<!--
- - Mapping of the primary key common to all Persistent objects.
- -
- -
- - @author Daniel Brunier-Coulin
- - @copyright OPEN CASCADE 2012
- -->
+ - Mapping of the primary key common to all Persistent objects.
+ -
+ -
+ - @author Daniel Brunier-Coulin
+ - @copyright OPEN CASCADE 2012
+-->
<hibernate-mapping>
- <class name="org.splat.dal.bo.kernel.Persistent" abstract="true">
- <id name="rid" column="rid" access="field" type="long">
- <generator class="org.hibernate.id.enhanced.SequenceStyleGenerator">
- <param name="sequence_name">persistent_id</param>
- <param name="initial_value">1000</param>
- </generator>
- </id>
-<!-- <set name="references" inverse="true" lazy="false"
- cascade="all-delete-orphan" access="field">
- <key column="refer" on-delete="cascade"/>
- <one-to-many class="org.splat.dal.bo.kernel.Relation" />
- </set> -->
- </class>
+ <class name="org.splat.dal.bo.kernel.Persistent" abstract="true">
+ <id name="rid" column="rid" access="field" type="long">
+ <generator
+ class="org.hibernate.id.enhanced.SequenceStyleGenerator">
+ <param name="sequence_name">persistent_id</param>
+ <param name="initial_value">1000</param>
+ </generator>
+ </id>
+ <property name="uid" access="property" type="string" length="36"
+ not-null="true" />
+ <!-- <set name="references" inverse="true" lazy="false"
+ cascade="all-delete-orphan" access="field">
+ <key column="refer" on-delete="cascade"/>
+ <one-to-many class="org.splat.dal.bo.kernel.Relation" />
+ </set> -->
+ </class>
</hibernate-mapping>
\ No newline at end of file
public abstract class Persistent {
- private long rid; // Primary key of persistent objects
+ /**
+ * Primary key of persistent objects.
+ */
+ private long rid;
+ /**
+ * UUID of the object used for identification in equals() and in hashCode().
+ */
+ private String _uid = IdGenerator.createId();
protected abstract static class Properties implements ObjectProperties {
private long rid; // Primary key of persistent objects
* @param rid
* the rid to set
*/
- public void setIndex(long rid) {
+ public void setIndex(final long rid) {
this.rid = rid;
}
}
* Database fetch constructor.
*/
protected Persistent() {
- // -----------------------
rid = 0; // Set when loading the object
}
* Checks the mutual compatibility of arguments previously set in the given properties object, if the validity check is enabled. As this
* validity depends on concrete classes, the check is delegated to subclasses of the given Persistent.Properties.
*/
- protected Persistent(ObjectProperties oprop)
+ protected Persistent(final ObjectProperties oprop)
throws MissedPropertyException, InvalidPropertyException,
MultiplyDefinedException {
- // ---------------------------------------------
- if (oprop.mustBeChecked())
+ if (oprop.mustBeChecked()) {
oprop.checkValidity(); // Throws one of the above exception if not valid
+ }
rid = 0; // Set when saving the object
}
// Public member functions
// ==============================================================================================================================
- public boolean equals(Object entity) {
- // ------------------------------------
- if (entity == null)
- return false;
- if (entity.getClass().equals(this.getClass())) {
- Persistent object = (Persistent) entity;
- long he = object.getIndex(); // getIndex() is supposed fetching the index if not yet done
- long me = this.getIndex(); // getIndex() is supposed fetching the index if not yet done
- if (me * he != 0)
- return (he == me);
- if (me + he == 0)
- return (this == object);
+ /**
+ * Persistent objects are equal if their UIDs are equal.<BR>
+ * {@inheritDoc}
+ *
+ * @see java.lang.Object#equals(java.lang.Object)
+ */
+ @Override
+ public boolean equals(final Object entity) {
+ boolean res = (entity != null);
+ if (res) {
+ res = Persistent.class.isAssignableFrom(entity.getClass());
+ if (res) {
+ Persistent object = (Persistent) entity;
+ res = getUid().equals(object.getUid());
+ }
}
- return false;
+ return res;
}
/**
* @see isSaved()
*/
public long getIndex() {
- // ----------------------
return rid;
}
* @param anId
* id to set
*/
- public void setIndex(long anId) {
+ public void setIndex(final long anId) {
rid = anId;
}
+ /**
+ * {@inheritDoc}
+ *
+ * @see java.lang.Object#hashCode()
+ */
+ @Override
public int hashCode() {
- // ----------------------
- return toString().hashCode();
+ return getUid().hashCode();
}
/**
* @see getIndex()
*/
public boolean isSaved() {
- // -------------------------
return (getIndex() != 0); // getIndex() is supposed fetching the index if not yet done
}
*
* @return the unique string representation of this object.
*/
+ @Override
public String toString() {
- // -------------------------
- long oid = getIndex(); // getIndex() is supposed fetching the index if not yet done
- if (oid == 0)
- oid = super.hashCode(); // WARNING: Must not call super.toString() as it goes back here (this.toString())
return new StringBuffer("object ").append(getClass().getName()).append(
- "@").append(oid).toString();
+ "@").append(getUid()).append("@").append(getIndex()).toString();
}
/**
* @param rid
* the rid to set
*/
- public void setRid(long rid) {
+ public void setRid(final long rid) {
this.rid = rid;
}
+
+ /**
+ * Get the uid.
+ *
+ * @return the uid
+ */
+ public String getUid() {
+ return _uid;
+ }
+
+ /**
+ * Set the uid.
+ *
+ * @param uid
+ * the uid to set
+ */
+ public void setUid(final String uid) {
+ _uid = uid;
+ }
}
\ No newline at end of file
<many-to-one name="mydoc" column="doc" cascade="merge" access="field" not-null="true"/>
<!-- ProjectElement owner -->
- <many-to-one name="owner" column="owner" access="field" not-null="true" />
+ <many-to-one name="owner" column="owner" cascade="merge" access="field" not-null="true" />
<!-- char isnew -->
<property name="isnew" column="isnew" access="field" not-null="true" />
import org.splat.dal.bo.som.Timestamp;
import org.splat.dal.bo.som.ValidationStep;
import org.splat.dal.bo.som.Document.Properties;
+import org.splat.dal.dao.kernel.RelationDAO;
import org.splat.dal.dao.som.DocumentDAO;
import org.splat.dal.dao.som.DocumentTypeDAO;
import org.splat.dal.dao.som.FileDAO;
* Injected document DAO.
*/
private DocumentDAO _documentDAO;
+ /**
+ * Injected relation DAO.
+ */
+ private RelationDAO _relationDAO;
/**
* Injected document type DAO.
*/
.append(aDoc.getFile().getFormat()) // File name and extension
.toString();
aDoc.getFile().changePath(path);
-// owner = getStudyDAO().merge(owner);
+ owner = getStudyDAO().merge(owner);
// getStudyDAO().update(owner);
}
* the format
* @return the created "Converts" relation
*/
+ @Transactional
public ConvertsRelation attach(final Document aDoc, final String format) {
return attach(aDoc, format, null);
}
ConvertsRelation attach = new ConvertsRelation(aDoc, export,
description);
- // RKV session.save(export);
- // RKV session.save(attach);
-
getFileDAO().create(export);
+ getRelationDAO().create(attach);
- // RKV aDoc.addRelation(attach); // Updates this
- aDoc.getAllRelations().add(attach); // Updates this //RKV
-
+ aDoc.getAllRelations().add(attach);
+ getDocumentDAO().merge(aDoc);
+
return attach;
}
_studyDAO = studyDAO;
}
+ /**
+ * Get the relationDAO.
+ * @return the relationDAO
+ */
+ public RelationDAO getRelationDAO() {
+ return _relationDAO;
+ }
+
+ /**
+ * Set the relationDAO.
+ * @param relationDAO the relationDAO to set
+ */
+ public void setRelationDAO(final RelationDAO relationDAO) {
+ _relationDAO = relationDAO;
+ }
+
}
* the format
* @return the created "Converts" relation
*/
+ @Transactional
public ConvertsRelation attach(final Publication aPublication,
final String format) {
return getDocumentService().attach(aPublication.value(), format);
* the description of the relation
* @return the created "Converts" relation
*/
+ @Transactional
public ConvertsRelation attach(final Publication aPublication,
final String format, final String description) {
return getDocumentService().attach(aPublication.value(), format,
import org.splat.dal.bo.som.DocumentType;
import org.splat.dal.bo.som.File;
import org.splat.dal.bo.som.KnowledgeElement;
-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;
}
// Identification and save
- aStep.getOwnerStudy().setLastLocalIndex(
- dprop.getOwner().getOwnerStudy().getLastLocalIndex());
if (LOG.isDebugEnabled()) {
LOG.debug("Local index after: "
- + dprop.getOwner().getOwnerStudy().getLastLocalIndex());
+ + aStep.getOwnerStudy().getLastLocalIndex());
}
getDocumentService().buildReferenceFrom(newdoc, aStep.getOwnerStudy());
getDocumentDAO().create(newdoc);
*/
public boolean remove(final Step aStep, final Publication oldoc) {
aStep.getDocuments().remove(oldoc); // Updates this step
- // Synchronize with database
- ProjectElement owner = getProjectElementDAO().merge(aStep.getOwner());
- if (owner != null) {
- aStep.getOwner().remove(oldoc); // in transient copy
- owner.remove(oldoc); // in persistent copy
- }
+ aStep.getOwner().remove(oldoc); // remove from the parent project element
+ getProjectElementDAO().merge(aStep.getOwner());
getDocumentService().release(oldoc.value()); // Decrements the configuration tag count of document
// The publication becoming orphan, it should automatically be removed from the database when updating of owner scenario.
return true;
Document value = torem.value();
if (!value.isPublished() && !value.isVersioned()) { // The referenced document is no more used
List<Document> using = new ArrayList<Document>();
- List<Relation> converts = new ArrayList<Relation>();
+ List<File> files = new ArrayList<File>();
for (Relation link : value.getAllRelations()) {
if (link.getClass().equals(ConvertsRelation.class)) { // File conversion
- converts.add(link);
+ files.add((File) link.getTo());
} else if (link.getClass().equals(UsesRelation.class)) { // Document dependency
using.add((Document) link.getTo());
}
}
- // value.getAllRelations().removeAll(converts);
// Remove relations from depending documents
if (LOG.isDebugEnabled()) {
LOG.debug("Remove " + using.size() + " UsedByRelation(s).");
if (LOG.isDebugEnabled()) {
LOG.debug("Remove UsedByRelation from "
+ doc.getTitle() + " to " + value.getTitle());
+ LOG.debug("Nb relations of doc " + doc.getTitle()
+ + " before: " + doc.getAllRelations().size());
}
doc.removeRelation(UsedByRelation.class, value);
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("Nb relations of doc " + doc.getTitle()
+ + " after: " + doc.getAllRelations().size());
+ }
getDocumentDAO().merge(doc);
}
- value = getPublicationDAO().merge(torem).value();
// Synchronize deleted objects with the database to avoid hibernate exception
- // org.hibernate.PropertyValueException: not-null property references a null or transient value:
- // org.splat.dal.bo.som.UsedByRelation.refer
- getDocumentDAO().flush(); // To show to the database that files from ConvertsRelation(s) are deleted already
- getDocumentDAO().delete(value); // The corresponding physical file is not removed from the vault
+ // org.hibernate.PropertyValueException: not-null property references a null or transient value
+ getDocumentDAO().flush();
+ // The corresponding physical file is not removed from the vault
+ getDocumentDAO().delete(getDocumentDAO().merge(torem.value()));
// Delete document's files
- for (Relation link : converts) {
- File file = (File) link.getTo();
- getFileDAO().delete(file); // The corresponding physical file is not removed from the vault
+ for (File file : files) {
+ getFileDAO().delete(getFileDAO().merge(file)); // The corresponding physical file is not removed from the vault
}
}
}
<property name="documentDAO" ref="documentDAO" />
<property name="documentTypeDAO" ref="documentTypeDAO" />
<property name="repositoryService" ref="repositoryService" />
- <property name="fileDAO" ref="fileDAO" />
+ <property name="fileDAO" ref="fileDAO" />
+ <property name="relationDAO" ref="relationDAO" />
<property name="studyDAO" ref="studyDAO" />
</bean>
import java.util.Map;
import org.splat.dal.bo.kernel.User;
+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.ProgressState;
steps.addAll(Arrays.asList(studySteps));
steps.addAll(Arrays.asList(scSteps));
steps.addAll(Arrays.asList(studySteps));
- for (org.splat.som.Step step: steps) {
+ for (org.splat.som.Step step : steps) {
LOG.debug("Create a document for the step " + step.getNumber());
- List<DocumentType> dtypes = _documentTypeService
- .selectTypesOf(step.getStep());
+ List<DocumentType> dtypes = _documentTypeService.selectTypesOf(step
+ .getStep());
if (dtypes.size() > 0) {
DocumentType dtype = dtypes.get(0);
int oldInd = ht.get(Study.class, aStudyFound.getIndex())
LOG.debug(">>>>> END testCreateDoc()");
}
+ /**
+ * Test of file attaching to a study document.<BR>
+ * <B>Description :</B> <BR>
+ * <i>Create a study and try to attach a new file to its each document.</i><BR>
+ * <B>Action : </B><BR>
+ * <i>1. call attach method for each document publication of the study.</i><BR>
+ * <B>Test data : </B><BR>
+ * <i>no input parameters</i><BR>
+ *
+ * <B>Outcome results:</B><BR>
+ * <i>
+ * <ul>
+ * <li>The new ConvertsRelation and the new File object must be created in the database.<BR>
+ * </li>
+ * </ul>
+ * </i>
+ *
+ * @throws InvalidPropertyException
+ * if an invalid property is used when creating objects
+ * @throws MultiplyDefinedException
+ * when trying to create an object with already existing id
+ * @throws MissedPropertyException
+ * if a mandatory property is not defined for an object to be created
+ * @throws SQLException
+ * if test study creation is failed
+ * @throws IOException
+ * if test study creation is failed
+ * @throws ParseException
+ * @throws InterruptedException
+ * @throws NotApplicableException
+ *
+ */
+ @Test
+ public void testAttach() throws InvalidPropertyException,
+ MissedPropertyException, MultiplyDefinedException, IOException,
+ SQLException, NotApplicableException, InterruptedException,
+ ParseException {
+ LOG.debug(">>>>> BEGIN testAttach()");
+ startNestedTransaction();
+
+ HibernateTemplate ht = getHibernateTemplate();
+ Study aStudy = createStudy();
+ // Call DAO's create method for a good transient study.
+ Long id = aStudy.getIndex();
+ Assert.assertNotNull(id,
+ "Create method returns null instead of a new id.");
+ Assert.assertTrue(id > 0, "The new id is not a positive number.");
+
+ // Call DAO's get method for an existing id.
+ _studyDAO.flush();
+ getHibernateTemplate().evict(aStudy);
+ getHibernateTemplate().clear();
+ Study aStudyFound = _studyDAO.get(id);
+ ht.clear();
+ ht.evict(aStudyFound);
+
+ long userId = aStudyFound.getAuthor().getIndex();
+ org.splat.som.Step[] studySteps = _projectElementService
+ .getSteps(aStudyFound);
+ org.splat.som.Step[] scSteps = _projectElementService
+ .getSteps(aStudyFound.getScenarii()[0]);
+
+ List<org.splat.som.Step> steps = new ArrayList<org.splat.som.Step>();
+ steps.addAll(Arrays.asList(studySteps));
+ steps.addAll(Arrays.asList(scSteps));
+ steps.addAll(Arrays.asList(studySteps));
+ for (org.splat.som.Step step : steps) {
+ LOG.debug("Attach a new .py file to documents of the step "
+ + step.getNumber() + ": " + step.getStep().getKey() + ": "
+ + step.getOwner().getClass().getSimpleName());
+
+ for (Publication pub : step.getAllDocuments()) {
+
+ ht.evict(step.getOwner());
+ ht.evict(pub);
+ ht.evict(pub.value());
+ int nbConverts = ht.find("from ConvertsRelation").size();
+ int nbDocConverts = ht.find("from ConvertsRelation where owner="
+ + pub.value().getIndex()).size();
+ int nbFiles = ht.find("from File").size();
+
+ ConvertsRelation rel = _publicationService.attach(pub, "py");
+
+ _studyDAO.flush();
+ ht.flush();
+ Assert.assertNotNull(rel,
+ "Returned ConvertsRelation must not be null.");
+ Assert
+ .assertTrue(rel.isSaved(),
+ "Returned ConvertsRelation must be saved in the database.");
+ Assert.assertEquals(ht
+ .find("from ConvertsRelation where owner="
+ + pub.value().getIndex()).size(), nbDocConverts + 1,
+ "Number of created ConvertsRelations must be 1.");
+ Assert.assertEquals(ht
+ .find("from ConvertsRelation").size(), nbConverts + 1,
+ "Number of created ConvertsRelations must be 1.");
+ Assert.assertNotNull(rel.getTo(),
+ "Attached File must not be null.");
+ Assert.assertTrue(rel.isSaved(),
+ "Attached File must be saved in the database.");
+ Assert.assertEquals(ht
+ .find("from File where rid="
+ + rel.getTo().getIndex()).size(), 1,
+ "Number of created File must be 1.");
+ Assert.assertEquals(ht
+ .find("from File").size(), nbFiles + 1,
+ "Number of created Files must be 1.");
+ }
+ }
+
+ rollbackNestedTransaction();
+ LOG.debug(">>>>> END testAttach()");
+ }
+
/**
* Get path to the user's downloads directory. The directory is created if it is not exist yet.
*
import java.util.Map;
import org.splat.dal.bo.kernel.User;
+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.File;
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.UsesRelation;
import org.splat.dal.bo.som.Document.Properties;
import org.splat.dal.dao.som.Database;
+import org.splat.dal.dao.som.FileDAO;
import org.splat.dal.dao.som.ScenarioDAO;
import org.splat.exception.BusinessException;
import org.splat.exception.DocumentIsUsedException;
@Qualifier("scenarioDAO")
private transient ScenarioDAO _scenarioDAO;
+ /**
+ * The File DAO. Later injected by Spring.
+ */
+ @Autowired
+ @Qualifier("fileDAO")
+ private transient FileDAO _fileDAO;
+
/**
* The PublicationService. Later injected by Spring.
*/
if (aScStep.getDocuments().size() > 0) {
docId = aScStep.getDocuments().get(0).value().getIndex();
ht.flush();
+
List<UsesRelation> uses = ht
.find("from UsesRelation where owner=" + docId);
List<UsedByRelation> usedBy = ht
Assert.assertEquals(ht.find("from Document where rid=" + docId)
.size(), 1, "Nothing to delete.");
+
+ ht.evict(aScStep.getDocuments().get(0).value()
+ .getFile());
+ LOG.debug("Load file#" + aScStep.getDocuments().get(0).value()
+ .getRelations(ConvertsRelation.class).get(0).getTo().getIndex());
+
+ ht.clear();
+ File f = _fileDAO.get(aScStep.getDocuments().get(0).value()
+ .getRelations(ConvertsRelation.class).get(0).getTo().getIndex());
+ ht.evict(aScStep.getDocuments().get(0).value());
+
ok = _stepService.removeDocument(aScStep, docId);
nbRemovedDoc++;
- nbRemovedDoc,
"Documents were not removed from the database.");
- Assert
- .assertEquals(ht.find("from File").size(), 0,
+ Assert.assertEquals(ht.find("from File").size(), 0,
"Files were not removed from the database.");
-
+
Assert.assertEquals(ht.find(
"from Publication where owner=" + aScen.getIndex()).size(), 0,
"Publications were not removed from the database.");
+++ /dev/null
-package org.splat.module;
-
-import java.io.File;
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Set;
-
-import org.hibernate.HibernateException;
-import org.hibernate.Session;
-import org.hibernate.Transaction;
-import org.splat.dal.bo.kernel.User;
-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.ProgressState;
-import org.splat.dal.bo.som.Publication;
-import org.splat.dal.bo.som.SimulationContext;
-import org.splat.dal.bo.som.SimulationContextType;
-import org.splat.dal.dao.som.Database;
-import org.splat.kernel.Do;
-import org.splat.service.DocumentTypeService;
-import org.splat.service.PublicationService;
-import org.splat.service.ScenarioService;
-import org.splat.service.SimulationContextService;
-import org.splat.service.StepService;
-import org.splat.service.technical.RepositoryService;
-import org.splat.simer.Action;
-import org.splat.simer.OpenStudy;
-import org.splat.som.Step;
-
-public class SaveDocumentAction extends Action {
-
- /**
- * Serial version ID.
- */
- private static final long serialVersionUID = -3364960833373200115L;
-
- /**
- * Current open study.
- */
- private transient OpenStudy _mystudy = null;
- private transient int _doctype = 0;
- private transient String _filename = null;
- private transient String _docname = null;
- private transient ProgressState _state = null;
- private transient List<Document> _defuses = null;
- private String _description = null; // Summary of changes in the new version
- /**
- * Injected scenario service.
- */
- private ScenarioService _scenarioService;
- /**
- * Injected publication service.
- */
- private PublicationService _publicationService;
- /**
- * Injected step service.
- */
- private StepService _stepService;
- /**
- * Injected document type service.
- */
- private DocumentTypeService _documentTypeService;
- /**
- * Injected repository service.
- */
- private RepositoryService _repositoryService;
- /**
- * Injected simulation context service.
- */
- private SimulationContextService _simulationContextService;
-
- // ==============================================================================================================================
- // Action methods
- // ==============================================================================================================================
-
- public String doSave() {
- // -----------------------
- Session connex = Database.getCurSession();
- Transaction transax = connex.beginTransaction();
- try {
- // Getting user inputs
- _mystudy = getOpenStudy();
- User user = getConnectedUser();
- Step step = _mystudy.getSelectedStep();
- DocumentType type = getDocumentTypeService().selectType(_doctype);
- // File updir = Database.getDownloadDirectory(user);
- // File upfile = new File(updir.getPath() + "/" + filename);
- String upath = getRepositoryService().getTemplatePath(); // Instead of DownloadDirectory for sharing the "uploaded" file
- // between users
- File upfile = new File(upath + _filename);
- String[] table = _filename.split("\\x2E");
- String format = table[table.length - 1];
-
- // Creation of the document
- getScenarioService().checkin(step.getOwner().getIndex()); // Modules necessarily save their data in a scenario step
- connex.flush();
-
- Document.Properties dprop = new Document.Properties();
- Publication credoc = getStepService().createDocument(
- step,
- dprop.setName(_docname).setType(type).setFormat(format)
- .setAuthor(user));
- // Writing the uploaded file into the created document
- File target = credoc.getSourceFile().asFile();
- if (target.exists()) {
- target.delete();
- }
- Do.copy(upfile, target); // Instead of rename for keeping the "uploaded" file for further use
- // upfile.renameTo(target);
-
- // Saving the document in given state
- getPublicationService().saveAs(credoc, _state);
-
- // Creation of default uses relations
- _defuses = new ArrayList<Document>();
- setupDefaultUses(type); // Recursive function
- for (Iterator<Document> i = _defuses.iterator(); i.hasNext();) {
- credoc.addDependency(i.next());
- }
-
- // Execution of module specific operations
-
- // 1. Conversion of the document to internal format, if required
- // TODO: The following code is temporary, waiting for the support of converters
- if ("part".equals(format)) {
- ConvertsRelation export = getPublicationService().attach(
- credoc, "brep");
-
- target = export.getTo().asFile();
- if (target.exists()) {
- target.delete();
- }
- Do.copy(upfile, target); // Instead of rename for keeping the "uploaded" file for further use
- }
- // 2. Addition of simulation contexts
- if ("model".equals(type)) { // Set the characteristics of the mesh
- SimulationContext.Properties cprop = new SimulationContext.Properties();
- SimulationContextType ctype = getSimulationContextService()
- .selectType("model");
- SimulationContext context = getSimulationContextService()
- .selectSimulationContext(ctype, "Éléments finis");
- if (context == null) {
- getStepService().addSimulationContext(step,
- cprop.setType(ctype).setValue("Éléments finis"));
- } else {
- getStepService().addSimulationContext(step, context);
- }
- ctype = getSimulationContextService().selectType("element");
- context = getSimulationContextService()
- .selectSimulationContext(ctype, "Surfacique");
- if (context == null) {
- getStepService().addSimulationContext(step,
- cprop.setType(ctype).setValue("Surfacique"));
- } else {
- getStepService().addSimulationContext(step, context);
- }
- ctype = getSimulationContextService().selectType("shape");
- context = getSimulationContextService()
- .selectSimulationContext(ctype, "Triangles");
- if (context == null) {
- getStepService().addSimulationContext(step,
- cprop.setType(ctype).setValue("Triangles"));
- } else {
- getStepService().addSimulationContext(step, context);
- }
- }
- // Update of the open study
- // mystudy.add(credoc); // Useless while the SIMER page need to be refreshed manually
- getMenu("study").selects(_mystudy.getSelection()); // Updates the menu icon, in case of first added document
-
- transax.commit();
- return SUCCESS;
- } catch (Exception saverror) {
- LOG.error("Reason:", saverror);
- if (transax != null && transax.isActive()) {
- // Second try-catch as the rollback could fail as well
- try {
- transax.rollback();
- } catch (HibernateException backerror) {
- LOG.debug("Error rolling back transaction", backerror);
- }
- }
- return ERROR;
- }
- }
-
- /**
- * Get the publicationService.
- *
- * @return publicationService
- */
- private PublicationService getPublicationService() {
- return _publicationService;
- }
-
- /**
- * Set the publicationService.
- *
- * @param publicationService
- * the publicationService to set
- */
- public void setPublicationService(
- final PublicationService publicationService) {
- _publicationService = publicationService;
- }
-
- /**
- * Get the scenarioService.
- *
- * @return scenarioService
- */
- public ScenarioService getScenarioService() {
- return _scenarioService;
- }
-
- /**
- * Set the scenarioService.
- *
- * @param scenarioService
- * the scenarioService to set
- */
- public void setScenarioService(final ScenarioService scenarioService) {
- _scenarioService = scenarioService;
- }
-
- /**
- * Get the stepService.
- *
- * @return the stepService
- */
- public StepService getStepService() {
- return _stepService;
- }
-
- /**
- * Set the stepService.
- *
- * @param stepService
- * the stepService to set
- */
- public void setStepService(final StepService stepService) {
- _stepService = stepService;
- }
-
- public String doUpdate() {
- // -------------------------
- return SUCCESS;
- }
-
- public String doVersion() {
- // --------------------------
- Session connex = Database.getCurSession();
- Transaction transax = connex.beginTransaction();
- try {
- // Getting user inputs
- _mystudy = getOpenStudy();
- User user = getConnectedUser();
- Step step = _mystudy.getSelectedStep();
- // File updir = Database.getDownloadDirectory(user);
- // File upfile = new File(updir.getPath() + "/" + filename);
- String upath = getRepositoryService().getTemplatePath(); // Instead of DownloadDirectory for sharing the "uploaded" file
- // between users
- File upfile = new File(upath + _filename);
- String[] table = _filename.split("\\x2E");
- String format = table[table.length - 1];
-
- // Versioning of the document
- Publication current = _mystudy.getSelectedDocument();
- Document.Properties dprop = new Document.Properties();
- dprop.setAuthor(user);
- if (_description.length() > 0) {
- dprop.setDescription(_description);
- }
-
- Publication next = getStepService().versionDocument(step, current,
- dprop);
-
- // Writing the uploaded file into the created document
- File target = next.getSourceFile().asFile();
- if (target.exists()) {
- target.delete();
- }
- Do.copy(upfile, target); // Instead of rename for keeping the "uploaded" file for further use
- // upfile.renameTo(target);
-
- // Saving the document in given state
- getPublicationService().saveAs(next, _state);
-
- // Creation of default uses relations
- _defuses = new ArrayList<Document>();
- setupDefaultUses(next.value().getType()); // Recursive function
- for (Iterator<Document> i = _defuses.iterator(); i.hasNext();) {
- next.addDependency(i.next());
- }
- // TODO: Outdating impacted document
-
- // Execution of module specific operations
-
- // 1. Conversion of the document to internal format, if required
- // TODO: The following code is temporary, waiting for the support of converters
- if ("part".equals(format)) {
- ConvertsRelation export = getPublicationService().attach(next,
- "brep");
- String fname = table[0];
-
- for (int i = 1; i < table.length - 1; i++) {
- fname = fname + table[i];
- }
- upfile = new File(upath + fname + ".brep");
- upfile.renameTo(export.getTo().asFile());
- }
-
- // Update of the open study
- // mystudy.setSelection(mystudy.getSelection()); // Rebuild the presentation
-
- transax.commit();
- return SUCCESS;
- } catch (Exception saverror) {
- LOG.error("Reason:", saverror);
- if (transax != null && transax.isActive()) {
- // Second try-catch as the rollback could fail as well
- try {
- transax.rollback();
- } catch (HibernateException backerror) {
- LOG.debug("Error rolling back transaction", backerror);
- }
- }
- return ERROR;
- }
- }
-
- // ==============================================================================================================================
- // Getters and setters
- // ==============================================================================================================================
-
- public String getDescription() {
- // -------------------------------
- return _description;
- }
-
- public void setDescription(final String summary) {
- // -------------------------------------------
- this._description = summary;
- }
-
- public void setDocumentName(final String name) {
- // -----------------------------------------
- this._docname = name;
- }
-
- public void setDocumentState(final String state) {
- // -------------------------------------------
- this._state = ProgressState.valueOf(state);
- }
-
- public void setDocumentType(final String value) {
- // ------------------------------------------
- this._doctype = Integer.valueOf(value);
- }
-
- public void setFileName(final String name) {
- // -------------------------------------
- this._filename = name;
- }
-
- // ==============================================================================================================================
- // Private service
- // ==============================================================================================================================
-
- private void setupDefaultUses(final DocumentType type) {
- Set<DocumentType> uses = type.getDefaultUses();
-
- for (Iterator<DocumentType> i = uses.iterator(); i.hasNext();) {
- DocumentType usetype = i.next();
- List<Document> usedoc = _mystudy.collectInvolvedDocuments(usetype);
- if (usedoc.isEmpty()) {
- setupDefaultUses(usetype);
- } else {
- _defuses.addAll(usedoc);
- }
- }
- }
-
- /**
- * Get the repositoryService.
- *
- * @return the repositoryService
- */
- public RepositoryService getRepositoryService() {
- return _repositoryService;
- }
-
- /**
- * Set the repositoryService.
- *
- * @param repositoryService
- * the repositoryService to set
- */
- public void setRepositoryService(final RepositoryService repositoryService) {
- _repositoryService = repositoryService;
- }
-
- /**
- * Get the simulationContextService.
- *
- * @return the simulationContextService
- */
- public SimulationContextService getSimulationContextService() {
- return _simulationContextService;
- }
-
- /**
- * Set the simulationContextService.
- *
- * @param simulationContextService
- * the simulationContextService to set
- */
- public void setSimulationContextService(
- final SimulationContextService simulationContextService) {
- _simulationContextService = simulationContextService;
- }
-
- /**
- * Get the documentTypeService.
- *
- * @return the documentTypeService
- */
- public DocumentTypeService getDocumentTypeService() {
- return _documentTypeService;
- }
-
- /**
- * Set the documentTypeService.
- *
- * @param documentTypeService
- * the documentTypeService to set
- */
- public void setDocumentTypeService(
- final DocumentTypeService documentTypeService) {
- _documentTypeService = documentTypeService;
- }
-}
\ No newline at end of file
scope="prototype">
</bean>
- <bean id="saveDocumentAction"
- class="org.splat.module.SaveDocumentAction" scope="prototype">
- <property name="documentTypeService" ref="documentTypeService" />
- <property name="publicationService" ref="publicationService" />
- <property name="repositoryService" ref="repositoryService" />
- <property name="scenarioService" ref="scenarioService" />
- <property name="stepService" ref="stepService" />
- <property name="simulationContextService"
- ref="simulationContextService" />
- </bean>
-
</beans>
</action>
</package>
- <package name="sgeom" namespace="/sgeom" extends="simer-default">
-
- <action name="valid-save" class="saveDocumentAction"
- method="save">
- <result name="success">/sgeom/index.jsp</result>
- </action>
- <action name="valid-update" class="saveDocumentAction"
- method="update">
- <result name="success">/sgeom/index.jsp</result>
- </action>
- <action name="valid-version" class="saveDocumentAction"
- method="version">
- <result name="success">/sgeom/index.jsp</result>
- </action>
-
- </package>
-
-
- <package name="smesh" namespace="/smesh" extends="simer-default">
-
- <action name="valid-save" class="saveDocumentAction"
- method="save">
- <result name="success">/smesh/index.jsp</result>
- </action>
- <action name="valid-update" class="saveDocumentAction"
- method="update">
- <result name="success">/smesh/index.jsp</result>
- </action>
- <action name="valid-version" class="saveDocumentAction"
- method="version">
- <result name="success">/smesh/index.jsp</result>
- </action>
-
- </package>
</struts>
\ No newline at end of file